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, 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, has_more_lines) = crate::inline_completion_edit_text(
 5988                    &snapshot,
 5989                    &edits,
 5990                    edit_preview.as_ref()?,
 5991                    true,
 5992                    cx,
 5993                )
 5994                .first_line_preview();
 5995
 5996                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 5997                    .with_highlights(&style.text, highlighted_edits.highlights);
 5998
 5999                let preview = h_flex()
 6000                    .gap_1()
 6001                    .min_w_16()
 6002                    .child(styled_text)
 6003                    .when(has_more_lines, |parent| parent.child(""));
 6004
 6005                let left = if first_edit_row != cursor_point.row {
 6006                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6007                        .into_any_element()
 6008                } else {
 6009                    Icon::new(IconName::ZedPredict).into_any_element()
 6010                };
 6011
 6012                Some(
 6013                    h_flex()
 6014                        .h_full()
 6015                        .flex_1()
 6016                        .gap_2()
 6017                        .pr_1()
 6018                        .overflow_x_hidden()
 6019                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6020                        .child(left)
 6021                        .child(preview),
 6022                )
 6023            }
 6024        }
 6025    }
 6026
 6027    fn render_context_menu(
 6028        &self,
 6029        style: &EditorStyle,
 6030        max_height_in_lines: u32,
 6031        y_flipped: bool,
 6032        window: &mut Window,
 6033        cx: &mut Context<Editor>,
 6034    ) -> Option<AnyElement> {
 6035        let menu = self.context_menu.borrow();
 6036        let menu = menu.as_ref()?;
 6037        if !menu.visible() {
 6038            return None;
 6039        };
 6040        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6041    }
 6042
 6043    fn render_context_menu_aside(
 6044        &self,
 6045        style: &EditorStyle,
 6046        max_size: Size<Pixels>,
 6047        cx: &mut Context<Editor>,
 6048    ) -> Option<AnyElement> {
 6049        self.context_menu.borrow().as_ref().and_then(|menu| {
 6050            if menu.visible() {
 6051                menu.render_aside(
 6052                    style,
 6053                    max_size,
 6054                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6055                    cx,
 6056                )
 6057            } else {
 6058                None
 6059            }
 6060        })
 6061    }
 6062
 6063    fn hide_context_menu(
 6064        &mut self,
 6065        window: &mut Window,
 6066        cx: &mut Context<Self>,
 6067    ) -> Option<CodeContextMenu> {
 6068        cx.notify();
 6069        self.completion_tasks.clear();
 6070        let context_menu = self.context_menu.borrow_mut().take();
 6071        self.stale_inline_completion_in_menu.take();
 6072        self.update_visible_inline_completion(window, cx);
 6073        context_menu
 6074    }
 6075
 6076    fn show_snippet_choices(
 6077        &mut self,
 6078        choices: &Vec<String>,
 6079        selection: Range<Anchor>,
 6080        cx: &mut Context<Self>,
 6081    ) {
 6082        if selection.start.buffer_id.is_none() {
 6083            return;
 6084        }
 6085        let buffer_id = selection.start.buffer_id.unwrap();
 6086        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6087        let id = post_inc(&mut self.next_completion_id);
 6088
 6089        if let Some(buffer) = buffer {
 6090            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6091                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6092            ));
 6093        }
 6094    }
 6095
 6096    pub fn insert_snippet(
 6097        &mut self,
 6098        insertion_ranges: &[Range<usize>],
 6099        snippet: Snippet,
 6100        window: &mut Window,
 6101        cx: &mut Context<Self>,
 6102    ) -> Result<()> {
 6103        struct Tabstop<T> {
 6104            is_end_tabstop: bool,
 6105            ranges: Vec<Range<T>>,
 6106            choices: Option<Vec<String>>,
 6107        }
 6108
 6109        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6110            let snippet_text: Arc<str> = snippet.text.clone().into();
 6111            buffer.edit(
 6112                insertion_ranges
 6113                    .iter()
 6114                    .cloned()
 6115                    .map(|range| (range, snippet_text.clone())),
 6116                Some(AutoindentMode::EachLine),
 6117                cx,
 6118            );
 6119
 6120            let snapshot = &*buffer.read(cx);
 6121            let snippet = &snippet;
 6122            snippet
 6123                .tabstops
 6124                .iter()
 6125                .map(|tabstop| {
 6126                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6127                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6128                    });
 6129                    let mut tabstop_ranges = tabstop
 6130                        .ranges
 6131                        .iter()
 6132                        .flat_map(|tabstop_range| {
 6133                            let mut delta = 0_isize;
 6134                            insertion_ranges.iter().map(move |insertion_range| {
 6135                                let insertion_start = insertion_range.start as isize + delta;
 6136                                delta +=
 6137                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6138
 6139                                let start = ((insertion_start + tabstop_range.start) as usize)
 6140                                    .min(snapshot.len());
 6141                                let end = ((insertion_start + tabstop_range.end) as usize)
 6142                                    .min(snapshot.len());
 6143                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6144                            })
 6145                        })
 6146                        .collect::<Vec<_>>();
 6147                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6148
 6149                    Tabstop {
 6150                        is_end_tabstop,
 6151                        ranges: tabstop_ranges,
 6152                        choices: tabstop.choices.clone(),
 6153                    }
 6154                })
 6155                .collect::<Vec<_>>()
 6156        });
 6157        if let Some(tabstop) = tabstops.first() {
 6158            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6159                s.select_ranges(tabstop.ranges.iter().cloned());
 6160            });
 6161
 6162            if let Some(choices) = &tabstop.choices {
 6163                if let Some(selection) = tabstop.ranges.first() {
 6164                    self.show_snippet_choices(choices, selection.clone(), cx)
 6165                }
 6166            }
 6167
 6168            // If we're already at the last tabstop and it's at the end of the snippet,
 6169            // we're done, we don't need to keep the state around.
 6170            if !tabstop.is_end_tabstop {
 6171                let choices = tabstops
 6172                    .iter()
 6173                    .map(|tabstop| tabstop.choices.clone())
 6174                    .collect();
 6175
 6176                let ranges = tabstops
 6177                    .into_iter()
 6178                    .map(|tabstop| tabstop.ranges)
 6179                    .collect::<Vec<_>>();
 6180
 6181                self.snippet_stack.push(SnippetState {
 6182                    active_index: 0,
 6183                    ranges,
 6184                    choices,
 6185                });
 6186            }
 6187
 6188            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6189            if self.autoclose_regions.is_empty() {
 6190                let snapshot = self.buffer.read(cx).snapshot(cx);
 6191                for selection in &mut self.selections.all::<Point>(cx) {
 6192                    let selection_head = selection.head();
 6193                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6194                        continue;
 6195                    };
 6196
 6197                    let mut bracket_pair = None;
 6198                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6199                    let prev_chars = snapshot
 6200                        .reversed_chars_at(selection_head)
 6201                        .collect::<String>();
 6202                    for (pair, enabled) in scope.brackets() {
 6203                        if enabled
 6204                            && pair.close
 6205                            && prev_chars.starts_with(pair.start.as_str())
 6206                            && next_chars.starts_with(pair.end.as_str())
 6207                        {
 6208                            bracket_pair = Some(pair.clone());
 6209                            break;
 6210                        }
 6211                    }
 6212                    if let Some(pair) = bracket_pair {
 6213                        let start = snapshot.anchor_after(selection_head);
 6214                        let end = snapshot.anchor_after(selection_head);
 6215                        self.autoclose_regions.push(AutocloseRegion {
 6216                            selection_id: selection.id,
 6217                            range: start..end,
 6218                            pair,
 6219                        });
 6220                    }
 6221                }
 6222            }
 6223        }
 6224        Ok(())
 6225    }
 6226
 6227    pub fn move_to_next_snippet_tabstop(
 6228        &mut self,
 6229        window: &mut Window,
 6230        cx: &mut Context<Self>,
 6231    ) -> bool {
 6232        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6233    }
 6234
 6235    pub fn move_to_prev_snippet_tabstop(
 6236        &mut self,
 6237        window: &mut Window,
 6238        cx: &mut Context<Self>,
 6239    ) -> bool {
 6240        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6241    }
 6242
 6243    pub fn move_to_snippet_tabstop(
 6244        &mut self,
 6245        bias: Bias,
 6246        window: &mut Window,
 6247        cx: &mut Context<Self>,
 6248    ) -> bool {
 6249        if let Some(mut snippet) = self.snippet_stack.pop() {
 6250            match bias {
 6251                Bias::Left => {
 6252                    if snippet.active_index > 0 {
 6253                        snippet.active_index -= 1;
 6254                    } else {
 6255                        self.snippet_stack.push(snippet);
 6256                        return false;
 6257                    }
 6258                }
 6259                Bias::Right => {
 6260                    if snippet.active_index + 1 < snippet.ranges.len() {
 6261                        snippet.active_index += 1;
 6262                    } else {
 6263                        self.snippet_stack.push(snippet);
 6264                        return false;
 6265                    }
 6266                }
 6267            }
 6268            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6269                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6270                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6271                });
 6272
 6273                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6274                    if let Some(selection) = current_ranges.first() {
 6275                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6276                    }
 6277                }
 6278
 6279                // If snippet state is not at the last tabstop, push it back on the stack
 6280                if snippet.active_index + 1 < snippet.ranges.len() {
 6281                    self.snippet_stack.push(snippet);
 6282                }
 6283                return true;
 6284            }
 6285        }
 6286
 6287        false
 6288    }
 6289
 6290    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6291        self.transact(window, cx, |this, window, cx| {
 6292            this.select_all(&SelectAll, window, cx);
 6293            this.insert("", window, cx);
 6294        });
 6295    }
 6296
 6297    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6298        self.transact(window, cx, |this, window, cx| {
 6299            this.select_autoclose_pair(window, cx);
 6300            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6301            if !this.linked_edit_ranges.is_empty() {
 6302                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6303                let snapshot = this.buffer.read(cx).snapshot(cx);
 6304
 6305                for selection in selections.iter() {
 6306                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6307                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6308                    if selection_start.buffer_id != selection_end.buffer_id {
 6309                        continue;
 6310                    }
 6311                    if let Some(ranges) =
 6312                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6313                    {
 6314                        for (buffer, entries) in ranges {
 6315                            linked_ranges.entry(buffer).or_default().extend(entries);
 6316                        }
 6317                    }
 6318                }
 6319            }
 6320
 6321            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6322            if !this.selections.line_mode {
 6323                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6324                for selection in &mut selections {
 6325                    if selection.is_empty() {
 6326                        let old_head = selection.head();
 6327                        let mut new_head =
 6328                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6329                                .to_point(&display_map);
 6330                        if let Some((buffer, line_buffer_range)) = display_map
 6331                            .buffer_snapshot
 6332                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6333                        {
 6334                            let indent_size =
 6335                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6336                            let indent_len = match indent_size.kind {
 6337                                IndentKind::Space => {
 6338                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6339                                }
 6340                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6341                            };
 6342                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6343                                let indent_len = indent_len.get();
 6344                                new_head = cmp::min(
 6345                                    new_head,
 6346                                    MultiBufferPoint::new(
 6347                                        old_head.row,
 6348                                        ((old_head.column - 1) / indent_len) * indent_len,
 6349                                    ),
 6350                                );
 6351                            }
 6352                        }
 6353
 6354                        selection.set_head(new_head, SelectionGoal::None);
 6355                    }
 6356                }
 6357            }
 6358
 6359            this.signature_help_state.set_backspace_pressed(true);
 6360            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6361                s.select(selections)
 6362            });
 6363            this.insert("", window, cx);
 6364            let empty_str: Arc<str> = Arc::from("");
 6365            for (buffer, edits) in linked_ranges {
 6366                let snapshot = buffer.read(cx).snapshot();
 6367                use text::ToPoint as TP;
 6368
 6369                let edits = edits
 6370                    .into_iter()
 6371                    .map(|range| {
 6372                        let end_point = TP::to_point(&range.end, &snapshot);
 6373                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6374
 6375                        if end_point == start_point {
 6376                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6377                                .saturating_sub(1);
 6378                            start_point =
 6379                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6380                        };
 6381
 6382                        (start_point..end_point, empty_str.clone())
 6383                    })
 6384                    .sorted_by_key(|(range, _)| range.start)
 6385                    .collect::<Vec<_>>();
 6386                buffer.update(cx, |this, cx| {
 6387                    this.edit(edits, None, cx);
 6388                })
 6389            }
 6390            this.refresh_inline_completion(true, false, window, cx);
 6391            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6392        });
 6393    }
 6394
 6395    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6396        self.transact(window, cx, |this, window, cx| {
 6397            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6398                let line_mode = s.line_mode;
 6399                s.move_with(|map, selection| {
 6400                    if selection.is_empty() && !line_mode {
 6401                        let cursor = movement::right(map, selection.head());
 6402                        selection.end = cursor;
 6403                        selection.reversed = true;
 6404                        selection.goal = SelectionGoal::None;
 6405                    }
 6406                })
 6407            });
 6408            this.insert("", window, cx);
 6409            this.refresh_inline_completion(true, false, window, cx);
 6410        });
 6411    }
 6412
 6413    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6414        if self.move_to_prev_snippet_tabstop(window, cx) {
 6415            return;
 6416        }
 6417
 6418        self.outdent(&Outdent, window, cx);
 6419    }
 6420
 6421    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6422        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6423            return;
 6424        }
 6425
 6426        let mut selections = self.selections.all_adjusted(cx);
 6427        let buffer = self.buffer.read(cx);
 6428        let snapshot = buffer.snapshot(cx);
 6429        let rows_iter = selections.iter().map(|s| s.head().row);
 6430        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6431
 6432        let mut edits = Vec::new();
 6433        let mut prev_edited_row = 0;
 6434        let mut row_delta = 0;
 6435        for selection in &mut selections {
 6436            if selection.start.row != prev_edited_row {
 6437                row_delta = 0;
 6438            }
 6439            prev_edited_row = selection.end.row;
 6440
 6441            // If the selection is non-empty, then increase the indentation of the selected lines.
 6442            if !selection.is_empty() {
 6443                row_delta =
 6444                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6445                continue;
 6446            }
 6447
 6448            // If the selection is empty and the cursor is in the leading whitespace before the
 6449            // suggested indentation, then auto-indent the line.
 6450            let cursor = selection.head();
 6451            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6452            if let Some(suggested_indent) =
 6453                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6454            {
 6455                if cursor.column < suggested_indent.len
 6456                    && cursor.column <= current_indent.len
 6457                    && current_indent.len <= suggested_indent.len
 6458                {
 6459                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6460                    selection.end = selection.start;
 6461                    if row_delta == 0 {
 6462                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6463                            cursor.row,
 6464                            current_indent,
 6465                            suggested_indent,
 6466                        ));
 6467                        row_delta = suggested_indent.len - current_indent.len;
 6468                    }
 6469                    continue;
 6470                }
 6471            }
 6472
 6473            // Otherwise, insert a hard or soft tab.
 6474            let settings = buffer.settings_at(cursor, cx);
 6475            let tab_size = if settings.hard_tabs {
 6476                IndentSize::tab()
 6477            } else {
 6478                let tab_size = settings.tab_size.get();
 6479                let char_column = snapshot
 6480                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6481                    .flat_map(str::chars)
 6482                    .count()
 6483                    + row_delta as usize;
 6484                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6485                IndentSize::spaces(chars_to_next_tab_stop)
 6486            };
 6487            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6488            selection.end = selection.start;
 6489            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6490            row_delta += tab_size.len;
 6491        }
 6492
 6493        self.transact(window, cx, |this, window, cx| {
 6494            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6495            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6496                s.select(selections)
 6497            });
 6498            this.refresh_inline_completion(true, false, window, cx);
 6499        });
 6500    }
 6501
 6502    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6503        if self.read_only(cx) {
 6504            return;
 6505        }
 6506        let mut selections = self.selections.all::<Point>(cx);
 6507        let mut prev_edited_row = 0;
 6508        let mut row_delta = 0;
 6509        let mut edits = Vec::new();
 6510        let buffer = self.buffer.read(cx);
 6511        let snapshot = buffer.snapshot(cx);
 6512        for selection in &mut selections {
 6513            if selection.start.row != prev_edited_row {
 6514                row_delta = 0;
 6515            }
 6516            prev_edited_row = selection.end.row;
 6517
 6518            row_delta =
 6519                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 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        });
 6528    }
 6529
 6530    fn indent_selection(
 6531        buffer: &MultiBuffer,
 6532        snapshot: &MultiBufferSnapshot,
 6533        selection: &mut Selection<Point>,
 6534        edits: &mut Vec<(Range<Point>, String)>,
 6535        delta_for_start_row: u32,
 6536        cx: &App,
 6537    ) -> u32 {
 6538        let settings = buffer.settings_at(selection.start, cx);
 6539        let tab_size = settings.tab_size.get();
 6540        let indent_kind = if settings.hard_tabs {
 6541            IndentKind::Tab
 6542        } else {
 6543            IndentKind::Space
 6544        };
 6545        let mut start_row = selection.start.row;
 6546        let mut end_row = selection.end.row + 1;
 6547
 6548        // If a selection ends at the beginning of a line, don't indent
 6549        // that last line.
 6550        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6551            end_row -= 1;
 6552        }
 6553
 6554        // Avoid re-indenting a row that has already been indented by a
 6555        // previous selection, but still update this selection's column
 6556        // to reflect that indentation.
 6557        if delta_for_start_row > 0 {
 6558            start_row += 1;
 6559            selection.start.column += delta_for_start_row;
 6560            if selection.end.row == selection.start.row {
 6561                selection.end.column += delta_for_start_row;
 6562            }
 6563        }
 6564
 6565        let mut delta_for_end_row = 0;
 6566        let has_multiple_rows = start_row + 1 != end_row;
 6567        for row in start_row..end_row {
 6568            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6569            let indent_delta = match (current_indent.kind, indent_kind) {
 6570                (IndentKind::Space, IndentKind::Space) => {
 6571                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6572                    IndentSize::spaces(columns_to_next_tab_stop)
 6573                }
 6574                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6575                (_, IndentKind::Tab) => IndentSize::tab(),
 6576            };
 6577
 6578            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6579                0
 6580            } else {
 6581                selection.start.column
 6582            };
 6583            let row_start = Point::new(row, start);
 6584            edits.push((
 6585                row_start..row_start,
 6586                indent_delta.chars().collect::<String>(),
 6587            ));
 6588
 6589            // Update this selection's endpoints to reflect the indentation.
 6590            if row == selection.start.row {
 6591                selection.start.column += indent_delta.len;
 6592            }
 6593            if row == selection.end.row {
 6594                selection.end.column += indent_delta.len;
 6595                delta_for_end_row = indent_delta.len;
 6596            }
 6597        }
 6598
 6599        if selection.start.row == selection.end.row {
 6600            delta_for_start_row + delta_for_end_row
 6601        } else {
 6602            delta_for_end_row
 6603        }
 6604    }
 6605
 6606    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6607        if self.read_only(cx) {
 6608            return;
 6609        }
 6610        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6611        let selections = self.selections.all::<Point>(cx);
 6612        let mut deletion_ranges = Vec::new();
 6613        let mut last_outdent = None;
 6614        {
 6615            let buffer = self.buffer.read(cx);
 6616            let snapshot = buffer.snapshot(cx);
 6617            for selection in &selections {
 6618                let settings = buffer.settings_at(selection.start, cx);
 6619                let tab_size = settings.tab_size.get();
 6620                let mut rows = selection.spanned_rows(false, &display_map);
 6621
 6622                // Avoid re-outdenting a row that has already been outdented by a
 6623                // previous selection.
 6624                if let Some(last_row) = last_outdent {
 6625                    if last_row == rows.start {
 6626                        rows.start = rows.start.next_row();
 6627                    }
 6628                }
 6629                let has_multiple_rows = rows.len() > 1;
 6630                for row in rows.iter_rows() {
 6631                    let indent_size = snapshot.indent_size_for_line(row);
 6632                    if indent_size.len > 0 {
 6633                        let deletion_len = match indent_size.kind {
 6634                            IndentKind::Space => {
 6635                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6636                                if columns_to_prev_tab_stop == 0 {
 6637                                    tab_size
 6638                                } else {
 6639                                    columns_to_prev_tab_stop
 6640                                }
 6641                            }
 6642                            IndentKind::Tab => 1,
 6643                        };
 6644                        let start = if has_multiple_rows
 6645                            || deletion_len > selection.start.column
 6646                            || indent_size.len < selection.start.column
 6647                        {
 6648                            0
 6649                        } else {
 6650                            selection.start.column - deletion_len
 6651                        };
 6652                        deletion_ranges.push(
 6653                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6654                        );
 6655                        last_outdent = Some(row);
 6656                    }
 6657                }
 6658            }
 6659        }
 6660
 6661        self.transact(window, cx, |this, window, cx| {
 6662            this.buffer.update(cx, |buffer, cx| {
 6663                let empty_str: Arc<str> = Arc::default();
 6664                buffer.edit(
 6665                    deletion_ranges
 6666                        .into_iter()
 6667                        .map(|range| (range, empty_str.clone())),
 6668                    None,
 6669                    cx,
 6670                );
 6671            });
 6672            let selections = this.selections.all::<usize>(cx);
 6673            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6674                s.select(selections)
 6675            });
 6676        });
 6677    }
 6678
 6679    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6680        if self.read_only(cx) {
 6681            return;
 6682        }
 6683        let selections = self
 6684            .selections
 6685            .all::<usize>(cx)
 6686            .into_iter()
 6687            .map(|s| s.range());
 6688
 6689        self.transact(window, cx, |this, window, cx| {
 6690            this.buffer.update(cx, |buffer, cx| {
 6691                buffer.autoindent_ranges(selections, cx);
 6692            });
 6693            let selections = this.selections.all::<usize>(cx);
 6694            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6695                s.select(selections)
 6696            });
 6697        });
 6698    }
 6699
 6700    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6701        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6702        let selections = self.selections.all::<Point>(cx);
 6703
 6704        let mut new_cursors = Vec::new();
 6705        let mut edit_ranges = Vec::new();
 6706        let mut selections = selections.iter().peekable();
 6707        while let Some(selection) = selections.next() {
 6708            let mut rows = selection.spanned_rows(false, &display_map);
 6709            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6710
 6711            // Accumulate contiguous regions of rows that we want to delete.
 6712            while let Some(next_selection) = selections.peek() {
 6713                let next_rows = next_selection.spanned_rows(false, &display_map);
 6714                if next_rows.start <= rows.end {
 6715                    rows.end = next_rows.end;
 6716                    selections.next().unwrap();
 6717                } else {
 6718                    break;
 6719                }
 6720            }
 6721
 6722            let buffer = &display_map.buffer_snapshot;
 6723            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6724            let edit_end;
 6725            let cursor_buffer_row;
 6726            if buffer.max_point().row >= rows.end.0 {
 6727                // If there's a line after the range, delete the \n from the end of the row range
 6728                // and position the cursor on the next line.
 6729                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6730                cursor_buffer_row = rows.end;
 6731            } else {
 6732                // If there isn't a line after the range, delete the \n from the line before the
 6733                // start of the row range and position the cursor there.
 6734                edit_start = edit_start.saturating_sub(1);
 6735                edit_end = buffer.len();
 6736                cursor_buffer_row = rows.start.previous_row();
 6737            }
 6738
 6739            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6740            *cursor.column_mut() =
 6741                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6742
 6743            new_cursors.push((
 6744                selection.id,
 6745                buffer.anchor_after(cursor.to_point(&display_map)),
 6746            ));
 6747            edit_ranges.push(edit_start..edit_end);
 6748        }
 6749
 6750        self.transact(window, cx, |this, window, cx| {
 6751            let buffer = this.buffer.update(cx, |buffer, cx| {
 6752                let empty_str: Arc<str> = Arc::default();
 6753                buffer.edit(
 6754                    edit_ranges
 6755                        .into_iter()
 6756                        .map(|range| (range, empty_str.clone())),
 6757                    None,
 6758                    cx,
 6759                );
 6760                buffer.snapshot(cx)
 6761            });
 6762            let new_selections = new_cursors
 6763                .into_iter()
 6764                .map(|(id, cursor)| {
 6765                    let cursor = cursor.to_point(&buffer);
 6766                    Selection {
 6767                        id,
 6768                        start: cursor,
 6769                        end: cursor,
 6770                        reversed: false,
 6771                        goal: SelectionGoal::None,
 6772                    }
 6773                })
 6774                .collect();
 6775
 6776            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6777                s.select(new_selections);
 6778            });
 6779        });
 6780    }
 6781
 6782    pub fn join_lines_impl(
 6783        &mut self,
 6784        insert_whitespace: bool,
 6785        window: &mut Window,
 6786        cx: &mut Context<Self>,
 6787    ) {
 6788        if self.read_only(cx) {
 6789            return;
 6790        }
 6791        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6792        for selection in self.selections.all::<Point>(cx) {
 6793            let start = MultiBufferRow(selection.start.row);
 6794            // Treat single line selections as if they include the next line. Otherwise this action
 6795            // would do nothing for single line selections individual cursors.
 6796            let end = if selection.start.row == selection.end.row {
 6797                MultiBufferRow(selection.start.row + 1)
 6798            } else {
 6799                MultiBufferRow(selection.end.row)
 6800            };
 6801
 6802            if let Some(last_row_range) = row_ranges.last_mut() {
 6803                if start <= last_row_range.end {
 6804                    last_row_range.end = end;
 6805                    continue;
 6806                }
 6807            }
 6808            row_ranges.push(start..end);
 6809        }
 6810
 6811        let snapshot = self.buffer.read(cx).snapshot(cx);
 6812        let mut cursor_positions = Vec::new();
 6813        for row_range in &row_ranges {
 6814            let anchor = snapshot.anchor_before(Point::new(
 6815                row_range.end.previous_row().0,
 6816                snapshot.line_len(row_range.end.previous_row()),
 6817            ));
 6818            cursor_positions.push(anchor..anchor);
 6819        }
 6820
 6821        self.transact(window, cx, |this, window, cx| {
 6822            for row_range in row_ranges.into_iter().rev() {
 6823                for row in row_range.iter_rows().rev() {
 6824                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6825                    let next_line_row = row.next_row();
 6826                    let indent = snapshot.indent_size_for_line(next_line_row);
 6827                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6828
 6829                    let replace =
 6830                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6831                            " "
 6832                        } else {
 6833                            ""
 6834                        };
 6835
 6836                    this.buffer.update(cx, |buffer, cx| {
 6837                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6838                    });
 6839                }
 6840            }
 6841
 6842            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6843                s.select_anchor_ranges(cursor_positions)
 6844            });
 6845        });
 6846    }
 6847
 6848    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6849        self.join_lines_impl(true, window, cx);
 6850    }
 6851
 6852    pub fn sort_lines_case_sensitive(
 6853        &mut self,
 6854        _: &SortLinesCaseSensitive,
 6855        window: &mut Window,
 6856        cx: &mut Context<Self>,
 6857    ) {
 6858        self.manipulate_lines(window, cx, |lines| lines.sort())
 6859    }
 6860
 6861    pub fn sort_lines_case_insensitive(
 6862        &mut self,
 6863        _: &SortLinesCaseInsensitive,
 6864        window: &mut Window,
 6865        cx: &mut Context<Self>,
 6866    ) {
 6867        self.manipulate_lines(window, cx, |lines| {
 6868            lines.sort_by_key(|line| line.to_lowercase())
 6869        })
 6870    }
 6871
 6872    pub fn unique_lines_case_insensitive(
 6873        &mut self,
 6874        _: &UniqueLinesCaseInsensitive,
 6875        window: &mut Window,
 6876        cx: &mut Context<Self>,
 6877    ) {
 6878        self.manipulate_lines(window, cx, |lines| {
 6879            let mut seen = HashSet::default();
 6880            lines.retain(|line| seen.insert(line.to_lowercase()));
 6881        })
 6882    }
 6883
 6884    pub fn unique_lines_case_sensitive(
 6885        &mut self,
 6886        _: &UniqueLinesCaseSensitive,
 6887        window: &mut Window,
 6888        cx: &mut Context<Self>,
 6889    ) {
 6890        self.manipulate_lines(window, cx, |lines| {
 6891            let mut seen = HashSet::default();
 6892            lines.retain(|line| seen.insert(*line));
 6893        })
 6894    }
 6895
 6896    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6897        let mut revert_changes = HashMap::default();
 6898        let snapshot = self.snapshot(window, cx);
 6899        for hunk in snapshot
 6900            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6901        {
 6902            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6903        }
 6904        if !revert_changes.is_empty() {
 6905            self.transact(window, cx, |editor, window, cx| {
 6906                editor.revert(revert_changes, window, cx);
 6907            });
 6908        }
 6909    }
 6910
 6911    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6912        let Some(project) = self.project.clone() else {
 6913            return;
 6914        };
 6915        self.reload(project, window, cx)
 6916            .detach_and_notify_err(window, cx);
 6917    }
 6918
 6919    pub fn revert_selected_hunks(
 6920        &mut self,
 6921        _: &RevertSelectedHunks,
 6922        window: &mut Window,
 6923        cx: &mut Context<Self>,
 6924    ) {
 6925        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6926        self.revert_hunks_in_ranges(selections, window, cx);
 6927    }
 6928
 6929    fn revert_hunks_in_ranges(
 6930        &mut self,
 6931        ranges: impl Iterator<Item = Range<Point>>,
 6932        window: &mut Window,
 6933        cx: &mut Context<Editor>,
 6934    ) {
 6935        let mut revert_changes = HashMap::default();
 6936        let snapshot = self.snapshot(window, cx);
 6937        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6938            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6939        }
 6940        if !revert_changes.is_empty() {
 6941            self.transact(window, cx, |editor, window, cx| {
 6942                editor.revert(revert_changes, window, cx);
 6943            });
 6944        }
 6945    }
 6946
 6947    pub fn open_active_item_in_terminal(
 6948        &mut self,
 6949        _: &OpenInTerminal,
 6950        window: &mut Window,
 6951        cx: &mut Context<Self>,
 6952    ) {
 6953        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6954            let project_path = buffer.read(cx).project_path(cx)?;
 6955            let project = self.project.as_ref()?.read(cx);
 6956            let entry = project.entry_for_path(&project_path, cx)?;
 6957            let parent = match &entry.canonical_path {
 6958                Some(canonical_path) => canonical_path.to_path_buf(),
 6959                None => project.absolute_path(&project_path, cx)?,
 6960            }
 6961            .parent()?
 6962            .to_path_buf();
 6963            Some(parent)
 6964        }) {
 6965            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6966        }
 6967    }
 6968
 6969    pub fn prepare_revert_change(
 6970        &self,
 6971        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6972        hunk: &MultiBufferDiffHunk,
 6973        cx: &mut App,
 6974    ) -> Option<()> {
 6975        let buffer = self.buffer.read(cx);
 6976        let diff = buffer.diff_for(hunk.buffer_id)?;
 6977        let buffer = buffer.buffer(hunk.buffer_id)?;
 6978        let buffer = buffer.read(cx);
 6979        let original_text = diff
 6980            .read(cx)
 6981            .base_text()
 6982            .as_ref()?
 6983            .as_rope()
 6984            .slice(hunk.diff_base_byte_range.clone());
 6985        let buffer_snapshot = buffer.snapshot();
 6986        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6987        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6988            probe
 6989                .0
 6990                .start
 6991                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6992                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6993        }) {
 6994            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6995            Some(())
 6996        } else {
 6997            None
 6998        }
 6999    }
 7000
 7001    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7002        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7003    }
 7004
 7005    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7006        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7007    }
 7008
 7009    fn manipulate_lines<Fn>(
 7010        &mut self,
 7011        window: &mut Window,
 7012        cx: &mut Context<Self>,
 7013        mut callback: Fn,
 7014    ) where
 7015        Fn: FnMut(&mut Vec<&str>),
 7016    {
 7017        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7018        let buffer = self.buffer.read(cx).snapshot(cx);
 7019
 7020        let mut edits = Vec::new();
 7021
 7022        let selections = self.selections.all::<Point>(cx);
 7023        let mut selections = selections.iter().peekable();
 7024        let mut contiguous_row_selections = Vec::new();
 7025        let mut new_selections = Vec::new();
 7026        let mut added_lines = 0;
 7027        let mut removed_lines = 0;
 7028
 7029        while let Some(selection) = selections.next() {
 7030            let (start_row, end_row) = consume_contiguous_rows(
 7031                &mut contiguous_row_selections,
 7032                selection,
 7033                &display_map,
 7034                &mut selections,
 7035            );
 7036
 7037            let start_point = Point::new(start_row.0, 0);
 7038            let end_point = Point::new(
 7039                end_row.previous_row().0,
 7040                buffer.line_len(end_row.previous_row()),
 7041            );
 7042            let text = buffer
 7043                .text_for_range(start_point..end_point)
 7044                .collect::<String>();
 7045
 7046            let mut lines = text.split('\n').collect_vec();
 7047
 7048            let lines_before = lines.len();
 7049            callback(&mut lines);
 7050            let lines_after = lines.len();
 7051
 7052            edits.push((start_point..end_point, lines.join("\n")));
 7053
 7054            // Selections must change based on added and removed line count
 7055            let start_row =
 7056                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7057            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7058            new_selections.push(Selection {
 7059                id: selection.id,
 7060                start: start_row,
 7061                end: end_row,
 7062                goal: SelectionGoal::None,
 7063                reversed: selection.reversed,
 7064            });
 7065
 7066            if lines_after > lines_before {
 7067                added_lines += lines_after - lines_before;
 7068            } else if lines_before > lines_after {
 7069                removed_lines += lines_before - lines_after;
 7070            }
 7071        }
 7072
 7073        self.transact(window, cx, |this, window, cx| {
 7074            let buffer = this.buffer.update(cx, |buffer, cx| {
 7075                buffer.edit(edits, None, cx);
 7076                buffer.snapshot(cx)
 7077            });
 7078
 7079            // Recalculate offsets on newly edited buffer
 7080            let new_selections = new_selections
 7081                .iter()
 7082                .map(|s| {
 7083                    let start_point = Point::new(s.start.0, 0);
 7084                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7085                    Selection {
 7086                        id: s.id,
 7087                        start: buffer.point_to_offset(start_point),
 7088                        end: buffer.point_to_offset(end_point),
 7089                        goal: s.goal,
 7090                        reversed: s.reversed,
 7091                    }
 7092                })
 7093                .collect();
 7094
 7095            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7096                s.select(new_selections);
 7097            });
 7098
 7099            this.request_autoscroll(Autoscroll::fit(), cx);
 7100        });
 7101    }
 7102
 7103    pub fn convert_to_upper_case(
 7104        &mut self,
 7105        _: &ConvertToUpperCase,
 7106        window: &mut Window,
 7107        cx: &mut Context<Self>,
 7108    ) {
 7109        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7110    }
 7111
 7112    pub fn convert_to_lower_case(
 7113        &mut self,
 7114        _: &ConvertToLowerCase,
 7115        window: &mut Window,
 7116        cx: &mut Context<Self>,
 7117    ) {
 7118        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7119    }
 7120
 7121    pub fn convert_to_title_case(
 7122        &mut self,
 7123        _: &ConvertToTitleCase,
 7124        window: &mut Window,
 7125        cx: &mut Context<Self>,
 7126    ) {
 7127        self.manipulate_text(window, cx, |text| {
 7128            text.split('\n')
 7129                .map(|line| line.to_case(Case::Title))
 7130                .join("\n")
 7131        })
 7132    }
 7133
 7134    pub fn convert_to_snake_case(
 7135        &mut self,
 7136        _: &ConvertToSnakeCase,
 7137        window: &mut Window,
 7138        cx: &mut Context<Self>,
 7139    ) {
 7140        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7141    }
 7142
 7143    pub fn convert_to_kebab_case(
 7144        &mut self,
 7145        _: &ConvertToKebabCase,
 7146        window: &mut Window,
 7147        cx: &mut Context<Self>,
 7148    ) {
 7149        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7150    }
 7151
 7152    pub fn convert_to_upper_camel_case(
 7153        &mut self,
 7154        _: &ConvertToUpperCamelCase,
 7155        window: &mut Window,
 7156        cx: &mut Context<Self>,
 7157    ) {
 7158        self.manipulate_text(window, cx, |text| {
 7159            text.split('\n')
 7160                .map(|line| line.to_case(Case::UpperCamel))
 7161                .join("\n")
 7162        })
 7163    }
 7164
 7165    pub fn convert_to_lower_camel_case(
 7166        &mut self,
 7167        _: &ConvertToLowerCamelCase,
 7168        window: &mut Window,
 7169        cx: &mut Context<Self>,
 7170    ) {
 7171        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7172    }
 7173
 7174    pub fn convert_to_opposite_case(
 7175        &mut self,
 7176        _: &ConvertToOppositeCase,
 7177        window: &mut Window,
 7178        cx: &mut Context<Self>,
 7179    ) {
 7180        self.manipulate_text(window, cx, |text| {
 7181            text.chars()
 7182                .fold(String::with_capacity(text.len()), |mut t, c| {
 7183                    if c.is_uppercase() {
 7184                        t.extend(c.to_lowercase());
 7185                    } else {
 7186                        t.extend(c.to_uppercase());
 7187                    }
 7188                    t
 7189                })
 7190        })
 7191    }
 7192
 7193    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7194    where
 7195        Fn: FnMut(&str) -> String,
 7196    {
 7197        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7198        let buffer = self.buffer.read(cx).snapshot(cx);
 7199
 7200        let mut new_selections = Vec::new();
 7201        let mut edits = Vec::new();
 7202        let mut selection_adjustment = 0i32;
 7203
 7204        for selection in self.selections.all::<usize>(cx) {
 7205            let selection_is_empty = selection.is_empty();
 7206
 7207            let (start, end) = if selection_is_empty {
 7208                let word_range = movement::surrounding_word(
 7209                    &display_map,
 7210                    selection.start.to_display_point(&display_map),
 7211                );
 7212                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7213                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7214                (start, end)
 7215            } else {
 7216                (selection.start, selection.end)
 7217            };
 7218
 7219            let text = buffer.text_for_range(start..end).collect::<String>();
 7220            let old_length = text.len() as i32;
 7221            let text = callback(&text);
 7222
 7223            new_selections.push(Selection {
 7224                start: (start as i32 - selection_adjustment) as usize,
 7225                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7226                goal: SelectionGoal::None,
 7227                ..selection
 7228            });
 7229
 7230            selection_adjustment += old_length - text.len() as i32;
 7231
 7232            edits.push((start..end, text));
 7233        }
 7234
 7235        self.transact(window, cx, |this, window, cx| {
 7236            this.buffer.update(cx, |buffer, cx| {
 7237                buffer.edit(edits, None, cx);
 7238            });
 7239
 7240            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7241                s.select(new_selections);
 7242            });
 7243
 7244            this.request_autoscroll(Autoscroll::fit(), cx);
 7245        });
 7246    }
 7247
 7248    pub fn duplicate(
 7249        &mut self,
 7250        upwards: bool,
 7251        whole_lines: bool,
 7252        window: &mut Window,
 7253        cx: &mut Context<Self>,
 7254    ) {
 7255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7256        let buffer = &display_map.buffer_snapshot;
 7257        let selections = self.selections.all::<Point>(cx);
 7258
 7259        let mut edits = Vec::new();
 7260        let mut selections_iter = selections.iter().peekable();
 7261        while let Some(selection) = selections_iter.next() {
 7262            let mut rows = selection.spanned_rows(false, &display_map);
 7263            // duplicate line-wise
 7264            if whole_lines || selection.start == selection.end {
 7265                // Avoid duplicating the same lines twice.
 7266                while let Some(next_selection) = selections_iter.peek() {
 7267                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7268                    if next_rows.start < rows.end {
 7269                        rows.end = next_rows.end;
 7270                        selections_iter.next().unwrap();
 7271                    } else {
 7272                        break;
 7273                    }
 7274                }
 7275
 7276                // Copy the text from the selected row region and splice it either at the start
 7277                // or end of the region.
 7278                let start = Point::new(rows.start.0, 0);
 7279                let end = Point::new(
 7280                    rows.end.previous_row().0,
 7281                    buffer.line_len(rows.end.previous_row()),
 7282                );
 7283                let text = buffer
 7284                    .text_for_range(start..end)
 7285                    .chain(Some("\n"))
 7286                    .collect::<String>();
 7287                let insert_location = if upwards {
 7288                    Point::new(rows.end.0, 0)
 7289                } else {
 7290                    start
 7291                };
 7292                edits.push((insert_location..insert_location, text));
 7293            } else {
 7294                // duplicate character-wise
 7295                let start = selection.start;
 7296                let end = selection.end;
 7297                let text = buffer.text_for_range(start..end).collect::<String>();
 7298                edits.push((selection.end..selection.end, text));
 7299            }
 7300        }
 7301
 7302        self.transact(window, cx, |this, _, cx| {
 7303            this.buffer.update(cx, |buffer, cx| {
 7304                buffer.edit(edits, None, cx);
 7305            });
 7306
 7307            this.request_autoscroll(Autoscroll::fit(), cx);
 7308        });
 7309    }
 7310
 7311    pub fn duplicate_line_up(
 7312        &mut self,
 7313        _: &DuplicateLineUp,
 7314        window: &mut Window,
 7315        cx: &mut Context<Self>,
 7316    ) {
 7317        self.duplicate(true, true, window, cx);
 7318    }
 7319
 7320    pub fn duplicate_line_down(
 7321        &mut self,
 7322        _: &DuplicateLineDown,
 7323        window: &mut Window,
 7324        cx: &mut Context<Self>,
 7325    ) {
 7326        self.duplicate(false, true, window, cx);
 7327    }
 7328
 7329    pub fn duplicate_selection(
 7330        &mut self,
 7331        _: &DuplicateSelection,
 7332        window: &mut Window,
 7333        cx: &mut Context<Self>,
 7334    ) {
 7335        self.duplicate(false, false, window, cx);
 7336    }
 7337
 7338    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7339        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7340        let buffer = self.buffer.read(cx).snapshot(cx);
 7341
 7342        let mut edits = Vec::new();
 7343        let mut unfold_ranges = Vec::new();
 7344        let mut refold_creases = Vec::new();
 7345
 7346        let selections = self.selections.all::<Point>(cx);
 7347        let mut selections = selections.iter().peekable();
 7348        let mut contiguous_row_selections = Vec::new();
 7349        let mut new_selections = Vec::new();
 7350
 7351        while let Some(selection) = selections.next() {
 7352            // Find all the selections that span a contiguous row range
 7353            let (start_row, end_row) = consume_contiguous_rows(
 7354                &mut contiguous_row_selections,
 7355                selection,
 7356                &display_map,
 7357                &mut selections,
 7358            );
 7359
 7360            // Move the text spanned by the row range to be before the line preceding the row range
 7361            if start_row.0 > 0 {
 7362                let range_to_move = Point::new(
 7363                    start_row.previous_row().0,
 7364                    buffer.line_len(start_row.previous_row()),
 7365                )
 7366                    ..Point::new(
 7367                        end_row.previous_row().0,
 7368                        buffer.line_len(end_row.previous_row()),
 7369                    );
 7370                let insertion_point = display_map
 7371                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7372                    .0;
 7373
 7374                // Don't move lines across excerpts
 7375                if buffer
 7376                    .excerpt_containing(insertion_point..range_to_move.end)
 7377                    .is_some()
 7378                {
 7379                    let text = buffer
 7380                        .text_for_range(range_to_move.clone())
 7381                        .flat_map(|s| s.chars())
 7382                        .skip(1)
 7383                        .chain(['\n'])
 7384                        .collect::<String>();
 7385
 7386                    edits.push((
 7387                        buffer.anchor_after(range_to_move.start)
 7388                            ..buffer.anchor_before(range_to_move.end),
 7389                        String::new(),
 7390                    ));
 7391                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7392                    edits.push((insertion_anchor..insertion_anchor, text));
 7393
 7394                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7395
 7396                    // Move selections up
 7397                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7398                        |mut selection| {
 7399                            selection.start.row -= row_delta;
 7400                            selection.end.row -= row_delta;
 7401                            selection
 7402                        },
 7403                    ));
 7404
 7405                    // Move folds up
 7406                    unfold_ranges.push(range_to_move.clone());
 7407                    for fold in display_map.folds_in_range(
 7408                        buffer.anchor_before(range_to_move.start)
 7409                            ..buffer.anchor_after(range_to_move.end),
 7410                    ) {
 7411                        let mut start = fold.range.start.to_point(&buffer);
 7412                        let mut end = fold.range.end.to_point(&buffer);
 7413                        start.row -= row_delta;
 7414                        end.row -= row_delta;
 7415                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7416                    }
 7417                }
 7418            }
 7419
 7420            // If we didn't move line(s), preserve the existing selections
 7421            new_selections.append(&mut contiguous_row_selections);
 7422        }
 7423
 7424        self.transact(window, cx, |this, window, cx| {
 7425            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7426            this.buffer.update(cx, |buffer, cx| {
 7427                for (range, text) in edits {
 7428                    buffer.edit([(range, text)], None, cx);
 7429                }
 7430            });
 7431            this.fold_creases(refold_creases, true, window, cx);
 7432            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7433                s.select(new_selections);
 7434            })
 7435        });
 7436    }
 7437
 7438    pub fn move_line_down(
 7439        &mut self,
 7440        _: &MoveLineDown,
 7441        window: &mut Window,
 7442        cx: &mut Context<Self>,
 7443    ) {
 7444        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7445        let buffer = self.buffer.read(cx).snapshot(cx);
 7446
 7447        let mut edits = Vec::new();
 7448        let mut unfold_ranges = Vec::new();
 7449        let mut refold_creases = Vec::new();
 7450
 7451        let selections = self.selections.all::<Point>(cx);
 7452        let mut selections = selections.iter().peekable();
 7453        let mut contiguous_row_selections = Vec::new();
 7454        let mut new_selections = Vec::new();
 7455
 7456        while let Some(selection) = selections.next() {
 7457            // Find all the selections that span a contiguous row range
 7458            let (start_row, end_row) = consume_contiguous_rows(
 7459                &mut contiguous_row_selections,
 7460                selection,
 7461                &display_map,
 7462                &mut selections,
 7463            );
 7464
 7465            // Move the text spanned by the row range to be after the last line of the row range
 7466            if end_row.0 <= buffer.max_point().row {
 7467                let range_to_move =
 7468                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7469                let insertion_point = display_map
 7470                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7471                    .0;
 7472
 7473                // Don't move lines across excerpt boundaries
 7474                if buffer
 7475                    .excerpt_containing(range_to_move.start..insertion_point)
 7476                    .is_some()
 7477                {
 7478                    let mut text = String::from("\n");
 7479                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7480                    text.pop(); // Drop trailing newline
 7481                    edits.push((
 7482                        buffer.anchor_after(range_to_move.start)
 7483                            ..buffer.anchor_before(range_to_move.end),
 7484                        String::new(),
 7485                    ));
 7486                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7487                    edits.push((insertion_anchor..insertion_anchor, text));
 7488
 7489                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7490
 7491                    // Move selections down
 7492                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7493                        |mut selection| {
 7494                            selection.start.row += row_delta;
 7495                            selection.end.row += row_delta;
 7496                            selection
 7497                        },
 7498                    ));
 7499
 7500                    // Move folds down
 7501                    unfold_ranges.push(range_to_move.clone());
 7502                    for fold in display_map.folds_in_range(
 7503                        buffer.anchor_before(range_to_move.start)
 7504                            ..buffer.anchor_after(range_to_move.end),
 7505                    ) {
 7506                        let mut start = fold.range.start.to_point(&buffer);
 7507                        let mut end = fold.range.end.to_point(&buffer);
 7508                        start.row += row_delta;
 7509                        end.row += row_delta;
 7510                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7511                    }
 7512                }
 7513            }
 7514
 7515            // If we didn't move line(s), preserve the existing selections
 7516            new_selections.append(&mut contiguous_row_selections);
 7517        }
 7518
 7519        self.transact(window, cx, |this, window, cx| {
 7520            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7521            this.buffer.update(cx, |buffer, cx| {
 7522                for (range, text) in edits {
 7523                    buffer.edit([(range, text)], None, cx);
 7524                }
 7525            });
 7526            this.fold_creases(refold_creases, true, window, cx);
 7527            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7528                s.select(new_selections)
 7529            });
 7530        });
 7531    }
 7532
 7533    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7534        let text_layout_details = &self.text_layout_details(window);
 7535        self.transact(window, cx, |this, window, cx| {
 7536            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7537                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7538                let line_mode = s.line_mode;
 7539                s.move_with(|display_map, selection| {
 7540                    if !selection.is_empty() || line_mode {
 7541                        return;
 7542                    }
 7543
 7544                    let mut head = selection.head();
 7545                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7546                    if head.column() == display_map.line_len(head.row()) {
 7547                        transpose_offset = display_map
 7548                            .buffer_snapshot
 7549                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7550                    }
 7551
 7552                    if transpose_offset == 0 {
 7553                        return;
 7554                    }
 7555
 7556                    *head.column_mut() += 1;
 7557                    head = display_map.clip_point(head, Bias::Right);
 7558                    let goal = SelectionGoal::HorizontalPosition(
 7559                        display_map
 7560                            .x_for_display_point(head, text_layout_details)
 7561                            .into(),
 7562                    );
 7563                    selection.collapse_to(head, goal);
 7564
 7565                    let transpose_start = display_map
 7566                        .buffer_snapshot
 7567                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7568                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7569                        let transpose_end = display_map
 7570                            .buffer_snapshot
 7571                            .clip_offset(transpose_offset + 1, Bias::Right);
 7572                        if let Some(ch) =
 7573                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7574                        {
 7575                            edits.push((transpose_start..transpose_offset, String::new()));
 7576                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7577                        }
 7578                    }
 7579                });
 7580                edits
 7581            });
 7582            this.buffer
 7583                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7584            let selections = this.selections.all::<usize>(cx);
 7585            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7586                s.select(selections);
 7587            });
 7588        });
 7589    }
 7590
 7591    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7592        self.rewrap_impl(IsVimMode::No, cx)
 7593    }
 7594
 7595    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7596        let buffer = self.buffer.read(cx).snapshot(cx);
 7597        let selections = self.selections.all::<Point>(cx);
 7598        let mut selections = selections.iter().peekable();
 7599
 7600        let mut edits = Vec::new();
 7601        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7602
 7603        while let Some(selection) = selections.next() {
 7604            let mut start_row = selection.start.row;
 7605            let mut end_row = selection.end.row;
 7606
 7607            // Skip selections that overlap with a range that has already been rewrapped.
 7608            let selection_range = start_row..end_row;
 7609            if rewrapped_row_ranges
 7610                .iter()
 7611                .any(|range| range.overlaps(&selection_range))
 7612            {
 7613                continue;
 7614            }
 7615
 7616            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7617
 7618            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7619                match language_scope.language_name().as_ref() {
 7620                    "Markdown" | "Plain Text" => {
 7621                        should_rewrap = true;
 7622                    }
 7623                    _ => {}
 7624                }
 7625            }
 7626
 7627            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7628
 7629            // Since not all lines in the selection may be at the same indent
 7630            // level, choose the indent size that is the most common between all
 7631            // of the lines.
 7632            //
 7633            // If there is a tie, we use the deepest indent.
 7634            let (indent_size, indent_end) = {
 7635                let mut indent_size_occurrences = HashMap::default();
 7636                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7637
 7638                for row in start_row..=end_row {
 7639                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7640                    rows_by_indent_size.entry(indent).or_default().push(row);
 7641                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7642                }
 7643
 7644                let indent_size = indent_size_occurrences
 7645                    .into_iter()
 7646                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7647                    .map(|(indent, _)| indent)
 7648                    .unwrap_or_default();
 7649                let row = rows_by_indent_size[&indent_size][0];
 7650                let indent_end = Point::new(row, indent_size.len);
 7651
 7652                (indent_size, indent_end)
 7653            };
 7654
 7655            let mut line_prefix = indent_size.chars().collect::<String>();
 7656
 7657            if let Some(comment_prefix) =
 7658                buffer
 7659                    .language_scope_at(selection.head())
 7660                    .and_then(|language| {
 7661                        language
 7662                            .line_comment_prefixes()
 7663                            .iter()
 7664                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7665                            .cloned()
 7666                    })
 7667            {
 7668                line_prefix.push_str(&comment_prefix);
 7669                should_rewrap = true;
 7670            }
 7671
 7672            if !should_rewrap {
 7673                continue;
 7674            }
 7675
 7676            if selection.is_empty() {
 7677                'expand_upwards: while start_row > 0 {
 7678                    let prev_row = start_row - 1;
 7679                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7680                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7681                    {
 7682                        start_row = prev_row;
 7683                    } else {
 7684                        break 'expand_upwards;
 7685                    }
 7686                }
 7687
 7688                'expand_downwards: while end_row < buffer.max_point().row {
 7689                    let next_row = end_row + 1;
 7690                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7691                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7692                    {
 7693                        end_row = next_row;
 7694                    } else {
 7695                        break 'expand_downwards;
 7696                    }
 7697                }
 7698            }
 7699
 7700            let start = Point::new(start_row, 0);
 7701            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7702            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7703            let Some(lines_without_prefixes) = selection_text
 7704                .lines()
 7705                .map(|line| {
 7706                    line.strip_prefix(&line_prefix)
 7707                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7708                        .ok_or_else(|| {
 7709                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7710                        })
 7711                })
 7712                .collect::<Result<Vec<_>, _>>()
 7713                .log_err()
 7714            else {
 7715                continue;
 7716            };
 7717
 7718            let wrap_column = buffer
 7719                .settings_at(Point::new(start_row, 0), cx)
 7720                .preferred_line_length as usize;
 7721            let wrapped_text = wrap_with_prefix(
 7722                line_prefix,
 7723                lines_without_prefixes.join(" "),
 7724                wrap_column,
 7725                tab_size,
 7726            );
 7727
 7728            // TODO: should always use char-based diff while still supporting cursor behavior that
 7729            // matches vim.
 7730            let diff = match is_vim_mode {
 7731                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7732                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7733            };
 7734            let mut offset = start.to_offset(&buffer);
 7735            let mut moved_since_edit = true;
 7736
 7737            for change in diff.iter_all_changes() {
 7738                let value = change.value();
 7739                match change.tag() {
 7740                    ChangeTag::Equal => {
 7741                        offset += value.len();
 7742                        moved_since_edit = true;
 7743                    }
 7744                    ChangeTag::Delete => {
 7745                        let start = buffer.anchor_after(offset);
 7746                        let end = buffer.anchor_before(offset + value.len());
 7747
 7748                        if moved_since_edit {
 7749                            edits.push((start..end, String::new()));
 7750                        } else {
 7751                            edits.last_mut().unwrap().0.end = end;
 7752                        }
 7753
 7754                        offset += value.len();
 7755                        moved_since_edit = false;
 7756                    }
 7757                    ChangeTag::Insert => {
 7758                        if moved_since_edit {
 7759                            let anchor = buffer.anchor_after(offset);
 7760                            edits.push((anchor..anchor, value.to_string()));
 7761                        } else {
 7762                            edits.last_mut().unwrap().1.push_str(value);
 7763                        }
 7764
 7765                        moved_since_edit = false;
 7766                    }
 7767                }
 7768            }
 7769
 7770            rewrapped_row_ranges.push(start_row..=end_row);
 7771        }
 7772
 7773        self.buffer
 7774            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7775    }
 7776
 7777    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7778        let mut text = String::new();
 7779        let buffer = self.buffer.read(cx).snapshot(cx);
 7780        let mut selections = self.selections.all::<Point>(cx);
 7781        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7782        {
 7783            let max_point = buffer.max_point();
 7784            let mut is_first = true;
 7785            for selection in &mut selections {
 7786                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7787                if is_entire_line {
 7788                    selection.start = Point::new(selection.start.row, 0);
 7789                    if !selection.is_empty() && selection.end.column == 0 {
 7790                        selection.end = cmp::min(max_point, selection.end);
 7791                    } else {
 7792                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7793                    }
 7794                    selection.goal = SelectionGoal::None;
 7795                }
 7796                if is_first {
 7797                    is_first = false;
 7798                } else {
 7799                    text += "\n";
 7800                }
 7801                let mut len = 0;
 7802                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7803                    text.push_str(chunk);
 7804                    len += chunk.len();
 7805                }
 7806                clipboard_selections.push(ClipboardSelection {
 7807                    len,
 7808                    is_entire_line,
 7809                    first_line_indent: buffer
 7810                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7811                        .len,
 7812                });
 7813            }
 7814        }
 7815
 7816        self.transact(window, cx, |this, window, cx| {
 7817            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7818                s.select(selections);
 7819            });
 7820            this.insert("", window, cx);
 7821        });
 7822        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7823    }
 7824
 7825    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7826        let item = self.cut_common(window, cx);
 7827        cx.write_to_clipboard(item);
 7828    }
 7829
 7830    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7831        self.change_selections(None, window, cx, |s| {
 7832            s.move_with(|snapshot, sel| {
 7833                if sel.is_empty() {
 7834                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7835                }
 7836            });
 7837        });
 7838        let item = self.cut_common(window, cx);
 7839        cx.set_global(KillRing(item))
 7840    }
 7841
 7842    pub fn kill_ring_yank(
 7843        &mut self,
 7844        _: &KillRingYank,
 7845        window: &mut Window,
 7846        cx: &mut Context<Self>,
 7847    ) {
 7848        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7849            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7850                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7851            } else {
 7852                return;
 7853            }
 7854        } else {
 7855            return;
 7856        };
 7857        self.do_paste(&text, metadata, false, window, cx);
 7858    }
 7859
 7860    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7861        let selections = self.selections.all::<Point>(cx);
 7862        let buffer = self.buffer.read(cx).read(cx);
 7863        let mut text = String::new();
 7864
 7865        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7866        {
 7867            let max_point = buffer.max_point();
 7868            let mut is_first = true;
 7869            for selection in selections.iter() {
 7870                let mut start = selection.start;
 7871                let mut end = selection.end;
 7872                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7873                if is_entire_line {
 7874                    start = Point::new(start.row, 0);
 7875                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7876                }
 7877                if is_first {
 7878                    is_first = false;
 7879                } else {
 7880                    text += "\n";
 7881                }
 7882                let mut len = 0;
 7883                for chunk in buffer.text_for_range(start..end) {
 7884                    text.push_str(chunk);
 7885                    len += chunk.len();
 7886                }
 7887                clipboard_selections.push(ClipboardSelection {
 7888                    len,
 7889                    is_entire_line,
 7890                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7891                });
 7892            }
 7893        }
 7894
 7895        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7896            text,
 7897            clipboard_selections,
 7898        ));
 7899    }
 7900
 7901    pub fn do_paste(
 7902        &mut self,
 7903        text: &String,
 7904        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7905        handle_entire_lines: bool,
 7906        window: &mut Window,
 7907        cx: &mut Context<Self>,
 7908    ) {
 7909        if self.read_only(cx) {
 7910            return;
 7911        }
 7912
 7913        let clipboard_text = Cow::Borrowed(text);
 7914
 7915        self.transact(window, cx, |this, window, cx| {
 7916            if let Some(mut clipboard_selections) = clipboard_selections {
 7917                let old_selections = this.selections.all::<usize>(cx);
 7918                let all_selections_were_entire_line =
 7919                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7920                let first_selection_indent_column =
 7921                    clipboard_selections.first().map(|s| s.first_line_indent);
 7922                if clipboard_selections.len() != old_selections.len() {
 7923                    clipboard_selections.drain(..);
 7924                }
 7925                let cursor_offset = this.selections.last::<usize>(cx).head();
 7926                let mut auto_indent_on_paste = true;
 7927
 7928                this.buffer.update(cx, |buffer, cx| {
 7929                    let snapshot = buffer.read(cx);
 7930                    auto_indent_on_paste =
 7931                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7932
 7933                    let mut start_offset = 0;
 7934                    let mut edits = Vec::new();
 7935                    let mut original_indent_columns = Vec::new();
 7936                    for (ix, selection) in old_selections.iter().enumerate() {
 7937                        let to_insert;
 7938                        let entire_line;
 7939                        let original_indent_column;
 7940                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7941                            let end_offset = start_offset + clipboard_selection.len;
 7942                            to_insert = &clipboard_text[start_offset..end_offset];
 7943                            entire_line = clipboard_selection.is_entire_line;
 7944                            start_offset = end_offset + 1;
 7945                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7946                        } else {
 7947                            to_insert = clipboard_text.as_str();
 7948                            entire_line = all_selections_were_entire_line;
 7949                            original_indent_column = first_selection_indent_column
 7950                        }
 7951
 7952                        // If the corresponding selection was empty when this slice of the
 7953                        // clipboard text was written, then the entire line containing the
 7954                        // selection was copied. If this selection is also currently empty,
 7955                        // then paste the line before the current line of the buffer.
 7956                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7957                            let column = selection.start.to_point(&snapshot).column as usize;
 7958                            let line_start = selection.start - column;
 7959                            line_start..line_start
 7960                        } else {
 7961                            selection.range()
 7962                        };
 7963
 7964                        edits.push((range, to_insert));
 7965                        original_indent_columns.extend(original_indent_column);
 7966                    }
 7967                    drop(snapshot);
 7968
 7969                    buffer.edit(
 7970                        edits,
 7971                        if auto_indent_on_paste {
 7972                            Some(AutoindentMode::Block {
 7973                                original_indent_columns,
 7974                            })
 7975                        } else {
 7976                            None
 7977                        },
 7978                        cx,
 7979                    );
 7980                });
 7981
 7982                let selections = this.selections.all::<usize>(cx);
 7983                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7984                    s.select(selections)
 7985                });
 7986            } else {
 7987                this.insert(&clipboard_text, window, cx);
 7988            }
 7989        });
 7990    }
 7991
 7992    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7993        if let Some(item) = cx.read_from_clipboard() {
 7994            let entries = item.entries();
 7995
 7996            match entries.first() {
 7997                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7998                // of all the pasted entries.
 7999                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8000                    .do_paste(
 8001                        clipboard_string.text(),
 8002                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8003                        true,
 8004                        window,
 8005                        cx,
 8006                    ),
 8007                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8008            }
 8009        }
 8010    }
 8011
 8012    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8013        if self.read_only(cx) {
 8014            return;
 8015        }
 8016
 8017        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8018            if let Some((selections, _)) =
 8019                self.selection_history.transaction(transaction_id).cloned()
 8020            {
 8021                self.change_selections(None, window, cx, |s| {
 8022                    s.select_anchors(selections.to_vec());
 8023                });
 8024            }
 8025            self.request_autoscroll(Autoscroll::fit(), cx);
 8026            self.unmark_text(window, cx);
 8027            self.refresh_inline_completion(true, false, window, cx);
 8028            cx.emit(EditorEvent::Edited { transaction_id });
 8029            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8030        }
 8031    }
 8032
 8033    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8034        if self.read_only(cx) {
 8035            return;
 8036        }
 8037
 8038        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8039            if let Some((_, Some(selections))) =
 8040                self.selection_history.transaction(transaction_id).cloned()
 8041            {
 8042                self.change_selections(None, window, cx, |s| {
 8043                    s.select_anchors(selections.to_vec());
 8044                });
 8045            }
 8046            self.request_autoscroll(Autoscroll::fit(), cx);
 8047            self.unmark_text(window, cx);
 8048            self.refresh_inline_completion(true, false, window, cx);
 8049            cx.emit(EditorEvent::Edited { transaction_id });
 8050        }
 8051    }
 8052
 8053    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8054        self.buffer
 8055            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8056    }
 8057
 8058    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8059        self.buffer
 8060            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8061    }
 8062
 8063    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8064        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8065            let line_mode = s.line_mode;
 8066            s.move_with(|map, selection| {
 8067                let cursor = if selection.is_empty() && !line_mode {
 8068                    movement::left(map, selection.start)
 8069                } else {
 8070                    selection.start
 8071                };
 8072                selection.collapse_to(cursor, SelectionGoal::None);
 8073            });
 8074        })
 8075    }
 8076
 8077    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8078        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8079            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8080        })
 8081    }
 8082
 8083    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8084        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8085            let line_mode = s.line_mode;
 8086            s.move_with(|map, selection| {
 8087                let cursor = if selection.is_empty() && !line_mode {
 8088                    movement::right(map, selection.end)
 8089                } else {
 8090                    selection.end
 8091                };
 8092                selection.collapse_to(cursor, SelectionGoal::None)
 8093            });
 8094        })
 8095    }
 8096
 8097    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8098        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8099            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8100        })
 8101    }
 8102
 8103    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8104        if self.take_rename(true, window, cx).is_some() {
 8105            return;
 8106        }
 8107
 8108        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8109            cx.propagate();
 8110            return;
 8111        }
 8112
 8113        let text_layout_details = &self.text_layout_details(window);
 8114        let selection_count = self.selections.count();
 8115        let first_selection = self.selections.first_anchor();
 8116
 8117        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8118            let line_mode = s.line_mode;
 8119            s.move_with(|map, selection| {
 8120                if !selection.is_empty() && !line_mode {
 8121                    selection.goal = SelectionGoal::None;
 8122                }
 8123                let (cursor, goal) = movement::up(
 8124                    map,
 8125                    selection.start,
 8126                    selection.goal,
 8127                    false,
 8128                    text_layout_details,
 8129                );
 8130                selection.collapse_to(cursor, goal);
 8131            });
 8132        });
 8133
 8134        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8135        {
 8136            cx.propagate();
 8137        }
 8138    }
 8139
 8140    pub fn move_up_by_lines(
 8141        &mut self,
 8142        action: &MoveUpByLines,
 8143        window: &mut Window,
 8144        cx: &mut Context<Self>,
 8145    ) {
 8146        if self.take_rename(true, window, cx).is_some() {
 8147            return;
 8148        }
 8149
 8150        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8151            cx.propagate();
 8152            return;
 8153        }
 8154
 8155        let text_layout_details = &self.text_layout_details(window);
 8156
 8157        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8158            let line_mode = s.line_mode;
 8159            s.move_with(|map, selection| {
 8160                if !selection.is_empty() && !line_mode {
 8161                    selection.goal = SelectionGoal::None;
 8162                }
 8163                let (cursor, goal) = movement::up_by_rows(
 8164                    map,
 8165                    selection.start,
 8166                    action.lines,
 8167                    selection.goal,
 8168                    false,
 8169                    text_layout_details,
 8170                );
 8171                selection.collapse_to(cursor, goal);
 8172            });
 8173        })
 8174    }
 8175
 8176    pub fn move_down_by_lines(
 8177        &mut self,
 8178        action: &MoveDownByLines,
 8179        window: &mut Window,
 8180        cx: &mut Context<Self>,
 8181    ) {
 8182        if self.take_rename(true, window, cx).is_some() {
 8183            return;
 8184        }
 8185
 8186        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8187            cx.propagate();
 8188            return;
 8189        }
 8190
 8191        let text_layout_details = &self.text_layout_details(window);
 8192
 8193        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8194            let line_mode = s.line_mode;
 8195            s.move_with(|map, selection| {
 8196                if !selection.is_empty() && !line_mode {
 8197                    selection.goal = SelectionGoal::None;
 8198                }
 8199                let (cursor, goal) = movement::down_by_rows(
 8200                    map,
 8201                    selection.start,
 8202                    action.lines,
 8203                    selection.goal,
 8204                    false,
 8205                    text_layout_details,
 8206                );
 8207                selection.collapse_to(cursor, goal);
 8208            });
 8209        })
 8210    }
 8211
 8212    pub fn select_down_by_lines(
 8213        &mut self,
 8214        action: &SelectDownByLines,
 8215        window: &mut Window,
 8216        cx: &mut Context<Self>,
 8217    ) {
 8218        let text_layout_details = &self.text_layout_details(window);
 8219        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8220            s.move_heads_with(|map, head, goal| {
 8221                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8222            })
 8223        })
 8224    }
 8225
 8226    pub fn select_up_by_lines(
 8227        &mut self,
 8228        action: &SelectUpByLines,
 8229        window: &mut Window,
 8230        cx: &mut Context<Self>,
 8231    ) {
 8232        let text_layout_details = &self.text_layout_details(window);
 8233        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8234            s.move_heads_with(|map, head, goal| {
 8235                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8236            })
 8237        })
 8238    }
 8239
 8240    pub fn select_page_up(
 8241        &mut self,
 8242        _: &SelectPageUp,
 8243        window: &mut Window,
 8244        cx: &mut Context<Self>,
 8245    ) {
 8246        let Some(row_count) = self.visible_row_count() else {
 8247            return;
 8248        };
 8249
 8250        let text_layout_details = &self.text_layout_details(window);
 8251
 8252        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8253            s.move_heads_with(|map, head, goal| {
 8254                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8255            })
 8256        })
 8257    }
 8258
 8259    pub fn move_page_up(
 8260        &mut self,
 8261        action: &MovePageUp,
 8262        window: &mut Window,
 8263        cx: &mut Context<Self>,
 8264    ) {
 8265        if self.take_rename(true, window, cx).is_some() {
 8266            return;
 8267        }
 8268
 8269        if self
 8270            .context_menu
 8271            .borrow_mut()
 8272            .as_mut()
 8273            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8274            .unwrap_or(false)
 8275        {
 8276            return;
 8277        }
 8278
 8279        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8280            cx.propagate();
 8281            return;
 8282        }
 8283
 8284        let Some(row_count) = self.visible_row_count() else {
 8285            return;
 8286        };
 8287
 8288        let autoscroll = if action.center_cursor {
 8289            Autoscroll::center()
 8290        } else {
 8291            Autoscroll::fit()
 8292        };
 8293
 8294        let text_layout_details = &self.text_layout_details(window);
 8295
 8296        self.change_selections(Some(autoscroll), window, cx, |s| {
 8297            let line_mode = s.line_mode;
 8298            s.move_with(|map, selection| {
 8299                if !selection.is_empty() && !line_mode {
 8300                    selection.goal = SelectionGoal::None;
 8301                }
 8302                let (cursor, goal) = movement::up_by_rows(
 8303                    map,
 8304                    selection.end,
 8305                    row_count,
 8306                    selection.goal,
 8307                    false,
 8308                    text_layout_details,
 8309                );
 8310                selection.collapse_to(cursor, goal);
 8311            });
 8312        });
 8313    }
 8314
 8315    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8316        let text_layout_details = &self.text_layout_details(window);
 8317        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8318            s.move_heads_with(|map, head, goal| {
 8319                movement::up(map, head, goal, false, text_layout_details)
 8320            })
 8321        })
 8322    }
 8323
 8324    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8325        self.take_rename(true, window, cx);
 8326
 8327        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8328            cx.propagate();
 8329            return;
 8330        }
 8331
 8332        let text_layout_details = &self.text_layout_details(window);
 8333        let selection_count = self.selections.count();
 8334        let first_selection = self.selections.first_anchor();
 8335
 8336        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8337            let line_mode = s.line_mode;
 8338            s.move_with(|map, selection| {
 8339                if !selection.is_empty() && !line_mode {
 8340                    selection.goal = SelectionGoal::None;
 8341                }
 8342                let (cursor, goal) = movement::down(
 8343                    map,
 8344                    selection.end,
 8345                    selection.goal,
 8346                    false,
 8347                    text_layout_details,
 8348                );
 8349                selection.collapse_to(cursor, goal);
 8350            });
 8351        });
 8352
 8353        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8354        {
 8355            cx.propagate();
 8356        }
 8357    }
 8358
 8359    pub fn select_page_down(
 8360        &mut self,
 8361        _: &SelectPageDown,
 8362        window: &mut Window,
 8363        cx: &mut Context<Self>,
 8364    ) {
 8365        let Some(row_count) = self.visible_row_count() else {
 8366            return;
 8367        };
 8368
 8369        let text_layout_details = &self.text_layout_details(window);
 8370
 8371        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8372            s.move_heads_with(|map, head, goal| {
 8373                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8374            })
 8375        })
 8376    }
 8377
 8378    pub fn move_page_down(
 8379        &mut self,
 8380        action: &MovePageDown,
 8381        window: &mut Window,
 8382        cx: &mut Context<Self>,
 8383    ) {
 8384        if self.take_rename(true, window, cx).is_some() {
 8385            return;
 8386        }
 8387
 8388        if self
 8389            .context_menu
 8390            .borrow_mut()
 8391            .as_mut()
 8392            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8393            .unwrap_or(false)
 8394        {
 8395            return;
 8396        }
 8397
 8398        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8399            cx.propagate();
 8400            return;
 8401        }
 8402
 8403        let Some(row_count) = self.visible_row_count() else {
 8404            return;
 8405        };
 8406
 8407        let autoscroll = if action.center_cursor {
 8408            Autoscroll::center()
 8409        } else {
 8410            Autoscroll::fit()
 8411        };
 8412
 8413        let text_layout_details = &self.text_layout_details(window);
 8414        self.change_selections(Some(autoscroll), window, cx, |s| {
 8415            let line_mode = s.line_mode;
 8416            s.move_with(|map, selection| {
 8417                if !selection.is_empty() && !line_mode {
 8418                    selection.goal = SelectionGoal::None;
 8419                }
 8420                let (cursor, goal) = movement::down_by_rows(
 8421                    map,
 8422                    selection.end,
 8423                    row_count,
 8424                    selection.goal,
 8425                    false,
 8426                    text_layout_details,
 8427                );
 8428                selection.collapse_to(cursor, goal);
 8429            });
 8430        });
 8431    }
 8432
 8433    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8434        let text_layout_details = &self.text_layout_details(window);
 8435        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8436            s.move_heads_with(|map, head, goal| {
 8437                movement::down(map, head, goal, false, text_layout_details)
 8438            })
 8439        });
 8440    }
 8441
 8442    pub fn context_menu_first(
 8443        &mut self,
 8444        _: &ContextMenuFirst,
 8445        _window: &mut Window,
 8446        cx: &mut Context<Self>,
 8447    ) {
 8448        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8449            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8450        }
 8451    }
 8452
 8453    pub fn context_menu_prev(
 8454        &mut self,
 8455        _: &ContextMenuPrev,
 8456        _window: &mut Window,
 8457        cx: &mut Context<Self>,
 8458    ) {
 8459        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8460            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8461        }
 8462    }
 8463
 8464    pub fn context_menu_next(
 8465        &mut self,
 8466        _: &ContextMenuNext,
 8467        _window: &mut Window,
 8468        cx: &mut Context<Self>,
 8469    ) {
 8470        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8471            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8472        }
 8473    }
 8474
 8475    pub fn context_menu_last(
 8476        &mut self,
 8477        _: &ContextMenuLast,
 8478        _window: &mut Window,
 8479        cx: &mut Context<Self>,
 8480    ) {
 8481        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8482            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8483        }
 8484    }
 8485
 8486    pub fn move_to_previous_word_start(
 8487        &mut self,
 8488        _: &MoveToPreviousWordStart,
 8489        window: &mut Window,
 8490        cx: &mut Context<Self>,
 8491    ) {
 8492        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8493            s.move_cursors_with(|map, head, _| {
 8494                (
 8495                    movement::previous_word_start(map, head),
 8496                    SelectionGoal::None,
 8497                )
 8498            });
 8499        })
 8500    }
 8501
 8502    pub fn move_to_previous_subword_start(
 8503        &mut self,
 8504        _: &MoveToPreviousSubwordStart,
 8505        window: &mut Window,
 8506        cx: &mut Context<Self>,
 8507    ) {
 8508        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8509            s.move_cursors_with(|map, head, _| {
 8510                (
 8511                    movement::previous_subword_start(map, head),
 8512                    SelectionGoal::None,
 8513                )
 8514            });
 8515        })
 8516    }
 8517
 8518    pub fn select_to_previous_word_start(
 8519        &mut self,
 8520        _: &SelectToPreviousWordStart,
 8521        window: &mut Window,
 8522        cx: &mut Context<Self>,
 8523    ) {
 8524        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8525            s.move_heads_with(|map, head, _| {
 8526                (
 8527                    movement::previous_word_start(map, head),
 8528                    SelectionGoal::None,
 8529                )
 8530            });
 8531        })
 8532    }
 8533
 8534    pub fn select_to_previous_subword_start(
 8535        &mut self,
 8536        _: &SelectToPreviousSubwordStart,
 8537        window: &mut Window,
 8538        cx: &mut Context<Self>,
 8539    ) {
 8540        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8541            s.move_heads_with(|map, head, _| {
 8542                (
 8543                    movement::previous_subword_start(map, head),
 8544                    SelectionGoal::None,
 8545                )
 8546            });
 8547        })
 8548    }
 8549
 8550    pub fn delete_to_previous_word_start(
 8551        &mut self,
 8552        action: &DeleteToPreviousWordStart,
 8553        window: &mut Window,
 8554        cx: &mut Context<Self>,
 8555    ) {
 8556        self.transact(window, cx, |this, window, cx| {
 8557            this.select_autoclose_pair(window, cx);
 8558            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8559                let line_mode = s.line_mode;
 8560                s.move_with(|map, selection| {
 8561                    if selection.is_empty() && !line_mode {
 8562                        let cursor = if action.ignore_newlines {
 8563                            movement::previous_word_start(map, selection.head())
 8564                        } else {
 8565                            movement::previous_word_start_or_newline(map, selection.head())
 8566                        };
 8567                        selection.set_head(cursor, SelectionGoal::None);
 8568                    }
 8569                });
 8570            });
 8571            this.insert("", window, cx);
 8572        });
 8573    }
 8574
 8575    pub fn delete_to_previous_subword_start(
 8576        &mut self,
 8577        _: &DeleteToPreviousSubwordStart,
 8578        window: &mut Window,
 8579        cx: &mut Context<Self>,
 8580    ) {
 8581        self.transact(window, cx, |this, window, cx| {
 8582            this.select_autoclose_pair(window, cx);
 8583            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8584                let line_mode = s.line_mode;
 8585                s.move_with(|map, selection| {
 8586                    if selection.is_empty() && !line_mode {
 8587                        let cursor = movement::previous_subword_start(map, selection.head());
 8588                        selection.set_head(cursor, SelectionGoal::None);
 8589                    }
 8590                });
 8591            });
 8592            this.insert("", window, cx);
 8593        });
 8594    }
 8595
 8596    pub fn move_to_next_word_end(
 8597        &mut self,
 8598        _: &MoveToNextWordEnd,
 8599        window: &mut Window,
 8600        cx: &mut Context<Self>,
 8601    ) {
 8602        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8603            s.move_cursors_with(|map, head, _| {
 8604                (movement::next_word_end(map, head), SelectionGoal::None)
 8605            });
 8606        })
 8607    }
 8608
 8609    pub fn move_to_next_subword_end(
 8610        &mut self,
 8611        _: &MoveToNextSubwordEnd,
 8612        window: &mut Window,
 8613        cx: &mut Context<Self>,
 8614    ) {
 8615        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8616            s.move_cursors_with(|map, head, _| {
 8617                (movement::next_subword_end(map, head), SelectionGoal::None)
 8618            });
 8619        })
 8620    }
 8621
 8622    pub fn select_to_next_word_end(
 8623        &mut self,
 8624        _: &SelectToNextWordEnd,
 8625        window: &mut Window,
 8626        cx: &mut Context<Self>,
 8627    ) {
 8628        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8629            s.move_heads_with(|map, head, _| {
 8630                (movement::next_word_end(map, head), SelectionGoal::None)
 8631            });
 8632        })
 8633    }
 8634
 8635    pub fn select_to_next_subword_end(
 8636        &mut self,
 8637        _: &SelectToNextSubwordEnd,
 8638        window: &mut Window,
 8639        cx: &mut Context<Self>,
 8640    ) {
 8641        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8642            s.move_heads_with(|map, head, _| {
 8643                (movement::next_subword_end(map, head), SelectionGoal::None)
 8644            });
 8645        })
 8646    }
 8647
 8648    pub fn delete_to_next_word_end(
 8649        &mut self,
 8650        action: &DeleteToNextWordEnd,
 8651        window: &mut Window,
 8652        cx: &mut Context<Self>,
 8653    ) {
 8654        self.transact(window, cx, |this, window, cx| {
 8655            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8656                let line_mode = s.line_mode;
 8657                s.move_with(|map, selection| {
 8658                    if selection.is_empty() && !line_mode {
 8659                        let cursor = if action.ignore_newlines {
 8660                            movement::next_word_end(map, selection.head())
 8661                        } else {
 8662                            movement::next_word_end_or_newline(map, selection.head())
 8663                        };
 8664                        selection.set_head(cursor, SelectionGoal::None);
 8665                    }
 8666                });
 8667            });
 8668            this.insert("", window, cx);
 8669        });
 8670    }
 8671
 8672    pub fn delete_to_next_subword_end(
 8673        &mut self,
 8674        _: &DeleteToNextSubwordEnd,
 8675        window: &mut Window,
 8676        cx: &mut Context<Self>,
 8677    ) {
 8678        self.transact(window, cx, |this, window, cx| {
 8679            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8680                s.move_with(|map, selection| {
 8681                    if selection.is_empty() {
 8682                        let cursor = movement::next_subword_end(map, selection.head());
 8683                        selection.set_head(cursor, SelectionGoal::None);
 8684                    }
 8685                });
 8686            });
 8687            this.insert("", window, cx);
 8688        });
 8689    }
 8690
 8691    pub fn move_to_beginning_of_line(
 8692        &mut self,
 8693        action: &MoveToBeginningOfLine,
 8694        window: &mut Window,
 8695        cx: &mut Context<Self>,
 8696    ) {
 8697        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8698            s.move_cursors_with(|map, head, _| {
 8699                (
 8700                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8701                    SelectionGoal::None,
 8702                )
 8703            });
 8704        })
 8705    }
 8706
 8707    pub fn select_to_beginning_of_line(
 8708        &mut self,
 8709        action: &SelectToBeginningOfLine,
 8710        window: &mut Window,
 8711        cx: &mut Context<Self>,
 8712    ) {
 8713        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8714            s.move_heads_with(|map, head, _| {
 8715                (
 8716                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8717                    SelectionGoal::None,
 8718                )
 8719            });
 8720        });
 8721    }
 8722
 8723    pub fn delete_to_beginning_of_line(
 8724        &mut self,
 8725        _: &DeleteToBeginningOfLine,
 8726        window: &mut Window,
 8727        cx: &mut Context<Self>,
 8728    ) {
 8729        self.transact(window, cx, |this, window, cx| {
 8730            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8731                s.move_with(|_, selection| {
 8732                    selection.reversed = true;
 8733                });
 8734            });
 8735
 8736            this.select_to_beginning_of_line(
 8737                &SelectToBeginningOfLine {
 8738                    stop_at_soft_wraps: false,
 8739                },
 8740                window,
 8741                cx,
 8742            );
 8743            this.backspace(&Backspace, window, cx);
 8744        });
 8745    }
 8746
 8747    pub fn move_to_end_of_line(
 8748        &mut self,
 8749        action: &MoveToEndOfLine,
 8750        window: &mut Window,
 8751        cx: &mut Context<Self>,
 8752    ) {
 8753        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8754            s.move_cursors_with(|map, head, _| {
 8755                (
 8756                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8757                    SelectionGoal::None,
 8758                )
 8759            });
 8760        })
 8761    }
 8762
 8763    pub fn select_to_end_of_line(
 8764        &mut self,
 8765        action: &SelectToEndOfLine,
 8766        window: &mut Window,
 8767        cx: &mut Context<Self>,
 8768    ) {
 8769        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8770            s.move_heads_with(|map, head, _| {
 8771                (
 8772                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8773                    SelectionGoal::None,
 8774                )
 8775            });
 8776        })
 8777    }
 8778
 8779    pub fn delete_to_end_of_line(
 8780        &mut self,
 8781        _: &DeleteToEndOfLine,
 8782        window: &mut Window,
 8783        cx: &mut Context<Self>,
 8784    ) {
 8785        self.transact(window, cx, |this, window, cx| {
 8786            this.select_to_end_of_line(
 8787                &SelectToEndOfLine {
 8788                    stop_at_soft_wraps: false,
 8789                },
 8790                window,
 8791                cx,
 8792            );
 8793            this.delete(&Delete, window, cx);
 8794        });
 8795    }
 8796
 8797    pub fn cut_to_end_of_line(
 8798        &mut self,
 8799        _: &CutToEndOfLine,
 8800        window: &mut Window,
 8801        cx: &mut Context<Self>,
 8802    ) {
 8803        self.transact(window, cx, |this, window, cx| {
 8804            this.select_to_end_of_line(
 8805                &SelectToEndOfLine {
 8806                    stop_at_soft_wraps: false,
 8807                },
 8808                window,
 8809                cx,
 8810            );
 8811            this.cut(&Cut, window, cx);
 8812        });
 8813    }
 8814
 8815    pub fn move_to_start_of_paragraph(
 8816        &mut self,
 8817        _: &MoveToStartOfParagraph,
 8818        window: &mut Window,
 8819        cx: &mut Context<Self>,
 8820    ) {
 8821        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8822            cx.propagate();
 8823            return;
 8824        }
 8825
 8826        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8827            s.move_with(|map, selection| {
 8828                selection.collapse_to(
 8829                    movement::start_of_paragraph(map, selection.head(), 1),
 8830                    SelectionGoal::None,
 8831                )
 8832            });
 8833        })
 8834    }
 8835
 8836    pub fn move_to_end_of_paragraph(
 8837        &mut self,
 8838        _: &MoveToEndOfParagraph,
 8839        window: &mut Window,
 8840        cx: &mut Context<Self>,
 8841    ) {
 8842        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8843            cx.propagate();
 8844            return;
 8845        }
 8846
 8847        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8848            s.move_with(|map, selection| {
 8849                selection.collapse_to(
 8850                    movement::end_of_paragraph(map, selection.head(), 1),
 8851                    SelectionGoal::None,
 8852                )
 8853            });
 8854        })
 8855    }
 8856
 8857    pub fn select_to_start_of_paragraph(
 8858        &mut self,
 8859        _: &SelectToStartOfParagraph,
 8860        window: &mut Window,
 8861        cx: &mut Context<Self>,
 8862    ) {
 8863        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8864            cx.propagate();
 8865            return;
 8866        }
 8867
 8868        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8869            s.move_heads_with(|map, head, _| {
 8870                (
 8871                    movement::start_of_paragraph(map, head, 1),
 8872                    SelectionGoal::None,
 8873                )
 8874            });
 8875        })
 8876    }
 8877
 8878    pub fn select_to_end_of_paragraph(
 8879        &mut self,
 8880        _: &SelectToEndOfParagraph,
 8881        window: &mut Window,
 8882        cx: &mut Context<Self>,
 8883    ) {
 8884        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8885            cx.propagate();
 8886            return;
 8887        }
 8888
 8889        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8890            s.move_heads_with(|map, head, _| {
 8891                (
 8892                    movement::end_of_paragraph(map, head, 1),
 8893                    SelectionGoal::None,
 8894                )
 8895            });
 8896        })
 8897    }
 8898
 8899    pub fn move_to_beginning(
 8900        &mut self,
 8901        _: &MoveToBeginning,
 8902        window: &mut Window,
 8903        cx: &mut Context<Self>,
 8904    ) {
 8905        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8906            cx.propagate();
 8907            return;
 8908        }
 8909
 8910        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8911            s.select_ranges(vec![0..0]);
 8912        });
 8913    }
 8914
 8915    pub fn select_to_beginning(
 8916        &mut self,
 8917        _: &SelectToBeginning,
 8918        window: &mut Window,
 8919        cx: &mut Context<Self>,
 8920    ) {
 8921        let mut selection = self.selections.last::<Point>(cx);
 8922        selection.set_head(Point::zero(), SelectionGoal::None);
 8923
 8924        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8925            s.select(vec![selection]);
 8926        });
 8927    }
 8928
 8929    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8930        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8931            cx.propagate();
 8932            return;
 8933        }
 8934
 8935        let cursor = self.buffer.read(cx).read(cx).len();
 8936        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8937            s.select_ranges(vec![cursor..cursor])
 8938        });
 8939    }
 8940
 8941    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8942        self.nav_history = nav_history;
 8943    }
 8944
 8945    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8946        self.nav_history.as_ref()
 8947    }
 8948
 8949    fn push_to_nav_history(
 8950        &mut self,
 8951        cursor_anchor: Anchor,
 8952        new_position: Option<Point>,
 8953        cx: &mut Context<Self>,
 8954    ) {
 8955        if let Some(nav_history) = self.nav_history.as_mut() {
 8956            let buffer = self.buffer.read(cx).read(cx);
 8957            let cursor_position = cursor_anchor.to_point(&buffer);
 8958            let scroll_state = self.scroll_manager.anchor();
 8959            let scroll_top_row = scroll_state.top_row(&buffer);
 8960            drop(buffer);
 8961
 8962            if let Some(new_position) = new_position {
 8963                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8964                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8965                    return;
 8966                }
 8967            }
 8968
 8969            nav_history.push(
 8970                Some(NavigationData {
 8971                    cursor_anchor,
 8972                    cursor_position,
 8973                    scroll_anchor: scroll_state,
 8974                    scroll_top_row,
 8975                }),
 8976                cx,
 8977            );
 8978        }
 8979    }
 8980
 8981    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8982        let buffer = self.buffer.read(cx).snapshot(cx);
 8983        let mut selection = self.selections.first::<usize>(cx);
 8984        selection.set_head(buffer.len(), SelectionGoal::None);
 8985        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8986            s.select(vec![selection]);
 8987        });
 8988    }
 8989
 8990    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8991        let end = self.buffer.read(cx).read(cx).len();
 8992        self.change_selections(None, window, cx, |s| {
 8993            s.select_ranges(vec![0..end]);
 8994        });
 8995    }
 8996
 8997    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8998        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8999        let mut selections = self.selections.all::<Point>(cx);
 9000        let max_point = display_map.buffer_snapshot.max_point();
 9001        for selection in &mut selections {
 9002            let rows = selection.spanned_rows(true, &display_map);
 9003            selection.start = Point::new(rows.start.0, 0);
 9004            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9005            selection.reversed = false;
 9006        }
 9007        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9008            s.select(selections);
 9009        });
 9010    }
 9011
 9012    pub fn split_selection_into_lines(
 9013        &mut self,
 9014        _: &SplitSelectionIntoLines,
 9015        window: &mut Window,
 9016        cx: &mut Context<Self>,
 9017    ) {
 9018        let mut to_unfold = Vec::new();
 9019        let mut new_selection_ranges = Vec::new();
 9020        {
 9021            let selections = self.selections.all::<Point>(cx);
 9022            let buffer = self.buffer.read(cx).read(cx);
 9023            for selection in selections {
 9024                for row in selection.start.row..selection.end.row {
 9025                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9026                    new_selection_ranges.push(cursor..cursor);
 9027                }
 9028                new_selection_ranges.push(selection.end..selection.end);
 9029                to_unfold.push(selection.start..selection.end);
 9030            }
 9031        }
 9032        self.unfold_ranges(&to_unfold, true, true, cx);
 9033        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9034            s.select_ranges(new_selection_ranges);
 9035        });
 9036    }
 9037
 9038    pub fn add_selection_above(
 9039        &mut self,
 9040        _: &AddSelectionAbove,
 9041        window: &mut Window,
 9042        cx: &mut Context<Self>,
 9043    ) {
 9044        self.add_selection(true, window, cx);
 9045    }
 9046
 9047    pub fn add_selection_below(
 9048        &mut self,
 9049        _: &AddSelectionBelow,
 9050        window: &mut Window,
 9051        cx: &mut Context<Self>,
 9052    ) {
 9053        self.add_selection(false, window, cx);
 9054    }
 9055
 9056    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9057        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9058        let mut selections = self.selections.all::<Point>(cx);
 9059        let text_layout_details = self.text_layout_details(window);
 9060        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9061            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9062            let range = oldest_selection.display_range(&display_map).sorted();
 9063
 9064            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9065            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9066            let positions = start_x.min(end_x)..start_x.max(end_x);
 9067
 9068            selections.clear();
 9069            let mut stack = Vec::new();
 9070            for row in range.start.row().0..=range.end.row().0 {
 9071                if let Some(selection) = self.selections.build_columnar_selection(
 9072                    &display_map,
 9073                    DisplayRow(row),
 9074                    &positions,
 9075                    oldest_selection.reversed,
 9076                    &text_layout_details,
 9077                ) {
 9078                    stack.push(selection.id);
 9079                    selections.push(selection);
 9080                }
 9081            }
 9082
 9083            if above {
 9084                stack.reverse();
 9085            }
 9086
 9087            AddSelectionsState { above, stack }
 9088        });
 9089
 9090        let last_added_selection = *state.stack.last().unwrap();
 9091        let mut new_selections = Vec::new();
 9092        if above == state.above {
 9093            let end_row = if above {
 9094                DisplayRow(0)
 9095            } else {
 9096                display_map.max_point().row()
 9097            };
 9098
 9099            'outer: for selection in selections {
 9100                if selection.id == last_added_selection {
 9101                    let range = selection.display_range(&display_map).sorted();
 9102                    debug_assert_eq!(range.start.row(), range.end.row());
 9103                    let mut row = range.start.row();
 9104                    let positions =
 9105                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9106                            px(start)..px(end)
 9107                        } else {
 9108                            let start_x =
 9109                                display_map.x_for_display_point(range.start, &text_layout_details);
 9110                            let end_x =
 9111                                display_map.x_for_display_point(range.end, &text_layout_details);
 9112                            start_x.min(end_x)..start_x.max(end_x)
 9113                        };
 9114
 9115                    while row != end_row {
 9116                        if above {
 9117                            row.0 -= 1;
 9118                        } else {
 9119                            row.0 += 1;
 9120                        }
 9121
 9122                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9123                            &display_map,
 9124                            row,
 9125                            &positions,
 9126                            selection.reversed,
 9127                            &text_layout_details,
 9128                        ) {
 9129                            state.stack.push(new_selection.id);
 9130                            if above {
 9131                                new_selections.push(new_selection);
 9132                                new_selections.push(selection);
 9133                            } else {
 9134                                new_selections.push(selection);
 9135                                new_selections.push(new_selection);
 9136                            }
 9137
 9138                            continue 'outer;
 9139                        }
 9140                    }
 9141                }
 9142
 9143                new_selections.push(selection);
 9144            }
 9145        } else {
 9146            new_selections = selections;
 9147            new_selections.retain(|s| s.id != last_added_selection);
 9148            state.stack.pop();
 9149        }
 9150
 9151        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9152            s.select(new_selections);
 9153        });
 9154        if state.stack.len() > 1 {
 9155            self.add_selections_state = Some(state);
 9156        }
 9157    }
 9158
 9159    pub fn select_next_match_internal(
 9160        &mut self,
 9161        display_map: &DisplaySnapshot,
 9162        replace_newest: bool,
 9163        autoscroll: Option<Autoscroll>,
 9164        window: &mut Window,
 9165        cx: &mut Context<Self>,
 9166    ) -> Result<()> {
 9167        fn select_next_match_ranges(
 9168            this: &mut Editor,
 9169            range: Range<usize>,
 9170            replace_newest: bool,
 9171            auto_scroll: Option<Autoscroll>,
 9172            window: &mut Window,
 9173            cx: &mut Context<Editor>,
 9174        ) {
 9175            this.unfold_ranges(&[range.clone()], false, true, cx);
 9176            this.change_selections(auto_scroll, window, cx, |s| {
 9177                if replace_newest {
 9178                    s.delete(s.newest_anchor().id);
 9179                }
 9180                s.insert_range(range.clone());
 9181            });
 9182        }
 9183
 9184        let buffer = &display_map.buffer_snapshot;
 9185        let mut selections = self.selections.all::<usize>(cx);
 9186        if let Some(mut select_next_state) = self.select_next_state.take() {
 9187            let query = &select_next_state.query;
 9188            if !select_next_state.done {
 9189                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9190                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9191                let mut next_selected_range = None;
 9192
 9193                let bytes_after_last_selection =
 9194                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9195                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9196                let query_matches = query
 9197                    .stream_find_iter(bytes_after_last_selection)
 9198                    .map(|result| (last_selection.end, result))
 9199                    .chain(
 9200                        query
 9201                            .stream_find_iter(bytes_before_first_selection)
 9202                            .map(|result| (0, result)),
 9203                    );
 9204
 9205                for (start_offset, query_match) in query_matches {
 9206                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9207                    let offset_range =
 9208                        start_offset + query_match.start()..start_offset + query_match.end();
 9209                    let display_range = offset_range.start.to_display_point(display_map)
 9210                        ..offset_range.end.to_display_point(display_map);
 9211
 9212                    if !select_next_state.wordwise
 9213                        || (!movement::is_inside_word(display_map, display_range.start)
 9214                            && !movement::is_inside_word(display_map, display_range.end))
 9215                    {
 9216                        // TODO: This is n^2, because we might check all the selections
 9217                        if !selections
 9218                            .iter()
 9219                            .any(|selection| selection.range().overlaps(&offset_range))
 9220                        {
 9221                            next_selected_range = Some(offset_range);
 9222                            break;
 9223                        }
 9224                    }
 9225                }
 9226
 9227                if let Some(next_selected_range) = next_selected_range {
 9228                    select_next_match_ranges(
 9229                        self,
 9230                        next_selected_range,
 9231                        replace_newest,
 9232                        autoscroll,
 9233                        window,
 9234                        cx,
 9235                    );
 9236                } else {
 9237                    select_next_state.done = true;
 9238                }
 9239            }
 9240
 9241            self.select_next_state = Some(select_next_state);
 9242        } else {
 9243            let mut only_carets = true;
 9244            let mut same_text_selected = true;
 9245            let mut selected_text = None;
 9246
 9247            let mut selections_iter = selections.iter().peekable();
 9248            while let Some(selection) = selections_iter.next() {
 9249                if selection.start != selection.end {
 9250                    only_carets = false;
 9251                }
 9252
 9253                if same_text_selected {
 9254                    if selected_text.is_none() {
 9255                        selected_text =
 9256                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9257                    }
 9258
 9259                    if let Some(next_selection) = selections_iter.peek() {
 9260                        if next_selection.range().len() == selection.range().len() {
 9261                            let next_selected_text = buffer
 9262                                .text_for_range(next_selection.range())
 9263                                .collect::<String>();
 9264                            if Some(next_selected_text) != selected_text {
 9265                                same_text_selected = false;
 9266                                selected_text = None;
 9267                            }
 9268                        } else {
 9269                            same_text_selected = false;
 9270                            selected_text = None;
 9271                        }
 9272                    }
 9273                }
 9274            }
 9275
 9276            if only_carets {
 9277                for selection in &mut selections {
 9278                    let word_range = movement::surrounding_word(
 9279                        display_map,
 9280                        selection.start.to_display_point(display_map),
 9281                    );
 9282                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9283                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9284                    selection.goal = SelectionGoal::None;
 9285                    selection.reversed = false;
 9286                    select_next_match_ranges(
 9287                        self,
 9288                        selection.start..selection.end,
 9289                        replace_newest,
 9290                        autoscroll,
 9291                        window,
 9292                        cx,
 9293                    );
 9294                }
 9295
 9296                if selections.len() == 1 {
 9297                    let selection = selections
 9298                        .last()
 9299                        .expect("ensured that there's only one selection");
 9300                    let query = buffer
 9301                        .text_for_range(selection.start..selection.end)
 9302                        .collect::<String>();
 9303                    let is_empty = query.is_empty();
 9304                    let select_state = SelectNextState {
 9305                        query: AhoCorasick::new(&[query])?,
 9306                        wordwise: true,
 9307                        done: is_empty,
 9308                    };
 9309                    self.select_next_state = Some(select_state);
 9310                } else {
 9311                    self.select_next_state = None;
 9312                }
 9313            } else if let Some(selected_text) = selected_text {
 9314                self.select_next_state = Some(SelectNextState {
 9315                    query: AhoCorasick::new(&[selected_text])?,
 9316                    wordwise: false,
 9317                    done: false,
 9318                });
 9319                self.select_next_match_internal(
 9320                    display_map,
 9321                    replace_newest,
 9322                    autoscroll,
 9323                    window,
 9324                    cx,
 9325                )?;
 9326            }
 9327        }
 9328        Ok(())
 9329    }
 9330
 9331    pub fn select_all_matches(
 9332        &mut self,
 9333        _action: &SelectAllMatches,
 9334        window: &mut Window,
 9335        cx: &mut Context<Self>,
 9336    ) -> Result<()> {
 9337        self.push_to_selection_history();
 9338        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9339
 9340        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9341        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9342            return Ok(());
 9343        };
 9344        if select_next_state.done {
 9345            return Ok(());
 9346        }
 9347
 9348        let mut new_selections = self.selections.all::<usize>(cx);
 9349
 9350        let buffer = &display_map.buffer_snapshot;
 9351        let query_matches = select_next_state
 9352            .query
 9353            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9354
 9355        for query_match in query_matches {
 9356            let query_match = query_match.unwrap(); // can only fail due to I/O
 9357            let offset_range = query_match.start()..query_match.end();
 9358            let display_range = offset_range.start.to_display_point(&display_map)
 9359                ..offset_range.end.to_display_point(&display_map);
 9360
 9361            if !select_next_state.wordwise
 9362                || (!movement::is_inside_word(&display_map, display_range.start)
 9363                    && !movement::is_inside_word(&display_map, display_range.end))
 9364            {
 9365                self.selections.change_with(cx, |selections| {
 9366                    new_selections.push(Selection {
 9367                        id: selections.new_selection_id(),
 9368                        start: offset_range.start,
 9369                        end: offset_range.end,
 9370                        reversed: false,
 9371                        goal: SelectionGoal::None,
 9372                    });
 9373                });
 9374            }
 9375        }
 9376
 9377        new_selections.sort_by_key(|selection| selection.start);
 9378        let mut ix = 0;
 9379        while ix + 1 < new_selections.len() {
 9380            let current_selection = &new_selections[ix];
 9381            let next_selection = &new_selections[ix + 1];
 9382            if current_selection.range().overlaps(&next_selection.range()) {
 9383                if current_selection.id < next_selection.id {
 9384                    new_selections.remove(ix + 1);
 9385                } else {
 9386                    new_selections.remove(ix);
 9387                }
 9388            } else {
 9389                ix += 1;
 9390            }
 9391        }
 9392
 9393        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9394
 9395        for selection in new_selections.iter_mut() {
 9396            selection.reversed = reversed;
 9397        }
 9398
 9399        select_next_state.done = true;
 9400        self.unfold_ranges(
 9401            &new_selections
 9402                .iter()
 9403                .map(|selection| selection.range())
 9404                .collect::<Vec<_>>(),
 9405            false,
 9406            false,
 9407            cx,
 9408        );
 9409        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9410            selections.select(new_selections)
 9411        });
 9412
 9413        Ok(())
 9414    }
 9415
 9416    pub fn select_next(
 9417        &mut self,
 9418        action: &SelectNext,
 9419        window: &mut Window,
 9420        cx: &mut Context<Self>,
 9421    ) -> Result<()> {
 9422        self.push_to_selection_history();
 9423        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9424        self.select_next_match_internal(
 9425            &display_map,
 9426            action.replace_newest,
 9427            Some(Autoscroll::newest()),
 9428            window,
 9429            cx,
 9430        )?;
 9431        Ok(())
 9432    }
 9433
 9434    pub fn select_previous(
 9435        &mut self,
 9436        action: &SelectPrevious,
 9437        window: &mut Window,
 9438        cx: &mut Context<Self>,
 9439    ) -> Result<()> {
 9440        self.push_to_selection_history();
 9441        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9442        let buffer = &display_map.buffer_snapshot;
 9443        let mut selections = self.selections.all::<usize>(cx);
 9444        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9445            let query = &select_prev_state.query;
 9446            if !select_prev_state.done {
 9447                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9448                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9449                let mut next_selected_range = None;
 9450                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9451                let bytes_before_last_selection =
 9452                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9453                let bytes_after_first_selection =
 9454                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9455                let query_matches = query
 9456                    .stream_find_iter(bytes_before_last_selection)
 9457                    .map(|result| (last_selection.start, result))
 9458                    .chain(
 9459                        query
 9460                            .stream_find_iter(bytes_after_first_selection)
 9461                            .map(|result| (buffer.len(), result)),
 9462                    );
 9463                for (end_offset, query_match) in query_matches {
 9464                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9465                    let offset_range =
 9466                        end_offset - query_match.end()..end_offset - query_match.start();
 9467                    let display_range = offset_range.start.to_display_point(&display_map)
 9468                        ..offset_range.end.to_display_point(&display_map);
 9469
 9470                    if !select_prev_state.wordwise
 9471                        || (!movement::is_inside_word(&display_map, display_range.start)
 9472                            && !movement::is_inside_word(&display_map, display_range.end))
 9473                    {
 9474                        next_selected_range = Some(offset_range);
 9475                        break;
 9476                    }
 9477                }
 9478
 9479                if let Some(next_selected_range) = next_selected_range {
 9480                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9481                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9482                        if action.replace_newest {
 9483                            s.delete(s.newest_anchor().id);
 9484                        }
 9485                        s.insert_range(next_selected_range);
 9486                    });
 9487                } else {
 9488                    select_prev_state.done = true;
 9489                }
 9490            }
 9491
 9492            self.select_prev_state = Some(select_prev_state);
 9493        } else {
 9494            let mut only_carets = true;
 9495            let mut same_text_selected = true;
 9496            let mut selected_text = None;
 9497
 9498            let mut selections_iter = selections.iter().peekable();
 9499            while let Some(selection) = selections_iter.next() {
 9500                if selection.start != selection.end {
 9501                    only_carets = false;
 9502                }
 9503
 9504                if same_text_selected {
 9505                    if selected_text.is_none() {
 9506                        selected_text =
 9507                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9508                    }
 9509
 9510                    if let Some(next_selection) = selections_iter.peek() {
 9511                        if next_selection.range().len() == selection.range().len() {
 9512                            let next_selected_text = buffer
 9513                                .text_for_range(next_selection.range())
 9514                                .collect::<String>();
 9515                            if Some(next_selected_text) != selected_text {
 9516                                same_text_selected = false;
 9517                                selected_text = None;
 9518                            }
 9519                        } else {
 9520                            same_text_selected = false;
 9521                            selected_text = None;
 9522                        }
 9523                    }
 9524                }
 9525            }
 9526
 9527            if only_carets {
 9528                for selection in &mut selections {
 9529                    let word_range = movement::surrounding_word(
 9530                        &display_map,
 9531                        selection.start.to_display_point(&display_map),
 9532                    );
 9533                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9534                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9535                    selection.goal = SelectionGoal::None;
 9536                    selection.reversed = false;
 9537                }
 9538                if selections.len() == 1 {
 9539                    let selection = selections
 9540                        .last()
 9541                        .expect("ensured that there's only one selection");
 9542                    let query = buffer
 9543                        .text_for_range(selection.start..selection.end)
 9544                        .collect::<String>();
 9545                    let is_empty = query.is_empty();
 9546                    let select_state = SelectNextState {
 9547                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9548                        wordwise: true,
 9549                        done: is_empty,
 9550                    };
 9551                    self.select_prev_state = Some(select_state);
 9552                } else {
 9553                    self.select_prev_state = None;
 9554                }
 9555
 9556                self.unfold_ranges(
 9557                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9558                    false,
 9559                    true,
 9560                    cx,
 9561                );
 9562                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9563                    s.select(selections);
 9564                });
 9565            } else if let Some(selected_text) = selected_text {
 9566                self.select_prev_state = Some(SelectNextState {
 9567                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9568                    wordwise: false,
 9569                    done: false,
 9570                });
 9571                self.select_previous(action, window, cx)?;
 9572            }
 9573        }
 9574        Ok(())
 9575    }
 9576
 9577    pub fn toggle_comments(
 9578        &mut self,
 9579        action: &ToggleComments,
 9580        window: &mut Window,
 9581        cx: &mut Context<Self>,
 9582    ) {
 9583        if self.read_only(cx) {
 9584            return;
 9585        }
 9586        let text_layout_details = &self.text_layout_details(window);
 9587        self.transact(window, cx, |this, window, cx| {
 9588            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9589            let mut edits = Vec::new();
 9590            let mut selection_edit_ranges = Vec::new();
 9591            let mut last_toggled_row = None;
 9592            let snapshot = this.buffer.read(cx).read(cx);
 9593            let empty_str: Arc<str> = Arc::default();
 9594            let mut suffixes_inserted = Vec::new();
 9595            let ignore_indent = action.ignore_indent;
 9596
 9597            fn comment_prefix_range(
 9598                snapshot: &MultiBufferSnapshot,
 9599                row: MultiBufferRow,
 9600                comment_prefix: &str,
 9601                comment_prefix_whitespace: &str,
 9602                ignore_indent: bool,
 9603            ) -> Range<Point> {
 9604                let indent_size = if ignore_indent {
 9605                    0
 9606                } else {
 9607                    snapshot.indent_size_for_line(row).len
 9608                };
 9609
 9610                let start = Point::new(row.0, indent_size);
 9611
 9612                let mut line_bytes = snapshot
 9613                    .bytes_in_range(start..snapshot.max_point())
 9614                    .flatten()
 9615                    .copied();
 9616
 9617                // If this line currently begins with the line comment prefix, then record
 9618                // the range containing the prefix.
 9619                if line_bytes
 9620                    .by_ref()
 9621                    .take(comment_prefix.len())
 9622                    .eq(comment_prefix.bytes())
 9623                {
 9624                    // Include any whitespace that matches the comment prefix.
 9625                    let matching_whitespace_len = line_bytes
 9626                        .zip(comment_prefix_whitespace.bytes())
 9627                        .take_while(|(a, b)| a == b)
 9628                        .count() as u32;
 9629                    let end = Point::new(
 9630                        start.row,
 9631                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9632                    );
 9633                    start..end
 9634                } else {
 9635                    start..start
 9636                }
 9637            }
 9638
 9639            fn comment_suffix_range(
 9640                snapshot: &MultiBufferSnapshot,
 9641                row: MultiBufferRow,
 9642                comment_suffix: &str,
 9643                comment_suffix_has_leading_space: bool,
 9644            ) -> Range<Point> {
 9645                let end = Point::new(row.0, snapshot.line_len(row));
 9646                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9647
 9648                let mut line_end_bytes = snapshot
 9649                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9650                    .flatten()
 9651                    .copied();
 9652
 9653                let leading_space_len = if suffix_start_column > 0
 9654                    && line_end_bytes.next() == Some(b' ')
 9655                    && comment_suffix_has_leading_space
 9656                {
 9657                    1
 9658                } else {
 9659                    0
 9660                };
 9661
 9662                // If this line currently begins with the line comment prefix, then record
 9663                // the range containing the prefix.
 9664                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9665                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9666                    start..end
 9667                } else {
 9668                    end..end
 9669                }
 9670            }
 9671
 9672            // TODO: Handle selections that cross excerpts
 9673            for selection in &mut selections {
 9674                let start_column = snapshot
 9675                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9676                    .len;
 9677                let language = if let Some(language) =
 9678                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9679                {
 9680                    language
 9681                } else {
 9682                    continue;
 9683                };
 9684
 9685                selection_edit_ranges.clear();
 9686
 9687                // If multiple selections contain a given row, avoid processing that
 9688                // row more than once.
 9689                let mut start_row = MultiBufferRow(selection.start.row);
 9690                if last_toggled_row == Some(start_row) {
 9691                    start_row = start_row.next_row();
 9692                }
 9693                let end_row =
 9694                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9695                        MultiBufferRow(selection.end.row - 1)
 9696                    } else {
 9697                        MultiBufferRow(selection.end.row)
 9698                    };
 9699                last_toggled_row = Some(end_row);
 9700
 9701                if start_row > end_row {
 9702                    continue;
 9703                }
 9704
 9705                // If the language has line comments, toggle those.
 9706                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9707
 9708                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9709                if ignore_indent {
 9710                    full_comment_prefixes = full_comment_prefixes
 9711                        .into_iter()
 9712                        .map(|s| Arc::from(s.trim_end()))
 9713                        .collect();
 9714                }
 9715
 9716                if !full_comment_prefixes.is_empty() {
 9717                    let first_prefix = full_comment_prefixes
 9718                        .first()
 9719                        .expect("prefixes is non-empty");
 9720                    let prefix_trimmed_lengths = full_comment_prefixes
 9721                        .iter()
 9722                        .map(|p| p.trim_end_matches(' ').len())
 9723                        .collect::<SmallVec<[usize; 4]>>();
 9724
 9725                    let mut all_selection_lines_are_comments = true;
 9726
 9727                    for row in start_row.0..=end_row.0 {
 9728                        let row = MultiBufferRow(row);
 9729                        if start_row < end_row && snapshot.is_line_blank(row) {
 9730                            continue;
 9731                        }
 9732
 9733                        let prefix_range = full_comment_prefixes
 9734                            .iter()
 9735                            .zip(prefix_trimmed_lengths.iter().copied())
 9736                            .map(|(prefix, trimmed_prefix_len)| {
 9737                                comment_prefix_range(
 9738                                    snapshot.deref(),
 9739                                    row,
 9740                                    &prefix[..trimmed_prefix_len],
 9741                                    &prefix[trimmed_prefix_len..],
 9742                                    ignore_indent,
 9743                                )
 9744                            })
 9745                            .max_by_key(|range| range.end.column - range.start.column)
 9746                            .expect("prefixes is non-empty");
 9747
 9748                        if prefix_range.is_empty() {
 9749                            all_selection_lines_are_comments = false;
 9750                        }
 9751
 9752                        selection_edit_ranges.push(prefix_range);
 9753                    }
 9754
 9755                    if all_selection_lines_are_comments {
 9756                        edits.extend(
 9757                            selection_edit_ranges
 9758                                .iter()
 9759                                .cloned()
 9760                                .map(|range| (range, empty_str.clone())),
 9761                        );
 9762                    } else {
 9763                        let min_column = selection_edit_ranges
 9764                            .iter()
 9765                            .map(|range| range.start.column)
 9766                            .min()
 9767                            .unwrap_or(0);
 9768                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9769                            let position = Point::new(range.start.row, min_column);
 9770                            (position..position, first_prefix.clone())
 9771                        }));
 9772                    }
 9773                } else if let Some((full_comment_prefix, comment_suffix)) =
 9774                    language.block_comment_delimiters()
 9775                {
 9776                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9777                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9778                    let prefix_range = comment_prefix_range(
 9779                        snapshot.deref(),
 9780                        start_row,
 9781                        comment_prefix,
 9782                        comment_prefix_whitespace,
 9783                        ignore_indent,
 9784                    );
 9785                    let suffix_range = comment_suffix_range(
 9786                        snapshot.deref(),
 9787                        end_row,
 9788                        comment_suffix.trim_start_matches(' '),
 9789                        comment_suffix.starts_with(' '),
 9790                    );
 9791
 9792                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9793                        edits.push((
 9794                            prefix_range.start..prefix_range.start,
 9795                            full_comment_prefix.clone(),
 9796                        ));
 9797                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9798                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9799                    } else {
 9800                        edits.push((prefix_range, empty_str.clone()));
 9801                        edits.push((suffix_range, empty_str.clone()));
 9802                    }
 9803                } else {
 9804                    continue;
 9805                }
 9806            }
 9807
 9808            drop(snapshot);
 9809            this.buffer.update(cx, |buffer, cx| {
 9810                buffer.edit(edits, None, cx);
 9811            });
 9812
 9813            // Adjust selections so that they end before any comment suffixes that
 9814            // were inserted.
 9815            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9816            let mut selections = this.selections.all::<Point>(cx);
 9817            let snapshot = this.buffer.read(cx).read(cx);
 9818            for selection in &mut selections {
 9819                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9820                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9821                        Ordering::Less => {
 9822                            suffixes_inserted.next();
 9823                            continue;
 9824                        }
 9825                        Ordering::Greater => break,
 9826                        Ordering::Equal => {
 9827                            if selection.end.column == snapshot.line_len(row) {
 9828                                if selection.is_empty() {
 9829                                    selection.start.column -= suffix_len as u32;
 9830                                }
 9831                                selection.end.column -= suffix_len as u32;
 9832                            }
 9833                            break;
 9834                        }
 9835                    }
 9836                }
 9837            }
 9838
 9839            drop(snapshot);
 9840            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9841                s.select(selections)
 9842            });
 9843
 9844            let selections = this.selections.all::<Point>(cx);
 9845            let selections_on_single_row = selections.windows(2).all(|selections| {
 9846                selections[0].start.row == selections[1].start.row
 9847                    && selections[0].end.row == selections[1].end.row
 9848                    && selections[0].start.row == selections[0].end.row
 9849            });
 9850            let selections_selecting = selections
 9851                .iter()
 9852                .any(|selection| selection.start != selection.end);
 9853            let advance_downwards = action.advance_downwards
 9854                && selections_on_single_row
 9855                && !selections_selecting
 9856                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9857
 9858            if advance_downwards {
 9859                let snapshot = this.buffer.read(cx).snapshot(cx);
 9860
 9861                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9862                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9863                        let mut point = display_point.to_point(display_snapshot);
 9864                        point.row += 1;
 9865                        point = snapshot.clip_point(point, Bias::Left);
 9866                        let display_point = point.to_display_point(display_snapshot);
 9867                        let goal = SelectionGoal::HorizontalPosition(
 9868                            display_snapshot
 9869                                .x_for_display_point(display_point, text_layout_details)
 9870                                .into(),
 9871                        );
 9872                        (display_point, goal)
 9873                    })
 9874                });
 9875            }
 9876        });
 9877    }
 9878
 9879    pub fn select_enclosing_symbol(
 9880        &mut self,
 9881        _: &SelectEnclosingSymbol,
 9882        window: &mut Window,
 9883        cx: &mut Context<Self>,
 9884    ) {
 9885        let buffer = self.buffer.read(cx).snapshot(cx);
 9886        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9887
 9888        fn update_selection(
 9889            selection: &Selection<usize>,
 9890            buffer_snap: &MultiBufferSnapshot,
 9891        ) -> Option<Selection<usize>> {
 9892            let cursor = selection.head();
 9893            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9894            for symbol in symbols.iter().rev() {
 9895                let start = symbol.range.start.to_offset(buffer_snap);
 9896                let end = symbol.range.end.to_offset(buffer_snap);
 9897                let new_range = start..end;
 9898                if start < selection.start || end > selection.end {
 9899                    return Some(Selection {
 9900                        id: selection.id,
 9901                        start: new_range.start,
 9902                        end: new_range.end,
 9903                        goal: SelectionGoal::None,
 9904                        reversed: selection.reversed,
 9905                    });
 9906                }
 9907            }
 9908            None
 9909        }
 9910
 9911        let mut selected_larger_symbol = false;
 9912        let new_selections = old_selections
 9913            .iter()
 9914            .map(|selection| match update_selection(selection, &buffer) {
 9915                Some(new_selection) => {
 9916                    if new_selection.range() != selection.range() {
 9917                        selected_larger_symbol = true;
 9918                    }
 9919                    new_selection
 9920                }
 9921                None => selection.clone(),
 9922            })
 9923            .collect::<Vec<_>>();
 9924
 9925        if selected_larger_symbol {
 9926            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9927                s.select(new_selections);
 9928            });
 9929        }
 9930    }
 9931
 9932    pub fn select_larger_syntax_node(
 9933        &mut self,
 9934        _: &SelectLargerSyntaxNode,
 9935        window: &mut Window,
 9936        cx: &mut Context<Self>,
 9937    ) {
 9938        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9939        let buffer = self.buffer.read(cx).snapshot(cx);
 9940        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9941
 9942        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9943        let mut selected_larger_node = false;
 9944        let new_selections = old_selections
 9945            .iter()
 9946            .map(|selection| {
 9947                let old_range = selection.start..selection.end;
 9948                let mut new_range = old_range.clone();
 9949                let mut new_node = None;
 9950                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9951                {
 9952                    new_node = Some(node);
 9953                    new_range = containing_range;
 9954                    if !display_map.intersects_fold(new_range.start)
 9955                        && !display_map.intersects_fold(new_range.end)
 9956                    {
 9957                        break;
 9958                    }
 9959                }
 9960
 9961                if let Some(node) = new_node {
 9962                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9963                    // nodes. Parent and grandparent are also logged because this operation will not
 9964                    // visit nodes that have the same range as their parent.
 9965                    log::info!("Node: {node:?}");
 9966                    let parent = node.parent();
 9967                    log::info!("Parent: {parent:?}");
 9968                    let grandparent = parent.and_then(|x| x.parent());
 9969                    log::info!("Grandparent: {grandparent:?}");
 9970                }
 9971
 9972                selected_larger_node |= new_range != old_range;
 9973                Selection {
 9974                    id: selection.id,
 9975                    start: new_range.start,
 9976                    end: new_range.end,
 9977                    goal: SelectionGoal::None,
 9978                    reversed: selection.reversed,
 9979                }
 9980            })
 9981            .collect::<Vec<_>>();
 9982
 9983        if selected_larger_node {
 9984            stack.push(old_selections);
 9985            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9986                s.select(new_selections);
 9987            });
 9988        }
 9989        self.select_larger_syntax_node_stack = stack;
 9990    }
 9991
 9992    pub fn select_smaller_syntax_node(
 9993        &mut self,
 9994        _: &SelectSmallerSyntaxNode,
 9995        window: &mut Window,
 9996        cx: &mut Context<Self>,
 9997    ) {
 9998        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9999        if let Some(selections) = stack.pop() {
10000            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10001                s.select(selections.to_vec());
10002            });
10003        }
10004        self.select_larger_syntax_node_stack = stack;
10005    }
10006
10007    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10008        if !EditorSettings::get_global(cx).gutter.runnables {
10009            self.clear_tasks();
10010            return Task::ready(());
10011        }
10012        let project = self.project.as_ref().map(Entity::downgrade);
10013        cx.spawn_in(window, |this, mut cx| async move {
10014            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10015            let Some(project) = project.and_then(|p| p.upgrade()) else {
10016                return;
10017            };
10018            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10019                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10020            }) else {
10021                return;
10022            };
10023
10024            let hide_runnables = project
10025                .update(&mut cx, |project, cx| {
10026                    // Do not display any test indicators in non-dev server remote projects.
10027                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10028                })
10029                .unwrap_or(true);
10030            if hide_runnables {
10031                return;
10032            }
10033            let new_rows =
10034                cx.background_executor()
10035                    .spawn({
10036                        let snapshot = display_snapshot.clone();
10037                        async move {
10038                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10039                        }
10040                    })
10041                    .await;
10042
10043            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10044            this.update(&mut cx, |this, _| {
10045                this.clear_tasks();
10046                for (key, value) in rows {
10047                    this.insert_tasks(key, value);
10048                }
10049            })
10050            .ok();
10051        })
10052    }
10053    fn fetch_runnable_ranges(
10054        snapshot: &DisplaySnapshot,
10055        range: Range<Anchor>,
10056    ) -> Vec<language::RunnableRange> {
10057        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10058    }
10059
10060    fn runnable_rows(
10061        project: Entity<Project>,
10062        snapshot: DisplaySnapshot,
10063        runnable_ranges: Vec<RunnableRange>,
10064        mut cx: AsyncWindowContext,
10065    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10066        runnable_ranges
10067            .into_iter()
10068            .filter_map(|mut runnable| {
10069                let tasks = cx
10070                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10071                    .ok()?;
10072                if tasks.is_empty() {
10073                    return None;
10074                }
10075
10076                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10077
10078                let row = snapshot
10079                    .buffer_snapshot
10080                    .buffer_line_for_row(MultiBufferRow(point.row))?
10081                    .1
10082                    .start
10083                    .row;
10084
10085                let context_range =
10086                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10087                Some((
10088                    (runnable.buffer_id, row),
10089                    RunnableTasks {
10090                        templates: tasks,
10091                        offset: MultiBufferOffset(runnable.run_range.start),
10092                        context_range,
10093                        column: point.column,
10094                        extra_variables: runnable.extra_captures,
10095                    },
10096                ))
10097            })
10098            .collect()
10099    }
10100
10101    fn templates_with_tags(
10102        project: &Entity<Project>,
10103        runnable: &mut Runnable,
10104        cx: &mut App,
10105    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10106        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10107            let (worktree_id, file) = project
10108                .buffer_for_id(runnable.buffer, cx)
10109                .and_then(|buffer| buffer.read(cx).file())
10110                .map(|file| (file.worktree_id(cx), file.clone()))
10111                .unzip();
10112
10113            (
10114                project.task_store().read(cx).task_inventory().cloned(),
10115                worktree_id,
10116                file,
10117            )
10118        });
10119
10120        let tags = mem::take(&mut runnable.tags);
10121        let mut tags: Vec<_> = tags
10122            .into_iter()
10123            .flat_map(|tag| {
10124                let tag = tag.0.clone();
10125                inventory
10126                    .as_ref()
10127                    .into_iter()
10128                    .flat_map(|inventory| {
10129                        inventory.read(cx).list_tasks(
10130                            file.clone(),
10131                            Some(runnable.language.clone()),
10132                            worktree_id,
10133                            cx,
10134                        )
10135                    })
10136                    .filter(move |(_, template)| {
10137                        template.tags.iter().any(|source_tag| source_tag == &tag)
10138                    })
10139            })
10140            .sorted_by_key(|(kind, _)| kind.to_owned())
10141            .collect();
10142        if let Some((leading_tag_source, _)) = tags.first() {
10143            // Strongest source wins; if we have worktree tag binding, prefer that to
10144            // global and language bindings;
10145            // if we have a global binding, prefer that to language binding.
10146            let first_mismatch = tags
10147                .iter()
10148                .position(|(tag_source, _)| tag_source != leading_tag_source);
10149            if let Some(index) = first_mismatch {
10150                tags.truncate(index);
10151            }
10152        }
10153
10154        tags
10155    }
10156
10157    pub fn move_to_enclosing_bracket(
10158        &mut self,
10159        _: &MoveToEnclosingBracket,
10160        window: &mut Window,
10161        cx: &mut Context<Self>,
10162    ) {
10163        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10164            s.move_offsets_with(|snapshot, selection| {
10165                let Some(enclosing_bracket_ranges) =
10166                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10167                else {
10168                    return;
10169                };
10170
10171                let mut best_length = usize::MAX;
10172                let mut best_inside = false;
10173                let mut best_in_bracket_range = false;
10174                let mut best_destination = None;
10175                for (open, close) in enclosing_bracket_ranges {
10176                    let close = close.to_inclusive();
10177                    let length = close.end() - open.start;
10178                    let inside = selection.start >= open.end && selection.end <= *close.start();
10179                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10180                        || close.contains(&selection.head());
10181
10182                    // If best is next to a bracket and current isn't, skip
10183                    if !in_bracket_range && best_in_bracket_range {
10184                        continue;
10185                    }
10186
10187                    // Prefer smaller lengths unless best is inside and current isn't
10188                    if length > best_length && (best_inside || !inside) {
10189                        continue;
10190                    }
10191
10192                    best_length = length;
10193                    best_inside = inside;
10194                    best_in_bracket_range = in_bracket_range;
10195                    best_destination = Some(
10196                        if close.contains(&selection.start) && close.contains(&selection.end) {
10197                            if inside {
10198                                open.end
10199                            } else {
10200                                open.start
10201                            }
10202                        } else if inside {
10203                            *close.start()
10204                        } else {
10205                            *close.end()
10206                        },
10207                    );
10208                }
10209
10210                if let Some(destination) = best_destination {
10211                    selection.collapse_to(destination, SelectionGoal::None);
10212                }
10213            })
10214        });
10215    }
10216
10217    pub fn undo_selection(
10218        &mut self,
10219        _: &UndoSelection,
10220        window: &mut Window,
10221        cx: &mut Context<Self>,
10222    ) {
10223        self.end_selection(window, cx);
10224        self.selection_history.mode = SelectionHistoryMode::Undoing;
10225        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10226            self.change_selections(None, window, cx, |s| {
10227                s.select_anchors(entry.selections.to_vec())
10228            });
10229            self.select_next_state = entry.select_next_state;
10230            self.select_prev_state = entry.select_prev_state;
10231            self.add_selections_state = entry.add_selections_state;
10232            self.request_autoscroll(Autoscroll::newest(), cx);
10233        }
10234        self.selection_history.mode = SelectionHistoryMode::Normal;
10235    }
10236
10237    pub fn redo_selection(
10238        &mut self,
10239        _: &RedoSelection,
10240        window: &mut Window,
10241        cx: &mut Context<Self>,
10242    ) {
10243        self.end_selection(window, cx);
10244        self.selection_history.mode = SelectionHistoryMode::Redoing;
10245        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10246            self.change_selections(None, window, cx, |s| {
10247                s.select_anchors(entry.selections.to_vec())
10248            });
10249            self.select_next_state = entry.select_next_state;
10250            self.select_prev_state = entry.select_prev_state;
10251            self.add_selections_state = entry.add_selections_state;
10252            self.request_autoscroll(Autoscroll::newest(), cx);
10253        }
10254        self.selection_history.mode = SelectionHistoryMode::Normal;
10255    }
10256
10257    pub fn expand_excerpts(
10258        &mut self,
10259        action: &ExpandExcerpts,
10260        _: &mut Window,
10261        cx: &mut Context<Self>,
10262    ) {
10263        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10264    }
10265
10266    pub fn expand_excerpts_down(
10267        &mut self,
10268        action: &ExpandExcerptsDown,
10269        _: &mut Window,
10270        cx: &mut Context<Self>,
10271    ) {
10272        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10273    }
10274
10275    pub fn expand_excerpts_up(
10276        &mut self,
10277        action: &ExpandExcerptsUp,
10278        _: &mut Window,
10279        cx: &mut Context<Self>,
10280    ) {
10281        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10282    }
10283
10284    pub fn expand_excerpts_for_direction(
10285        &mut self,
10286        lines: u32,
10287        direction: ExpandExcerptDirection,
10288
10289        cx: &mut Context<Self>,
10290    ) {
10291        let selections = self.selections.disjoint_anchors();
10292
10293        let lines = if lines == 0 {
10294            EditorSettings::get_global(cx).expand_excerpt_lines
10295        } else {
10296            lines
10297        };
10298
10299        self.buffer.update(cx, |buffer, cx| {
10300            let snapshot = buffer.snapshot(cx);
10301            let mut excerpt_ids = selections
10302                .iter()
10303                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10304                .collect::<Vec<_>>();
10305            excerpt_ids.sort();
10306            excerpt_ids.dedup();
10307            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10308        })
10309    }
10310
10311    pub fn expand_excerpt(
10312        &mut self,
10313        excerpt: ExcerptId,
10314        direction: ExpandExcerptDirection,
10315        cx: &mut Context<Self>,
10316    ) {
10317        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10318        self.buffer.update(cx, |buffer, cx| {
10319            buffer.expand_excerpts([excerpt], lines, direction, cx)
10320        })
10321    }
10322
10323    pub fn go_to_singleton_buffer_point(
10324        &mut self,
10325        point: Point,
10326        window: &mut Window,
10327        cx: &mut Context<Self>,
10328    ) {
10329        self.go_to_singleton_buffer_range(point..point, window, cx);
10330    }
10331
10332    pub fn go_to_singleton_buffer_range(
10333        &mut self,
10334        range: Range<Point>,
10335        window: &mut Window,
10336        cx: &mut Context<Self>,
10337    ) {
10338        let multibuffer = self.buffer().read(cx);
10339        let Some(buffer) = multibuffer.as_singleton() else {
10340            return;
10341        };
10342        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10343            return;
10344        };
10345        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10346            return;
10347        };
10348        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10349            s.select_anchor_ranges([start..end])
10350        });
10351    }
10352
10353    fn go_to_diagnostic(
10354        &mut self,
10355        _: &GoToDiagnostic,
10356        window: &mut Window,
10357        cx: &mut Context<Self>,
10358    ) {
10359        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10360    }
10361
10362    fn go_to_prev_diagnostic(
10363        &mut self,
10364        _: &GoToPrevDiagnostic,
10365        window: &mut Window,
10366        cx: &mut Context<Self>,
10367    ) {
10368        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10369    }
10370
10371    pub fn go_to_diagnostic_impl(
10372        &mut self,
10373        direction: Direction,
10374        window: &mut Window,
10375        cx: &mut Context<Self>,
10376    ) {
10377        let buffer = self.buffer.read(cx).snapshot(cx);
10378        let selection = self.selections.newest::<usize>(cx);
10379
10380        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10381        if direction == Direction::Next {
10382            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10383                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10384                    return;
10385                };
10386                self.activate_diagnostics(
10387                    buffer_id,
10388                    popover.local_diagnostic.diagnostic.group_id,
10389                    window,
10390                    cx,
10391                );
10392                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10393                    let primary_range_start = active_diagnostics.primary_range.start;
10394                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10395                        let mut new_selection = s.newest_anchor().clone();
10396                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10397                        s.select_anchors(vec![new_selection.clone()]);
10398                    });
10399                    self.refresh_inline_completion(false, true, window, cx);
10400                }
10401                return;
10402            }
10403        }
10404
10405        let active_group_id = self
10406            .active_diagnostics
10407            .as_ref()
10408            .map(|active_group| active_group.group_id);
10409        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10410            active_diagnostics
10411                .primary_range
10412                .to_offset(&buffer)
10413                .to_inclusive()
10414        });
10415        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10416            if active_primary_range.contains(&selection.head()) {
10417                *active_primary_range.start()
10418            } else {
10419                selection.head()
10420            }
10421        } else {
10422            selection.head()
10423        };
10424
10425        let snapshot = self.snapshot(window, cx);
10426        let primary_diagnostics_before = buffer
10427            .diagnostics_in_range::<usize>(0..search_start)
10428            .filter(|entry| entry.diagnostic.is_primary)
10429            .filter(|entry| entry.range.start != entry.range.end)
10430            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10431            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10432            .collect::<Vec<_>>();
10433        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10434            primary_diagnostics_before
10435                .iter()
10436                .position(|entry| entry.diagnostic.group_id == active_group_id)
10437        });
10438
10439        let primary_diagnostics_after = buffer
10440            .diagnostics_in_range::<usize>(search_start..buffer.len())
10441            .filter(|entry| entry.diagnostic.is_primary)
10442            .filter(|entry| entry.range.start != entry.range.end)
10443            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10444            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10445            .collect::<Vec<_>>();
10446        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10447            primary_diagnostics_after
10448                .iter()
10449                .enumerate()
10450                .rev()
10451                .find_map(|(i, entry)| {
10452                    if entry.diagnostic.group_id == active_group_id {
10453                        Some(i)
10454                    } else {
10455                        None
10456                    }
10457                })
10458        });
10459
10460        let next_primary_diagnostic = match direction {
10461            Direction::Prev => primary_diagnostics_before
10462                .iter()
10463                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10464                .rev()
10465                .next(),
10466            Direction::Next => primary_diagnostics_after
10467                .iter()
10468                .skip(
10469                    last_same_group_diagnostic_after
10470                        .map(|index| index + 1)
10471                        .unwrap_or(0),
10472                )
10473                .next(),
10474        };
10475
10476        // Cycle around to the start of the buffer, potentially moving back to the start of
10477        // the currently active diagnostic.
10478        let cycle_around = || match direction {
10479            Direction::Prev => primary_diagnostics_after
10480                .iter()
10481                .rev()
10482                .chain(primary_diagnostics_before.iter().rev())
10483                .next(),
10484            Direction::Next => primary_diagnostics_before
10485                .iter()
10486                .chain(primary_diagnostics_after.iter())
10487                .next(),
10488        };
10489
10490        if let Some((primary_range, group_id)) = next_primary_diagnostic
10491            .or_else(cycle_around)
10492            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10493        {
10494            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10495                return;
10496            };
10497            self.activate_diagnostics(buffer_id, group_id, window, cx);
10498            if self.active_diagnostics.is_some() {
10499                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10500                    s.select(vec![Selection {
10501                        id: selection.id,
10502                        start: primary_range.start,
10503                        end: primary_range.start,
10504                        reversed: false,
10505                        goal: SelectionGoal::None,
10506                    }]);
10507                });
10508                self.refresh_inline_completion(false, true, window, cx);
10509            }
10510        }
10511    }
10512
10513    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10514        let snapshot = self.snapshot(window, cx);
10515        let selection = self.selections.newest::<Point>(cx);
10516        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10517    }
10518
10519    fn go_to_hunk_after_position(
10520        &mut self,
10521        snapshot: &EditorSnapshot,
10522        position: Point,
10523        window: &mut Window,
10524        cx: &mut Context<Editor>,
10525    ) -> Option<MultiBufferDiffHunk> {
10526        let mut hunk = snapshot
10527            .buffer_snapshot
10528            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10529            .find(|hunk| hunk.row_range.start.0 > position.row);
10530        if hunk.is_none() {
10531            hunk = snapshot
10532                .buffer_snapshot
10533                .diff_hunks_in_range(Point::zero()..position)
10534                .find(|hunk| hunk.row_range.end.0 < position.row)
10535        }
10536        if let Some(hunk) = &hunk {
10537            let destination = Point::new(hunk.row_range.start.0, 0);
10538            self.unfold_ranges(&[destination..destination], false, false, cx);
10539            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10540                s.select_ranges(vec![destination..destination]);
10541            });
10542        }
10543
10544        hunk
10545    }
10546
10547    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10548        let snapshot = self.snapshot(window, cx);
10549        let selection = self.selections.newest::<Point>(cx);
10550        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10551    }
10552
10553    fn go_to_hunk_before_position(
10554        &mut self,
10555        snapshot: &EditorSnapshot,
10556        position: Point,
10557        window: &mut Window,
10558        cx: &mut Context<Editor>,
10559    ) -> Option<MultiBufferDiffHunk> {
10560        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10561        if hunk.is_none() {
10562            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10563        }
10564        if let Some(hunk) = &hunk {
10565            let destination = Point::new(hunk.row_range.start.0, 0);
10566            self.unfold_ranges(&[destination..destination], false, false, cx);
10567            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10568                s.select_ranges(vec![destination..destination]);
10569            });
10570        }
10571
10572        hunk
10573    }
10574
10575    pub fn go_to_definition(
10576        &mut self,
10577        _: &GoToDefinition,
10578        window: &mut Window,
10579        cx: &mut Context<Self>,
10580    ) -> Task<Result<Navigated>> {
10581        let definition =
10582            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10583        cx.spawn_in(window, |editor, mut cx| async move {
10584            if definition.await? == Navigated::Yes {
10585                return Ok(Navigated::Yes);
10586            }
10587            match editor.update_in(&mut cx, |editor, window, cx| {
10588                editor.find_all_references(&FindAllReferences, window, cx)
10589            })? {
10590                Some(references) => references.await,
10591                None => Ok(Navigated::No),
10592            }
10593        })
10594    }
10595
10596    pub fn go_to_declaration(
10597        &mut self,
10598        _: &GoToDeclaration,
10599        window: &mut Window,
10600        cx: &mut Context<Self>,
10601    ) -> Task<Result<Navigated>> {
10602        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10603    }
10604
10605    pub fn go_to_declaration_split(
10606        &mut self,
10607        _: &GoToDeclaration,
10608        window: &mut Window,
10609        cx: &mut Context<Self>,
10610    ) -> Task<Result<Navigated>> {
10611        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10612    }
10613
10614    pub fn go_to_implementation(
10615        &mut self,
10616        _: &GoToImplementation,
10617        window: &mut Window,
10618        cx: &mut Context<Self>,
10619    ) -> Task<Result<Navigated>> {
10620        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10621    }
10622
10623    pub fn go_to_implementation_split(
10624        &mut self,
10625        _: &GoToImplementationSplit,
10626        window: &mut Window,
10627        cx: &mut Context<Self>,
10628    ) -> Task<Result<Navigated>> {
10629        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10630    }
10631
10632    pub fn go_to_type_definition(
10633        &mut self,
10634        _: &GoToTypeDefinition,
10635        window: &mut Window,
10636        cx: &mut Context<Self>,
10637    ) -> Task<Result<Navigated>> {
10638        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10639    }
10640
10641    pub fn go_to_definition_split(
10642        &mut self,
10643        _: &GoToDefinitionSplit,
10644        window: &mut Window,
10645        cx: &mut Context<Self>,
10646    ) -> Task<Result<Navigated>> {
10647        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10648    }
10649
10650    pub fn go_to_type_definition_split(
10651        &mut self,
10652        _: &GoToTypeDefinitionSplit,
10653        window: &mut Window,
10654        cx: &mut Context<Self>,
10655    ) -> Task<Result<Navigated>> {
10656        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10657    }
10658
10659    fn go_to_definition_of_kind(
10660        &mut self,
10661        kind: GotoDefinitionKind,
10662        split: bool,
10663        window: &mut Window,
10664        cx: &mut Context<Self>,
10665    ) -> Task<Result<Navigated>> {
10666        let Some(provider) = self.semantics_provider.clone() else {
10667            return Task::ready(Ok(Navigated::No));
10668        };
10669        let head = self.selections.newest::<usize>(cx).head();
10670        let buffer = self.buffer.read(cx);
10671        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10672            text_anchor
10673        } else {
10674            return Task::ready(Ok(Navigated::No));
10675        };
10676
10677        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10678            return Task::ready(Ok(Navigated::No));
10679        };
10680
10681        cx.spawn_in(window, |editor, mut cx| async move {
10682            let definitions = definitions.await?;
10683            let navigated = editor
10684                .update_in(&mut cx, |editor, window, cx| {
10685                    editor.navigate_to_hover_links(
10686                        Some(kind),
10687                        definitions
10688                            .into_iter()
10689                            .filter(|location| {
10690                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10691                            })
10692                            .map(HoverLink::Text)
10693                            .collect::<Vec<_>>(),
10694                        split,
10695                        window,
10696                        cx,
10697                    )
10698                })?
10699                .await?;
10700            anyhow::Ok(navigated)
10701        })
10702    }
10703
10704    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10705        let selection = self.selections.newest_anchor();
10706        let head = selection.head();
10707        let tail = selection.tail();
10708
10709        let Some((buffer, start_position)) =
10710            self.buffer.read(cx).text_anchor_for_position(head, cx)
10711        else {
10712            return;
10713        };
10714
10715        let end_position = if head != tail {
10716            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10717                return;
10718            };
10719            Some(pos)
10720        } else {
10721            None
10722        };
10723
10724        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10725            let url = if let Some(end_pos) = end_position {
10726                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10727            } else {
10728                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10729            };
10730
10731            if let Some(url) = url {
10732                editor.update(&mut cx, |_, cx| {
10733                    cx.open_url(&url);
10734                })
10735            } else {
10736                Ok(())
10737            }
10738        });
10739
10740        url_finder.detach();
10741    }
10742
10743    pub fn open_selected_filename(
10744        &mut self,
10745        _: &OpenSelectedFilename,
10746        window: &mut Window,
10747        cx: &mut Context<Self>,
10748    ) {
10749        let Some(workspace) = self.workspace() else {
10750            return;
10751        };
10752
10753        let position = self.selections.newest_anchor().head();
10754
10755        let Some((buffer, buffer_position)) =
10756            self.buffer.read(cx).text_anchor_for_position(position, cx)
10757        else {
10758            return;
10759        };
10760
10761        let project = self.project.clone();
10762
10763        cx.spawn_in(window, |_, mut cx| async move {
10764            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10765
10766            if let Some((_, path)) = result {
10767                workspace
10768                    .update_in(&mut cx, |workspace, window, cx| {
10769                        workspace.open_resolved_path(path, window, cx)
10770                    })?
10771                    .await?;
10772            }
10773            anyhow::Ok(())
10774        })
10775        .detach();
10776    }
10777
10778    pub(crate) fn navigate_to_hover_links(
10779        &mut self,
10780        kind: Option<GotoDefinitionKind>,
10781        mut definitions: Vec<HoverLink>,
10782        split: bool,
10783        window: &mut Window,
10784        cx: &mut Context<Editor>,
10785    ) -> Task<Result<Navigated>> {
10786        // If there is one definition, just open it directly
10787        if definitions.len() == 1 {
10788            let definition = definitions.pop().unwrap();
10789
10790            enum TargetTaskResult {
10791                Location(Option<Location>),
10792                AlreadyNavigated,
10793            }
10794
10795            let target_task = match definition {
10796                HoverLink::Text(link) => {
10797                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10798                }
10799                HoverLink::InlayHint(lsp_location, server_id) => {
10800                    let computation =
10801                        self.compute_target_location(lsp_location, server_id, window, cx);
10802                    cx.background_executor().spawn(async move {
10803                        let location = computation.await?;
10804                        Ok(TargetTaskResult::Location(location))
10805                    })
10806                }
10807                HoverLink::Url(url) => {
10808                    cx.open_url(&url);
10809                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10810                }
10811                HoverLink::File(path) => {
10812                    if let Some(workspace) = self.workspace() {
10813                        cx.spawn_in(window, |_, mut cx| async move {
10814                            workspace
10815                                .update_in(&mut cx, |workspace, window, cx| {
10816                                    workspace.open_resolved_path(path, window, cx)
10817                                })?
10818                                .await
10819                                .map(|_| TargetTaskResult::AlreadyNavigated)
10820                        })
10821                    } else {
10822                        Task::ready(Ok(TargetTaskResult::Location(None)))
10823                    }
10824                }
10825            };
10826            cx.spawn_in(window, |editor, mut cx| async move {
10827                let target = match target_task.await.context("target resolution task")? {
10828                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10829                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10830                    TargetTaskResult::Location(Some(target)) => target,
10831                };
10832
10833                editor.update_in(&mut cx, |editor, window, cx| {
10834                    let Some(workspace) = editor.workspace() else {
10835                        return Navigated::No;
10836                    };
10837                    let pane = workspace.read(cx).active_pane().clone();
10838
10839                    let range = target.range.to_point(target.buffer.read(cx));
10840                    let range = editor.range_for_match(&range);
10841                    let range = collapse_multiline_range(range);
10842
10843                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10844                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10845                    } else {
10846                        window.defer(cx, move |window, cx| {
10847                            let target_editor: Entity<Self> =
10848                                workspace.update(cx, |workspace, cx| {
10849                                    let pane = if split {
10850                                        workspace.adjacent_pane(window, cx)
10851                                    } else {
10852                                        workspace.active_pane().clone()
10853                                    };
10854
10855                                    workspace.open_project_item(
10856                                        pane,
10857                                        target.buffer.clone(),
10858                                        true,
10859                                        true,
10860                                        window,
10861                                        cx,
10862                                    )
10863                                });
10864                            target_editor.update(cx, |target_editor, cx| {
10865                                // When selecting a definition in a different buffer, disable the nav history
10866                                // to avoid creating a history entry at the previous cursor location.
10867                                pane.update(cx, |pane, _| pane.disable_history());
10868                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10869                                pane.update(cx, |pane, _| pane.enable_history());
10870                            });
10871                        });
10872                    }
10873                    Navigated::Yes
10874                })
10875            })
10876        } else if !definitions.is_empty() {
10877            cx.spawn_in(window, |editor, mut cx| async move {
10878                let (title, location_tasks, workspace) = editor
10879                    .update_in(&mut cx, |editor, window, cx| {
10880                        let tab_kind = match kind {
10881                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10882                            _ => "Definitions",
10883                        };
10884                        let title = definitions
10885                            .iter()
10886                            .find_map(|definition| match definition {
10887                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10888                                    let buffer = origin.buffer.read(cx);
10889                                    format!(
10890                                        "{} for {}",
10891                                        tab_kind,
10892                                        buffer
10893                                            .text_for_range(origin.range.clone())
10894                                            .collect::<String>()
10895                                    )
10896                                }),
10897                                HoverLink::InlayHint(_, _) => None,
10898                                HoverLink::Url(_) => None,
10899                                HoverLink::File(_) => None,
10900                            })
10901                            .unwrap_or(tab_kind.to_string());
10902                        let location_tasks = definitions
10903                            .into_iter()
10904                            .map(|definition| match definition {
10905                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10906                                HoverLink::InlayHint(lsp_location, server_id) => editor
10907                                    .compute_target_location(lsp_location, server_id, window, cx),
10908                                HoverLink::Url(_) => Task::ready(Ok(None)),
10909                                HoverLink::File(_) => Task::ready(Ok(None)),
10910                            })
10911                            .collect::<Vec<_>>();
10912                        (title, location_tasks, editor.workspace().clone())
10913                    })
10914                    .context("location tasks preparation")?;
10915
10916                let locations = future::join_all(location_tasks)
10917                    .await
10918                    .into_iter()
10919                    .filter_map(|location| location.transpose())
10920                    .collect::<Result<_>>()
10921                    .context("location tasks")?;
10922
10923                let Some(workspace) = workspace else {
10924                    return Ok(Navigated::No);
10925                };
10926                let opened = workspace
10927                    .update_in(&mut cx, |workspace, window, cx| {
10928                        Self::open_locations_in_multibuffer(
10929                            workspace,
10930                            locations,
10931                            title,
10932                            split,
10933                            MultibufferSelectionMode::First,
10934                            window,
10935                            cx,
10936                        )
10937                    })
10938                    .ok();
10939
10940                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10941            })
10942        } else {
10943            Task::ready(Ok(Navigated::No))
10944        }
10945    }
10946
10947    fn compute_target_location(
10948        &self,
10949        lsp_location: lsp::Location,
10950        server_id: LanguageServerId,
10951        window: &mut Window,
10952        cx: &mut Context<Self>,
10953    ) -> Task<anyhow::Result<Option<Location>>> {
10954        let Some(project) = self.project.clone() else {
10955            return Task::ready(Ok(None));
10956        };
10957
10958        cx.spawn_in(window, move |editor, mut cx| async move {
10959            let location_task = editor.update(&mut cx, |_, cx| {
10960                project.update(cx, |project, cx| {
10961                    let language_server_name = project
10962                        .language_server_statuses(cx)
10963                        .find(|(id, _)| server_id == *id)
10964                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10965                    language_server_name.map(|language_server_name| {
10966                        project.open_local_buffer_via_lsp(
10967                            lsp_location.uri.clone(),
10968                            server_id,
10969                            language_server_name,
10970                            cx,
10971                        )
10972                    })
10973                })
10974            })?;
10975            let location = match location_task {
10976                Some(task) => Some({
10977                    let target_buffer_handle = task.await.context("open local buffer")?;
10978                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10979                        let target_start = target_buffer
10980                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10981                        let target_end = target_buffer
10982                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10983                        target_buffer.anchor_after(target_start)
10984                            ..target_buffer.anchor_before(target_end)
10985                    })?;
10986                    Location {
10987                        buffer: target_buffer_handle,
10988                        range,
10989                    }
10990                }),
10991                None => None,
10992            };
10993            Ok(location)
10994        })
10995    }
10996
10997    pub fn find_all_references(
10998        &mut self,
10999        _: &FindAllReferences,
11000        window: &mut Window,
11001        cx: &mut Context<Self>,
11002    ) -> Option<Task<Result<Navigated>>> {
11003        let selection = self.selections.newest::<usize>(cx);
11004        let multi_buffer = self.buffer.read(cx);
11005        let head = selection.head();
11006
11007        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11008        let head_anchor = multi_buffer_snapshot.anchor_at(
11009            head,
11010            if head < selection.tail() {
11011                Bias::Right
11012            } else {
11013                Bias::Left
11014            },
11015        );
11016
11017        match self
11018            .find_all_references_task_sources
11019            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11020        {
11021            Ok(_) => {
11022                log::info!(
11023                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11024                );
11025                return None;
11026            }
11027            Err(i) => {
11028                self.find_all_references_task_sources.insert(i, head_anchor);
11029            }
11030        }
11031
11032        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11033        let workspace = self.workspace()?;
11034        let project = workspace.read(cx).project().clone();
11035        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11036        Some(cx.spawn_in(window, |editor, mut cx| async move {
11037            let _cleanup = defer({
11038                let mut cx = cx.clone();
11039                move || {
11040                    let _ = editor.update(&mut cx, |editor, _| {
11041                        if let Ok(i) =
11042                            editor
11043                                .find_all_references_task_sources
11044                                .binary_search_by(|anchor| {
11045                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11046                                })
11047                        {
11048                            editor.find_all_references_task_sources.remove(i);
11049                        }
11050                    });
11051                }
11052            });
11053
11054            let locations = references.await?;
11055            if locations.is_empty() {
11056                return anyhow::Ok(Navigated::No);
11057            }
11058
11059            workspace.update_in(&mut cx, |workspace, window, cx| {
11060                let title = locations
11061                    .first()
11062                    .as_ref()
11063                    .map(|location| {
11064                        let buffer = location.buffer.read(cx);
11065                        format!(
11066                            "References to `{}`",
11067                            buffer
11068                                .text_for_range(location.range.clone())
11069                                .collect::<String>()
11070                        )
11071                    })
11072                    .unwrap();
11073                Self::open_locations_in_multibuffer(
11074                    workspace,
11075                    locations,
11076                    title,
11077                    false,
11078                    MultibufferSelectionMode::First,
11079                    window,
11080                    cx,
11081                );
11082                Navigated::Yes
11083            })
11084        }))
11085    }
11086
11087    /// Opens a multibuffer with the given project locations in it
11088    pub fn open_locations_in_multibuffer(
11089        workspace: &mut Workspace,
11090        mut locations: Vec<Location>,
11091        title: String,
11092        split: bool,
11093        multibuffer_selection_mode: MultibufferSelectionMode,
11094        window: &mut Window,
11095        cx: &mut Context<Workspace>,
11096    ) {
11097        // If there are multiple definitions, open them in a multibuffer
11098        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11099        let mut locations = locations.into_iter().peekable();
11100        let mut ranges = Vec::new();
11101        let capability = workspace.project().read(cx).capability();
11102
11103        let excerpt_buffer = cx.new(|cx| {
11104            let mut multibuffer = MultiBuffer::new(capability);
11105            while let Some(location) = locations.next() {
11106                let buffer = location.buffer.read(cx);
11107                let mut ranges_for_buffer = Vec::new();
11108                let range = location.range.to_offset(buffer);
11109                ranges_for_buffer.push(range.clone());
11110
11111                while let Some(next_location) = locations.peek() {
11112                    if next_location.buffer == location.buffer {
11113                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11114                        locations.next();
11115                    } else {
11116                        break;
11117                    }
11118                }
11119
11120                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11121                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11122                    location.buffer.clone(),
11123                    ranges_for_buffer,
11124                    DEFAULT_MULTIBUFFER_CONTEXT,
11125                    cx,
11126                ))
11127            }
11128
11129            multibuffer.with_title(title)
11130        });
11131
11132        let editor = cx.new(|cx| {
11133            Editor::for_multibuffer(
11134                excerpt_buffer,
11135                Some(workspace.project().clone()),
11136                true,
11137                window,
11138                cx,
11139            )
11140        });
11141        editor.update(cx, |editor, cx| {
11142            match multibuffer_selection_mode {
11143                MultibufferSelectionMode::First => {
11144                    if let Some(first_range) = ranges.first() {
11145                        editor.change_selections(None, window, cx, |selections| {
11146                            selections.clear_disjoint();
11147                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11148                        });
11149                    }
11150                    editor.highlight_background::<Self>(
11151                        &ranges,
11152                        |theme| theme.editor_highlighted_line_background,
11153                        cx,
11154                    );
11155                }
11156                MultibufferSelectionMode::All => {
11157                    editor.change_selections(None, window, cx, |selections| {
11158                        selections.clear_disjoint();
11159                        selections.select_anchor_ranges(ranges);
11160                    });
11161                }
11162            }
11163            editor.register_buffers_with_language_servers(cx);
11164        });
11165
11166        let item = Box::new(editor);
11167        let item_id = item.item_id();
11168
11169        if split {
11170            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11171        } else {
11172            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11173                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11174                    pane.close_current_preview_item(window, cx)
11175                } else {
11176                    None
11177                }
11178            });
11179            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11180        }
11181        workspace.active_pane().update(cx, |pane, cx| {
11182            pane.set_preview_item_id(Some(item_id), cx);
11183        });
11184    }
11185
11186    pub fn rename(
11187        &mut self,
11188        _: &Rename,
11189        window: &mut Window,
11190        cx: &mut Context<Self>,
11191    ) -> Option<Task<Result<()>>> {
11192        use language::ToOffset as _;
11193
11194        let provider = self.semantics_provider.clone()?;
11195        let selection = self.selections.newest_anchor().clone();
11196        let (cursor_buffer, cursor_buffer_position) = self
11197            .buffer
11198            .read(cx)
11199            .text_anchor_for_position(selection.head(), cx)?;
11200        let (tail_buffer, cursor_buffer_position_end) = self
11201            .buffer
11202            .read(cx)
11203            .text_anchor_for_position(selection.tail(), cx)?;
11204        if tail_buffer != cursor_buffer {
11205            return None;
11206        }
11207
11208        let snapshot = cursor_buffer.read(cx).snapshot();
11209        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11210        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11211        let prepare_rename = provider
11212            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11213            .unwrap_or_else(|| Task::ready(Ok(None)));
11214        drop(snapshot);
11215
11216        Some(cx.spawn_in(window, |this, mut cx| async move {
11217            let rename_range = if let Some(range) = prepare_rename.await? {
11218                Some(range)
11219            } else {
11220                this.update(&mut cx, |this, cx| {
11221                    let buffer = this.buffer.read(cx).snapshot(cx);
11222                    let mut buffer_highlights = this
11223                        .document_highlights_for_position(selection.head(), &buffer)
11224                        .filter(|highlight| {
11225                            highlight.start.excerpt_id == selection.head().excerpt_id
11226                                && highlight.end.excerpt_id == selection.head().excerpt_id
11227                        });
11228                    buffer_highlights
11229                        .next()
11230                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11231                })?
11232            };
11233            if let Some(rename_range) = rename_range {
11234                this.update_in(&mut cx, |this, window, cx| {
11235                    let snapshot = cursor_buffer.read(cx).snapshot();
11236                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11237                    let cursor_offset_in_rename_range =
11238                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11239                    let cursor_offset_in_rename_range_end =
11240                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11241
11242                    this.take_rename(false, window, cx);
11243                    let buffer = this.buffer.read(cx).read(cx);
11244                    let cursor_offset = selection.head().to_offset(&buffer);
11245                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11246                    let rename_end = rename_start + rename_buffer_range.len();
11247                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11248                    let mut old_highlight_id = None;
11249                    let old_name: Arc<str> = buffer
11250                        .chunks(rename_start..rename_end, true)
11251                        .map(|chunk| {
11252                            if old_highlight_id.is_none() {
11253                                old_highlight_id = chunk.syntax_highlight_id;
11254                            }
11255                            chunk.text
11256                        })
11257                        .collect::<String>()
11258                        .into();
11259
11260                    drop(buffer);
11261
11262                    // Position the selection in the rename editor so that it matches the current selection.
11263                    this.show_local_selections = false;
11264                    let rename_editor = cx.new(|cx| {
11265                        let mut editor = Editor::single_line(window, cx);
11266                        editor.buffer.update(cx, |buffer, cx| {
11267                            buffer.edit([(0..0, old_name.clone())], None, cx)
11268                        });
11269                        let rename_selection_range = match cursor_offset_in_rename_range
11270                            .cmp(&cursor_offset_in_rename_range_end)
11271                        {
11272                            Ordering::Equal => {
11273                                editor.select_all(&SelectAll, window, cx);
11274                                return editor;
11275                            }
11276                            Ordering::Less => {
11277                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11278                            }
11279                            Ordering::Greater => {
11280                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11281                            }
11282                        };
11283                        if rename_selection_range.end > old_name.len() {
11284                            editor.select_all(&SelectAll, window, cx);
11285                        } else {
11286                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11287                                s.select_ranges([rename_selection_range]);
11288                            });
11289                        }
11290                        editor
11291                    });
11292                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11293                        if e == &EditorEvent::Focused {
11294                            cx.emit(EditorEvent::FocusedIn)
11295                        }
11296                    })
11297                    .detach();
11298
11299                    let write_highlights =
11300                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11301                    let read_highlights =
11302                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11303                    let ranges = write_highlights
11304                        .iter()
11305                        .flat_map(|(_, ranges)| ranges.iter())
11306                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11307                        .cloned()
11308                        .collect();
11309
11310                    this.highlight_text::<Rename>(
11311                        ranges,
11312                        HighlightStyle {
11313                            fade_out: Some(0.6),
11314                            ..Default::default()
11315                        },
11316                        cx,
11317                    );
11318                    let rename_focus_handle = rename_editor.focus_handle(cx);
11319                    window.focus(&rename_focus_handle);
11320                    let block_id = this.insert_blocks(
11321                        [BlockProperties {
11322                            style: BlockStyle::Flex,
11323                            placement: BlockPlacement::Below(range.start),
11324                            height: 1,
11325                            render: Arc::new({
11326                                let rename_editor = rename_editor.clone();
11327                                move |cx: &mut BlockContext| {
11328                                    let mut text_style = cx.editor_style.text.clone();
11329                                    if let Some(highlight_style) = old_highlight_id
11330                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11331                                    {
11332                                        text_style = text_style.highlight(highlight_style);
11333                                    }
11334                                    div()
11335                                        .block_mouse_down()
11336                                        .pl(cx.anchor_x)
11337                                        .child(EditorElement::new(
11338                                            &rename_editor,
11339                                            EditorStyle {
11340                                                background: cx.theme().system().transparent,
11341                                                local_player: cx.editor_style.local_player,
11342                                                text: text_style,
11343                                                scrollbar_width: cx.editor_style.scrollbar_width,
11344                                                syntax: cx.editor_style.syntax.clone(),
11345                                                status: cx.editor_style.status.clone(),
11346                                                inlay_hints_style: HighlightStyle {
11347                                                    font_weight: Some(FontWeight::BOLD),
11348                                                    ..make_inlay_hints_style(cx.app)
11349                                                },
11350                                                inline_completion_styles: make_suggestion_styles(
11351                                                    cx.app,
11352                                                ),
11353                                                ..EditorStyle::default()
11354                                            },
11355                                        ))
11356                                        .into_any_element()
11357                                }
11358                            }),
11359                            priority: 0,
11360                        }],
11361                        Some(Autoscroll::fit()),
11362                        cx,
11363                    )[0];
11364                    this.pending_rename = Some(RenameState {
11365                        range,
11366                        old_name,
11367                        editor: rename_editor,
11368                        block_id,
11369                    });
11370                })?;
11371            }
11372
11373            Ok(())
11374        }))
11375    }
11376
11377    pub fn confirm_rename(
11378        &mut self,
11379        _: &ConfirmRename,
11380        window: &mut Window,
11381        cx: &mut Context<Self>,
11382    ) -> Option<Task<Result<()>>> {
11383        let rename = self.take_rename(false, window, cx)?;
11384        let workspace = self.workspace()?.downgrade();
11385        let (buffer, start) = self
11386            .buffer
11387            .read(cx)
11388            .text_anchor_for_position(rename.range.start, cx)?;
11389        let (end_buffer, _) = self
11390            .buffer
11391            .read(cx)
11392            .text_anchor_for_position(rename.range.end, cx)?;
11393        if buffer != end_buffer {
11394            return None;
11395        }
11396
11397        let old_name = rename.old_name;
11398        let new_name = rename.editor.read(cx).text(cx);
11399
11400        let rename = self.semantics_provider.as_ref()?.perform_rename(
11401            &buffer,
11402            start,
11403            new_name.clone(),
11404            cx,
11405        )?;
11406
11407        Some(cx.spawn_in(window, |editor, mut cx| async move {
11408            let project_transaction = rename.await?;
11409            Self::open_project_transaction(
11410                &editor,
11411                workspace,
11412                project_transaction,
11413                format!("Rename: {}{}", old_name, new_name),
11414                cx.clone(),
11415            )
11416            .await?;
11417
11418            editor.update(&mut cx, |editor, cx| {
11419                editor.refresh_document_highlights(cx);
11420            })?;
11421            Ok(())
11422        }))
11423    }
11424
11425    fn take_rename(
11426        &mut self,
11427        moving_cursor: bool,
11428        window: &mut Window,
11429        cx: &mut Context<Self>,
11430    ) -> Option<RenameState> {
11431        let rename = self.pending_rename.take()?;
11432        if rename.editor.focus_handle(cx).is_focused(window) {
11433            window.focus(&self.focus_handle);
11434        }
11435
11436        self.remove_blocks(
11437            [rename.block_id].into_iter().collect(),
11438            Some(Autoscroll::fit()),
11439            cx,
11440        );
11441        self.clear_highlights::<Rename>(cx);
11442        self.show_local_selections = true;
11443
11444        if moving_cursor {
11445            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11446                editor.selections.newest::<usize>(cx).head()
11447            });
11448
11449            // Update the selection to match the position of the selection inside
11450            // the rename editor.
11451            let snapshot = self.buffer.read(cx).read(cx);
11452            let rename_range = rename.range.to_offset(&snapshot);
11453            let cursor_in_editor = snapshot
11454                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11455                .min(rename_range.end);
11456            drop(snapshot);
11457
11458            self.change_selections(None, window, cx, |s| {
11459                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11460            });
11461        } else {
11462            self.refresh_document_highlights(cx);
11463        }
11464
11465        Some(rename)
11466    }
11467
11468    pub fn pending_rename(&self) -> Option<&RenameState> {
11469        self.pending_rename.as_ref()
11470    }
11471
11472    fn format(
11473        &mut self,
11474        _: &Format,
11475        window: &mut Window,
11476        cx: &mut Context<Self>,
11477    ) -> Option<Task<Result<()>>> {
11478        let project = match &self.project {
11479            Some(project) => project.clone(),
11480            None => return None,
11481        };
11482
11483        Some(self.perform_format(
11484            project,
11485            FormatTrigger::Manual,
11486            FormatTarget::Buffers,
11487            window,
11488            cx,
11489        ))
11490    }
11491
11492    fn format_selections(
11493        &mut self,
11494        _: &FormatSelections,
11495        window: &mut Window,
11496        cx: &mut Context<Self>,
11497    ) -> Option<Task<Result<()>>> {
11498        let project = match &self.project {
11499            Some(project) => project.clone(),
11500            None => return None,
11501        };
11502
11503        let ranges = self
11504            .selections
11505            .all_adjusted(cx)
11506            .into_iter()
11507            .map(|selection| selection.range())
11508            .collect_vec();
11509
11510        Some(self.perform_format(
11511            project,
11512            FormatTrigger::Manual,
11513            FormatTarget::Ranges(ranges),
11514            window,
11515            cx,
11516        ))
11517    }
11518
11519    fn perform_format(
11520        &mut self,
11521        project: Entity<Project>,
11522        trigger: FormatTrigger,
11523        target: FormatTarget,
11524        window: &mut Window,
11525        cx: &mut Context<Self>,
11526    ) -> Task<Result<()>> {
11527        let buffer = self.buffer.clone();
11528        let (buffers, target) = match target {
11529            FormatTarget::Buffers => {
11530                let mut buffers = buffer.read(cx).all_buffers();
11531                if trigger == FormatTrigger::Save {
11532                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11533                }
11534                (buffers, LspFormatTarget::Buffers)
11535            }
11536            FormatTarget::Ranges(selection_ranges) => {
11537                let multi_buffer = buffer.read(cx);
11538                let snapshot = multi_buffer.read(cx);
11539                let mut buffers = HashSet::default();
11540                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11541                    BTreeMap::new();
11542                for selection_range in selection_ranges {
11543                    for (buffer, buffer_range, _) in
11544                        snapshot.range_to_buffer_ranges(selection_range)
11545                    {
11546                        let buffer_id = buffer.remote_id();
11547                        let start = buffer.anchor_before(buffer_range.start);
11548                        let end = buffer.anchor_after(buffer_range.end);
11549                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11550                        buffer_id_to_ranges
11551                            .entry(buffer_id)
11552                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11553                            .or_insert_with(|| vec![start..end]);
11554                    }
11555                }
11556                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11557            }
11558        };
11559
11560        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11561        let format = project.update(cx, |project, cx| {
11562            project.format(buffers, target, true, trigger, cx)
11563        });
11564
11565        cx.spawn_in(window, |_, mut cx| async move {
11566            let transaction = futures::select_biased! {
11567                () = timeout => {
11568                    log::warn!("timed out waiting for formatting");
11569                    None
11570                }
11571                transaction = format.log_err().fuse() => transaction,
11572            };
11573
11574            buffer
11575                .update(&mut cx, |buffer, cx| {
11576                    if let Some(transaction) = transaction {
11577                        if !buffer.is_singleton() {
11578                            buffer.push_transaction(&transaction.0, cx);
11579                        }
11580                    }
11581
11582                    cx.notify();
11583                })
11584                .ok();
11585
11586            Ok(())
11587        })
11588    }
11589
11590    fn restart_language_server(
11591        &mut self,
11592        _: &RestartLanguageServer,
11593        _: &mut Window,
11594        cx: &mut Context<Self>,
11595    ) {
11596        if let Some(project) = self.project.clone() {
11597            self.buffer.update(cx, |multi_buffer, cx| {
11598                project.update(cx, |project, cx| {
11599                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11600                });
11601            })
11602        }
11603    }
11604
11605    fn cancel_language_server_work(
11606        workspace: &mut Workspace,
11607        _: &actions::CancelLanguageServerWork,
11608        _: &mut Window,
11609        cx: &mut Context<Workspace>,
11610    ) {
11611        let project = workspace.project();
11612        let buffers = workspace
11613            .active_item(cx)
11614            .and_then(|item| item.act_as::<Editor>(cx))
11615            .map_or(HashSet::default(), |editor| {
11616                editor.read(cx).buffer.read(cx).all_buffers()
11617            });
11618        project.update(cx, |project, cx| {
11619            project.cancel_language_server_work_for_buffers(buffers, cx);
11620        });
11621    }
11622
11623    fn show_character_palette(
11624        &mut self,
11625        _: &ShowCharacterPalette,
11626        window: &mut Window,
11627        _: &mut Context<Self>,
11628    ) {
11629        window.show_character_palette();
11630    }
11631
11632    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11633        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11634            let buffer = self.buffer.read(cx).snapshot(cx);
11635            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11636            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11637            let is_valid = buffer
11638                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11639                .any(|entry| {
11640                    entry.diagnostic.is_primary
11641                        && !entry.range.is_empty()
11642                        && entry.range.start == primary_range_start
11643                        && entry.diagnostic.message == active_diagnostics.primary_message
11644                });
11645
11646            if is_valid != active_diagnostics.is_valid {
11647                active_diagnostics.is_valid = is_valid;
11648                let mut new_styles = HashMap::default();
11649                for (block_id, diagnostic) in &active_diagnostics.blocks {
11650                    new_styles.insert(
11651                        *block_id,
11652                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11653                    );
11654                }
11655                self.display_map.update(cx, |display_map, _cx| {
11656                    display_map.replace_blocks(new_styles)
11657                });
11658            }
11659        }
11660    }
11661
11662    fn activate_diagnostics(
11663        &mut self,
11664        buffer_id: BufferId,
11665        group_id: usize,
11666        window: &mut Window,
11667        cx: &mut Context<Self>,
11668    ) {
11669        self.dismiss_diagnostics(cx);
11670        let snapshot = self.snapshot(window, cx);
11671        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11672            let buffer = self.buffer.read(cx).snapshot(cx);
11673
11674            let mut primary_range = None;
11675            let mut primary_message = None;
11676            let diagnostic_group = buffer
11677                .diagnostic_group(buffer_id, group_id)
11678                .filter_map(|entry| {
11679                    let start = entry.range.start;
11680                    let end = entry.range.end;
11681                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11682                        && (start.row == end.row
11683                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11684                    {
11685                        return None;
11686                    }
11687                    if entry.diagnostic.is_primary {
11688                        primary_range = Some(entry.range.clone());
11689                        primary_message = Some(entry.diagnostic.message.clone());
11690                    }
11691                    Some(entry)
11692                })
11693                .collect::<Vec<_>>();
11694            let primary_range = primary_range?;
11695            let primary_message = primary_message?;
11696
11697            let blocks = display_map
11698                .insert_blocks(
11699                    diagnostic_group.iter().map(|entry| {
11700                        let diagnostic = entry.diagnostic.clone();
11701                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11702                        BlockProperties {
11703                            style: BlockStyle::Fixed,
11704                            placement: BlockPlacement::Below(
11705                                buffer.anchor_after(entry.range.start),
11706                            ),
11707                            height: message_height,
11708                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11709                            priority: 0,
11710                        }
11711                    }),
11712                    cx,
11713                )
11714                .into_iter()
11715                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11716                .collect();
11717
11718            Some(ActiveDiagnosticGroup {
11719                primary_range: buffer.anchor_before(primary_range.start)
11720                    ..buffer.anchor_after(primary_range.end),
11721                primary_message,
11722                group_id,
11723                blocks,
11724                is_valid: true,
11725            })
11726        });
11727    }
11728
11729    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11730        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11731            self.display_map.update(cx, |display_map, cx| {
11732                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11733            });
11734            cx.notify();
11735        }
11736    }
11737
11738    pub fn set_selections_from_remote(
11739        &mut self,
11740        selections: Vec<Selection<Anchor>>,
11741        pending_selection: Option<Selection<Anchor>>,
11742        window: &mut Window,
11743        cx: &mut Context<Self>,
11744    ) {
11745        let old_cursor_position = self.selections.newest_anchor().head();
11746        self.selections.change_with(cx, |s| {
11747            s.select_anchors(selections);
11748            if let Some(pending_selection) = pending_selection {
11749                s.set_pending(pending_selection, SelectMode::Character);
11750            } else {
11751                s.clear_pending();
11752            }
11753        });
11754        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11755    }
11756
11757    fn push_to_selection_history(&mut self) {
11758        self.selection_history.push(SelectionHistoryEntry {
11759            selections: self.selections.disjoint_anchors(),
11760            select_next_state: self.select_next_state.clone(),
11761            select_prev_state: self.select_prev_state.clone(),
11762            add_selections_state: self.add_selections_state.clone(),
11763        });
11764    }
11765
11766    pub fn transact(
11767        &mut self,
11768        window: &mut Window,
11769        cx: &mut Context<Self>,
11770        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11771    ) -> Option<TransactionId> {
11772        self.start_transaction_at(Instant::now(), window, cx);
11773        update(self, window, cx);
11774        self.end_transaction_at(Instant::now(), cx)
11775    }
11776
11777    pub fn start_transaction_at(
11778        &mut self,
11779        now: Instant,
11780        window: &mut Window,
11781        cx: &mut Context<Self>,
11782    ) {
11783        self.end_selection(window, cx);
11784        if let Some(tx_id) = self
11785            .buffer
11786            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11787        {
11788            self.selection_history
11789                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11790            cx.emit(EditorEvent::TransactionBegun {
11791                transaction_id: tx_id,
11792            })
11793        }
11794    }
11795
11796    pub fn end_transaction_at(
11797        &mut self,
11798        now: Instant,
11799        cx: &mut Context<Self>,
11800    ) -> Option<TransactionId> {
11801        if let Some(transaction_id) = self
11802            .buffer
11803            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11804        {
11805            if let Some((_, end_selections)) =
11806                self.selection_history.transaction_mut(transaction_id)
11807            {
11808                *end_selections = Some(self.selections.disjoint_anchors());
11809            } else {
11810                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11811            }
11812
11813            cx.emit(EditorEvent::Edited { transaction_id });
11814            Some(transaction_id)
11815        } else {
11816            None
11817        }
11818    }
11819
11820    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11821        if self.selection_mark_mode {
11822            self.change_selections(None, window, cx, |s| {
11823                s.move_with(|_, sel| {
11824                    sel.collapse_to(sel.head(), SelectionGoal::None);
11825                });
11826            })
11827        }
11828        self.selection_mark_mode = true;
11829        cx.notify();
11830    }
11831
11832    pub fn swap_selection_ends(
11833        &mut self,
11834        _: &actions::SwapSelectionEnds,
11835        window: &mut Window,
11836        cx: &mut Context<Self>,
11837    ) {
11838        self.change_selections(None, window, cx, |s| {
11839            s.move_with(|_, sel| {
11840                if sel.start != sel.end {
11841                    sel.reversed = !sel.reversed
11842                }
11843            });
11844        });
11845        self.request_autoscroll(Autoscroll::newest(), cx);
11846        cx.notify();
11847    }
11848
11849    pub fn toggle_fold(
11850        &mut self,
11851        _: &actions::ToggleFold,
11852        window: &mut Window,
11853        cx: &mut Context<Self>,
11854    ) {
11855        if self.is_singleton(cx) {
11856            let selection = self.selections.newest::<Point>(cx);
11857
11858            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11859            let range = if selection.is_empty() {
11860                let point = selection.head().to_display_point(&display_map);
11861                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11862                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11863                    .to_point(&display_map);
11864                start..end
11865            } else {
11866                selection.range()
11867            };
11868            if display_map.folds_in_range(range).next().is_some() {
11869                self.unfold_lines(&Default::default(), window, cx)
11870            } else {
11871                self.fold(&Default::default(), window, cx)
11872            }
11873        } else {
11874            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11875            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11876                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11877                .map(|(snapshot, _, _)| snapshot.remote_id())
11878                .collect();
11879
11880            for buffer_id in buffer_ids {
11881                if self.is_buffer_folded(buffer_id, cx) {
11882                    self.unfold_buffer(buffer_id, cx);
11883                } else {
11884                    self.fold_buffer(buffer_id, cx);
11885                }
11886            }
11887        }
11888    }
11889
11890    pub fn toggle_fold_recursive(
11891        &mut self,
11892        _: &actions::ToggleFoldRecursive,
11893        window: &mut Window,
11894        cx: &mut Context<Self>,
11895    ) {
11896        let selection = self.selections.newest::<Point>(cx);
11897
11898        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11899        let range = if selection.is_empty() {
11900            let point = selection.head().to_display_point(&display_map);
11901            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11902            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11903                .to_point(&display_map);
11904            start..end
11905        } else {
11906            selection.range()
11907        };
11908        if display_map.folds_in_range(range).next().is_some() {
11909            self.unfold_recursive(&Default::default(), window, cx)
11910        } else {
11911            self.fold_recursive(&Default::default(), window, cx)
11912        }
11913    }
11914
11915    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11916        if self.is_singleton(cx) {
11917            let mut to_fold = Vec::new();
11918            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11919            let selections = self.selections.all_adjusted(cx);
11920
11921            for selection in selections {
11922                let range = selection.range().sorted();
11923                let buffer_start_row = range.start.row;
11924
11925                if range.start.row != range.end.row {
11926                    let mut found = false;
11927                    let mut row = range.start.row;
11928                    while row <= range.end.row {
11929                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11930                        {
11931                            found = true;
11932                            row = crease.range().end.row + 1;
11933                            to_fold.push(crease);
11934                        } else {
11935                            row += 1
11936                        }
11937                    }
11938                    if found {
11939                        continue;
11940                    }
11941                }
11942
11943                for row in (0..=range.start.row).rev() {
11944                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11945                        if crease.range().end.row >= buffer_start_row {
11946                            to_fold.push(crease);
11947                            if row <= range.start.row {
11948                                break;
11949                            }
11950                        }
11951                    }
11952                }
11953            }
11954
11955            self.fold_creases(to_fold, true, window, cx);
11956        } else {
11957            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11958
11959            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11960                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11961                .map(|(snapshot, _, _)| snapshot.remote_id())
11962                .collect();
11963            for buffer_id in buffer_ids {
11964                self.fold_buffer(buffer_id, cx);
11965            }
11966        }
11967    }
11968
11969    fn fold_at_level(
11970        &mut self,
11971        fold_at: &FoldAtLevel,
11972        window: &mut Window,
11973        cx: &mut Context<Self>,
11974    ) {
11975        if !self.buffer.read(cx).is_singleton() {
11976            return;
11977        }
11978
11979        let fold_at_level = fold_at.0;
11980        let snapshot = self.buffer.read(cx).snapshot(cx);
11981        let mut to_fold = Vec::new();
11982        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11983
11984        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11985            while start_row < end_row {
11986                match self
11987                    .snapshot(window, cx)
11988                    .crease_for_buffer_row(MultiBufferRow(start_row))
11989                {
11990                    Some(crease) => {
11991                        let nested_start_row = crease.range().start.row + 1;
11992                        let nested_end_row = crease.range().end.row;
11993
11994                        if current_level < fold_at_level {
11995                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11996                        } else if current_level == fold_at_level {
11997                            to_fold.push(crease);
11998                        }
11999
12000                        start_row = nested_end_row + 1;
12001                    }
12002                    None => start_row += 1,
12003                }
12004            }
12005        }
12006
12007        self.fold_creases(to_fold, true, window, cx);
12008    }
12009
12010    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12011        if self.buffer.read(cx).is_singleton() {
12012            let mut fold_ranges = Vec::new();
12013            let snapshot = self.buffer.read(cx).snapshot(cx);
12014
12015            for row in 0..snapshot.max_row().0 {
12016                if let Some(foldable_range) = self
12017                    .snapshot(window, cx)
12018                    .crease_for_buffer_row(MultiBufferRow(row))
12019                {
12020                    fold_ranges.push(foldable_range);
12021                }
12022            }
12023
12024            self.fold_creases(fold_ranges, true, window, cx);
12025        } else {
12026            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12027                editor
12028                    .update_in(&mut cx, |editor, _, cx| {
12029                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12030                            editor.fold_buffer(buffer_id, cx);
12031                        }
12032                    })
12033                    .ok();
12034            });
12035        }
12036    }
12037
12038    pub fn fold_function_bodies(
12039        &mut self,
12040        _: &actions::FoldFunctionBodies,
12041        window: &mut Window,
12042        cx: &mut Context<Self>,
12043    ) {
12044        let snapshot = self.buffer.read(cx).snapshot(cx);
12045
12046        let ranges = snapshot
12047            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12048            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12049            .collect::<Vec<_>>();
12050
12051        let creases = ranges
12052            .into_iter()
12053            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12054            .collect();
12055
12056        self.fold_creases(creases, true, window, cx);
12057    }
12058
12059    pub fn fold_recursive(
12060        &mut self,
12061        _: &actions::FoldRecursive,
12062        window: &mut Window,
12063        cx: &mut Context<Self>,
12064    ) {
12065        let mut to_fold = Vec::new();
12066        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12067        let selections = self.selections.all_adjusted(cx);
12068
12069        for selection in selections {
12070            let range = selection.range().sorted();
12071            let buffer_start_row = range.start.row;
12072
12073            if range.start.row != range.end.row {
12074                let mut found = false;
12075                for row in range.start.row..=range.end.row {
12076                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12077                        found = true;
12078                        to_fold.push(crease);
12079                    }
12080                }
12081                if found {
12082                    continue;
12083                }
12084            }
12085
12086            for row in (0..=range.start.row).rev() {
12087                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12088                    if crease.range().end.row >= buffer_start_row {
12089                        to_fold.push(crease);
12090                    } else {
12091                        break;
12092                    }
12093                }
12094            }
12095        }
12096
12097        self.fold_creases(to_fold, true, window, cx);
12098    }
12099
12100    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12101        let buffer_row = fold_at.buffer_row;
12102        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12103
12104        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12105            let autoscroll = self
12106                .selections
12107                .all::<Point>(cx)
12108                .iter()
12109                .any(|selection| crease.range().overlaps(&selection.range()));
12110
12111            self.fold_creases(vec![crease], autoscroll, window, cx);
12112        }
12113    }
12114
12115    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12116        if self.is_singleton(cx) {
12117            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12118            let buffer = &display_map.buffer_snapshot;
12119            let selections = self.selections.all::<Point>(cx);
12120            let ranges = selections
12121                .iter()
12122                .map(|s| {
12123                    let range = s.display_range(&display_map).sorted();
12124                    let mut start = range.start.to_point(&display_map);
12125                    let mut end = range.end.to_point(&display_map);
12126                    start.column = 0;
12127                    end.column = buffer.line_len(MultiBufferRow(end.row));
12128                    start..end
12129                })
12130                .collect::<Vec<_>>();
12131
12132            self.unfold_ranges(&ranges, true, true, cx);
12133        } else {
12134            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12135            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12136                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12137                .map(|(snapshot, _, _)| snapshot.remote_id())
12138                .collect();
12139            for buffer_id in buffer_ids {
12140                self.unfold_buffer(buffer_id, cx);
12141            }
12142        }
12143    }
12144
12145    pub fn unfold_recursive(
12146        &mut self,
12147        _: &UnfoldRecursive,
12148        _window: &mut Window,
12149        cx: &mut Context<Self>,
12150    ) {
12151        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12152        let selections = self.selections.all::<Point>(cx);
12153        let ranges = selections
12154            .iter()
12155            .map(|s| {
12156                let mut range = s.display_range(&display_map).sorted();
12157                *range.start.column_mut() = 0;
12158                *range.end.column_mut() = display_map.line_len(range.end.row());
12159                let start = range.start.to_point(&display_map);
12160                let end = range.end.to_point(&display_map);
12161                start..end
12162            })
12163            .collect::<Vec<_>>();
12164
12165        self.unfold_ranges(&ranges, true, true, cx);
12166    }
12167
12168    pub fn unfold_at(
12169        &mut self,
12170        unfold_at: &UnfoldAt,
12171        _window: &mut Window,
12172        cx: &mut Context<Self>,
12173    ) {
12174        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12175
12176        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12177            ..Point::new(
12178                unfold_at.buffer_row.0,
12179                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12180            );
12181
12182        let autoscroll = self
12183            .selections
12184            .all::<Point>(cx)
12185            .iter()
12186            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12187
12188        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12189    }
12190
12191    pub fn unfold_all(
12192        &mut self,
12193        _: &actions::UnfoldAll,
12194        _window: &mut Window,
12195        cx: &mut Context<Self>,
12196    ) {
12197        if self.buffer.read(cx).is_singleton() {
12198            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12199            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12200        } else {
12201            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12202                editor
12203                    .update(&mut cx, |editor, cx| {
12204                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12205                            editor.unfold_buffer(buffer_id, cx);
12206                        }
12207                    })
12208                    .ok();
12209            });
12210        }
12211    }
12212
12213    pub fn fold_selected_ranges(
12214        &mut self,
12215        _: &FoldSelectedRanges,
12216        window: &mut Window,
12217        cx: &mut Context<Self>,
12218    ) {
12219        let selections = self.selections.all::<Point>(cx);
12220        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12221        let line_mode = self.selections.line_mode;
12222        let ranges = selections
12223            .into_iter()
12224            .map(|s| {
12225                if line_mode {
12226                    let start = Point::new(s.start.row, 0);
12227                    let end = Point::new(
12228                        s.end.row,
12229                        display_map
12230                            .buffer_snapshot
12231                            .line_len(MultiBufferRow(s.end.row)),
12232                    );
12233                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12234                } else {
12235                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12236                }
12237            })
12238            .collect::<Vec<_>>();
12239        self.fold_creases(ranges, true, window, cx);
12240    }
12241
12242    pub fn fold_ranges<T: ToOffset + Clone>(
12243        &mut self,
12244        ranges: Vec<Range<T>>,
12245        auto_scroll: bool,
12246        window: &mut Window,
12247        cx: &mut Context<Self>,
12248    ) {
12249        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12250        let ranges = ranges
12251            .into_iter()
12252            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12253            .collect::<Vec<_>>();
12254        self.fold_creases(ranges, auto_scroll, window, cx);
12255    }
12256
12257    pub fn fold_creases<T: ToOffset + Clone>(
12258        &mut self,
12259        creases: Vec<Crease<T>>,
12260        auto_scroll: bool,
12261        window: &mut Window,
12262        cx: &mut Context<Self>,
12263    ) {
12264        if creases.is_empty() {
12265            return;
12266        }
12267
12268        let mut buffers_affected = HashSet::default();
12269        let multi_buffer = self.buffer().read(cx);
12270        for crease in &creases {
12271            if let Some((_, buffer, _)) =
12272                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12273            {
12274                buffers_affected.insert(buffer.read(cx).remote_id());
12275            };
12276        }
12277
12278        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12279
12280        if auto_scroll {
12281            self.request_autoscroll(Autoscroll::fit(), cx);
12282        }
12283
12284        cx.notify();
12285
12286        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12287            // Clear diagnostics block when folding a range that contains it.
12288            let snapshot = self.snapshot(window, cx);
12289            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12290                drop(snapshot);
12291                self.active_diagnostics = Some(active_diagnostics);
12292                self.dismiss_diagnostics(cx);
12293            } else {
12294                self.active_diagnostics = Some(active_diagnostics);
12295            }
12296        }
12297
12298        self.scrollbar_marker_state.dirty = true;
12299    }
12300
12301    /// Removes any folds whose ranges intersect any of the given ranges.
12302    pub fn unfold_ranges<T: ToOffset + Clone>(
12303        &mut self,
12304        ranges: &[Range<T>],
12305        inclusive: bool,
12306        auto_scroll: bool,
12307        cx: &mut Context<Self>,
12308    ) {
12309        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12310            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12311        });
12312    }
12313
12314    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12315        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12316            return;
12317        }
12318        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12319        self.display_map
12320            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12321        cx.emit(EditorEvent::BufferFoldToggled {
12322            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12323            folded: true,
12324        });
12325        cx.notify();
12326    }
12327
12328    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12329        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12330            return;
12331        }
12332        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12333        self.display_map.update(cx, |display_map, cx| {
12334            display_map.unfold_buffer(buffer_id, cx);
12335        });
12336        cx.emit(EditorEvent::BufferFoldToggled {
12337            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12338            folded: false,
12339        });
12340        cx.notify();
12341    }
12342
12343    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12344        self.display_map.read(cx).is_buffer_folded(buffer)
12345    }
12346
12347    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12348        self.display_map.read(cx).folded_buffers()
12349    }
12350
12351    /// Removes any folds with the given ranges.
12352    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12353        &mut self,
12354        ranges: &[Range<T>],
12355        type_id: TypeId,
12356        auto_scroll: bool,
12357        cx: &mut Context<Self>,
12358    ) {
12359        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12360            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12361        });
12362    }
12363
12364    fn remove_folds_with<T: ToOffset + Clone>(
12365        &mut self,
12366        ranges: &[Range<T>],
12367        auto_scroll: bool,
12368        cx: &mut Context<Self>,
12369        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12370    ) {
12371        if ranges.is_empty() {
12372            return;
12373        }
12374
12375        let mut buffers_affected = HashSet::default();
12376        let multi_buffer = self.buffer().read(cx);
12377        for range in ranges {
12378            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12379                buffers_affected.insert(buffer.read(cx).remote_id());
12380            };
12381        }
12382
12383        self.display_map.update(cx, update);
12384
12385        if auto_scroll {
12386            self.request_autoscroll(Autoscroll::fit(), cx);
12387        }
12388
12389        cx.notify();
12390        self.scrollbar_marker_state.dirty = true;
12391        self.active_indent_guides_state.dirty = true;
12392    }
12393
12394    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12395        self.display_map.read(cx).fold_placeholder.clone()
12396    }
12397
12398    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12399        self.buffer.update(cx, |buffer, cx| {
12400            buffer.set_all_diff_hunks_expanded(cx);
12401        });
12402    }
12403
12404    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12405        self.distinguish_unstaged_diff_hunks = true;
12406    }
12407
12408    pub fn expand_all_diff_hunks(
12409        &mut self,
12410        _: &ExpandAllHunkDiffs,
12411        _window: &mut Window,
12412        cx: &mut Context<Self>,
12413    ) {
12414        self.buffer.update(cx, |buffer, cx| {
12415            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12416        });
12417    }
12418
12419    pub fn toggle_selected_diff_hunks(
12420        &mut self,
12421        _: &ToggleSelectedDiffHunks,
12422        _window: &mut Window,
12423        cx: &mut Context<Self>,
12424    ) {
12425        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12426        self.toggle_diff_hunks_in_ranges(ranges, cx);
12427    }
12428
12429    fn diff_hunks_in_ranges<'a>(
12430        &'a self,
12431        ranges: &'a [Range<Anchor>],
12432        buffer: &'a MultiBufferSnapshot,
12433    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12434        ranges.iter().flat_map(move |range| {
12435            let end_excerpt_id = range.end.excerpt_id;
12436            let range = range.to_point(buffer);
12437            let mut peek_end = range.end;
12438            if range.end.row < buffer.max_row().0 {
12439                peek_end = Point::new(range.end.row + 1, 0);
12440            }
12441            buffer
12442                .diff_hunks_in_range(range.start..peek_end)
12443                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12444        })
12445    }
12446
12447    pub fn has_stageable_diff_hunks_in_ranges(
12448        &self,
12449        ranges: &[Range<Anchor>],
12450        snapshot: &MultiBufferSnapshot,
12451    ) -> bool {
12452        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12453        hunks.any(|hunk| {
12454            log::debug!("considering {hunk:?}");
12455            hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12456        })
12457    }
12458
12459    pub fn toggle_staged_selected_diff_hunks(
12460        &mut self,
12461        _: &ToggleStagedSelectedDiffHunks,
12462        _window: &mut Window,
12463        cx: &mut Context<Self>,
12464    ) {
12465        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12466        self.stage_or_unstage_diff_hunks(&ranges, cx);
12467    }
12468
12469    pub fn stage_or_unstage_diff_hunks(
12470        &mut self,
12471        ranges: &[Range<Anchor>],
12472        cx: &mut Context<Self>,
12473    ) {
12474        let Some(project) = &self.project else {
12475            return;
12476        };
12477        let snapshot = self.buffer.read(cx).snapshot(cx);
12478        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12479
12480        let chunk_by = self
12481            .diff_hunks_in_ranges(&ranges, &snapshot)
12482            .chunk_by(|hunk| hunk.buffer_id);
12483        for (buffer_id, hunks) in &chunk_by {
12484            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12485                log::debug!("no buffer for id");
12486                continue;
12487            };
12488            let buffer = buffer.read(cx).snapshot();
12489            let Some((repo, path)) = project
12490                .read(cx)
12491                .repository_and_path_for_buffer_id(buffer_id, cx)
12492            else {
12493                log::debug!("no git repo for buffer id");
12494                continue;
12495            };
12496            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12497                log::debug!("no diff for buffer id");
12498                continue;
12499            };
12500            let Some(secondary_diff) = diff.secondary_diff() else {
12501                log::debug!("no secondary diff for buffer id");
12502                continue;
12503            };
12504
12505            let edits = diff.secondary_edits_for_stage_or_unstage(
12506                stage,
12507                hunks.map(|hunk| {
12508                    (
12509                        hunk.diff_base_byte_range.clone(),
12510                        hunk.secondary_diff_base_byte_range.clone(),
12511                        hunk.buffer_range.clone(),
12512                    )
12513                }),
12514                &buffer,
12515            );
12516
12517            let index_base = secondary_diff.base_text().map_or_else(
12518                || Rope::from(""),
12519                |snapshot| snapshot.text.as_rope().clone(),
12520            );
12521            let index_buffer = cx.new(|cx| {
12522                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12523            });
12524            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12525                index_buffer.edit(edits, None, cx);
12526                index_buffer.snapshot().as_rope().to_string()
12527            });
12528            let new_index_text = if new_index_text.is_empty()
12529                && (diff.is_single_insertion
12530                    || buffer
12531                        .file()
12532                        .map_or(false, |file| file.disk_state() == DiskState::New))
12533            {
12534                log::debug!("removing from index");
12535                None
12536            } else {
12537                Some(new_index_text)
12538            };
12539
12540            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12541        }
12542    }
12543
12544    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12545        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12546        self.buffer
12547            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12548    }
12549
12550    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12551        self.buffer.update(cx, |buffer, cx| {
12552            let ranges = vec![Anchor::min()..Anchor::max()];
12553            if !buffer.all_diff_hunks_expanded()
12554                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12555            {
12556                buffer.collapse_diff_hunks(ranges, cx);
12557                true
12558            } else {
12559                false
12560            }
12561        })
12562    }
12563
12564    fn toggle_diff_hunks_in_ranges(
12565        &mut self,
12566        ranges: Vec<Range<Anchor>>,
12567        cx: &mut Context<'_, Editor>,
12568    ) {
12569        self.buffer.update(cx, |buffer, cx| {
12570            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12571            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12572        })
12573    }
12574
12575    fn toggle_diff_hunks_in_ranges_narrow(
12576        &mut self,
12577        ranges: Vec<Range<Anchor>>,
12578        cx: &mut Context<'_, Editor>,
12579    ) {
12580        self.buffer.update(cx, |buffer, cx| {
12581            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12582            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12583        })
12584    }
12585
12586    pub(crate) fn apply_all_diff_hunks(
12587        &mut self,
12588        _: &ApplyAllDiffHunks,
12589        window: &mut Window,
12590        cx: &mut Context<Self>,
12591    ) {
12592        let buffers = self.buffer.read(cx).all_buffers();
12593        for branch_buffer in buffers {
12594            branch_buffer.update(cx, |branch_buffer, cx| {
12595                branch_buffer.merge_into_base(Vec::new(), cx);
12596            });
12597        }
12598
12599        if let Some(project) = self.project.clone() {
12600            self.save(true, project, window, cx).detach_and_log_err(cx);
12601        }
12602    }
12603
12604    pub(crate) fn apply_selected_diff_hunks(
12605        &mut self,
12606        _: &ApplyDiffHunk,
12607        window: &mut Window,
12608        cx: &mut Context<Self>,
12609    ) {
12610        let snapshot = self.snapshot(window, cx);
12611        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12612        let mut ranges_by_buffer = HashMap::default();
12613        self.transact(window, cx, |editor, _window, cx| {
12614            for hunk in hunks {
12615                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12616                    ranges_by_buffer
12617                        .entry(buffer.clone())
12618                        .or_insert_with(Vec::new)
12619                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12620                }
12621            }
12622
12623            for (buffer, ranges) in ranges_by_buffer {
12624                buffer.update(cx, |buffer, cx| {
12625                    buffer.merge_into_base(ranges, cx);
12626                });
12627            }
12628        });
12629
12630        if let Some(project) = self.project.clone() {
12631            self.save(true, project, window, cx).detach_and_log_err(cx);
12632        }
12633    }
12634
12635    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12636        if hovered != self.gutter_hovered {
12637            self.gutter_hovered = hovered;
12638            cx.notify();
12639        }
12640    }
12641
12642    pub fn insert_blocks(
12643        &mut self,
12644        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12645        autoscroll: Option<Autoscroll>,
12646        cx: &mut Context<Self>,
12647    ) -> Vec<CustomBlockId> {
12648        let blocks = self
12649            .display_map
12650            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12651        if let Some(autoscroll) = autoscroll {
12652            self.request_autoscroll(autoscroll, cx);
12653        }
12654        cx.notify();
12655        blocks
12656    }
12657
12658    pub fn resize_blocks(
12659        &mut self,
12660        heights: HashMap<CustomBlockId, u32>,
12661        autoscroll: Option<Autoscroll>,
12662        cx: &mut Context<Self>,
12663    ) {
12664        self.display_map
12665            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12666        if let Some(autoscroll) = autoscroll {
12667            self.request_autoscroll(autoscroll, cx);
12668        }
12669        cx.notify();
12670    }
12671
12672    pub fn replace_blocks(
12673        &mut self,
12674        renderers: HashMap<CustomBlockId, RenderBlock>,
12675        autoscroll: Option<Autoscroll>,
12676        cx: &mut Context<Self>,
12677    ) {
12678        self.display_map
12679            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12680        if let Some(autoscroll) = autoscroll {
12681            self.request_autoscroll(autoscroll, cx);
12682        }
12683        cx.notify();
12684    }
12685
12686    pub fn remove_blocks(
12687        &mut self,
12688        block_ids: HashSet<CustomBlockId>,
12689        autoscroll: Option<Autoscroll>,
12690        cx: &mut Context<Self>,
12691    ) {
12692        self.display_map.update(cx, |display_map, cx| {
12693            display_map.remove_blocks(block_ids, cx)
12694        });
12695        if let Some(autoscroll) = autoscroll {
12696            self.request_autoscroll(autoscroll, cx);
12697        }
12698        cx.notify();
12699    }
12700
12701    pub fn row_for_block(
12702        &self,
12703        block_id: CustomBlockId,
12704        cx: &mut Context<Self>,
12705    ) -> Option<DisplayRow> {
12706        self.display_map
12707            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12708    }
12709
12710    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12711        self.focused_block = Some(focused_block);
12712    }
12713
12714    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12715        self.focused_block.take()
12716    }
12717
12718    pub fn insert_creases(
12719        &mut self,
12720        creases: impl IntoIterator<Item = Crease<Anchor>>,
12721        cx: &mut Context<Self>,
12722    ) -> Vec<CreaseId> {
12723        self.display_map
12724            .update(cx, |map, cx| map.insert_creases(creases, cx))
12725    }
12726
12727    pub fn remove_creases(
12728        &mut self,
12729        ids: impl IntoIterator<Item = CreaseId>,
12730        cx: &mut Context<Self>,
12731    ) {
12732        self.display_map
12733            .update(cx, |map, cx| map.remove_creases(ids, cx));
12734    }
12735
12736    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12737        self.display_map
12738            .update(cx, |map, cx| map.snapshot(cx))
12739            .longest_row()
12740    }
12741
12742    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12743        self.display_map
12744            .update(cx, |map, cx| map.snapshot(cx))
12745            .max_point()
12746    }
12747
12748    pub fn text(&self, cx: &App) -> String {
12749        self.buffer.read(cx).read(cx).text()
12750    }
12751
12752    pub fn is_empty(&self, cx: &App) -> bool {
12753        self.buffer.read(cx).read(cx).is_empty()
12754    }
12755
12756    pub fn text_option(&self, cx: &App) -> Option<String> {
12757        let text = self.text(cx);
12758        let text = text.trim();
12759
12760        if text.is_empty() {
12761            return None;
12762        }
12763
12764        Some(text.to_string())
12765    }
12766
12767    pub fn set_text(
12768        &mut self,
12769        text: impl Into<Arc<str>>,
12770        window: &mut Window,
12771        cx: &mut Context<Self>,
12772    ) {
12773        self.transact(window, cx, |this, _, cx| {
12774            this.buffer
12775                .read(cx)
12776                .as_singleton()
12777                .expect("you can only call set_text on editors for singleton buffers")
12778                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12779        });
12780    }
12781
12782    pub fn display_text(&self, cx: &mut App) -> String {
12783        self.display_map
12784            .update(cx, |map, cx| map.snapshot(cx))
12785            .text()
12786    }
12787
12788    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12789        let mut wrap_guides = smallvec::smallvec![];
12790
12791        if self.show_wrap_guides == Some(false) {
12792            return wrap_guides;
12793        }
12794
12795        let settings = self.buffer.read(cx).settings_at(0, cx);
12796        if settings.show_wrap_guides {
12797            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12798                wrap_guides.push((soft_wrap as usize, true));
12799            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12800                wrap_guides.push((soft_wrap as usize, true));
12801            }
12802            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12803        }
12804
12805        wrap_guides
12806    }
12807
12808    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12809        let settings = self.buffer.read(cx).settings_at(0, cx);
12810        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12811        match mode {
12812            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12813                SoftWrap::None
12814            }
12815            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12816            language_settings::SoftWrap::PreferredLineLength => {
12817                SoftWrap::Column(settings.preferred_line_length)
12818            }
12819            language_settings::SoftWrap::Bounded => {
12820                SoftWrap::Bounded(settings.preferred_line_length)
12821            }
12822        }
12823    }
12824
12825    pub fn set_soft_wrap_mode(
12826        &mut self,
12827        mode: language_settings::SoftWrap,
12828
12829        cx: &mut Context<Self>,
12830    ) {
12831        self.soft_wrap_mode_override = Some(mode);
12832        cx.notify();
12833    }
12834
12835    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12836        self.text_style_refinement = Some(style);
12837    }
12838
12839    /// called by the Element so we know what style we were most recently rendered with.
12840    pub(crate) fn set_style(
12841        &mut self,
12842        style: EditorStyle,
12843        window: &mut Window,
12844        cx: &mut Context<Self>,
12845    ) {
12846        let rem_size = window.rem_size();
12847        self.display_map.update(cx, |map, cx| {
12848            map.set_font(
12849                style.text.font(),
12850                style.text.font_size.to_pixels(rem_size),
12851                cx,
12852            )
12853        });
12854        self.style = Some(style);
12855    }
12856
12857    pub fn style(&self) -> Option<&EditorStyle> {
12858        self.style.as_ref()
12859    }
12860
12861    // Called by the element. This method is not designed to be called outside of the editor
12862    // element's layout code because it does not notify when rewrapping is computed synchronously.
12863    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12864        self.display_map
12865            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12866    }
12867
12868    pub fn set_soft_wrap(&mut self) {
12869        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12870    }
12871
12872    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12873        if self.soft_wrap_mode_override.is_some() {
12874            self.soft_wrap_mode_override.take();
12875        } else {
12876            let soft_wrap = match self.soft_wrap_mode(cx) {
12877                SoftWrap::GitDiff => return,
12878                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12879                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12880                    language_settings::SoftWrap::None
12881                }
12882            };
12883            self.soft_wrap_mode_override = Some(soft_wrap);
12884        }
12885        cx.notify();
12886    }
12887
12888    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12889        let Some(workspace) = self.workspace() else {
12890            return;
12891        };
12892        let fs = workspace.read(cx).app_state().fs.clone();
12893        let current_show = TabBarSettings::get_global(cx).show;
12894        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12895            setting.show = Some(!current_show);
12896        });
12897    }
12898
12899    pub fn toggle_indent_guides(
12900        &mut self,
12901        _: &ToggleIndentGuides,
12902        _: &mut Window,
12903        cx: &mut Context<Self>,
12904    ) {
12905        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12906            self.buffer
12907                .read(cx)
12908                .settings_at(0, cx)
12909                .indent_guides
12910                .enabled
12911        });
12912        self.show_indent_guides = Some(!currently_enabled);
12913        cx.notify();
12914    }
12915
12916    fn should_show_indent_guides(&self) -> Option<bool> {
12917        self.show_indent_guides
12918    }
12919
12920    pub fn toggle_line_numbers(
12921        &mut self,
12922        _: &ToggleLineNumbers,
12923        _: &mut Window,
12924        cx: &mut Context<Self>,
12925    ) {
12926        let mut editor_settings = EditorSettings::get_global(cx).clone();
12927        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12928        EditorSettings::override_global(editor_settings, cx);
12929    }
12930
12931    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12932        self.use_relative_line_numbers
12933            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12934    }
12935
12936    pub fn toggle_relative_line_numbers(
12937        &mut self,
12938        _: &ToggleRelativeLineNumbers,
12939        _: &mut Window,
12940        cx: &mut Context<Self>,
12941    ) {
12942        let is_relative = self.should_use_relative_line_numbers(cx);
12943        self.set_relative_line_number(Some(!is_relative), cx)
12944    }
12945
12946    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12947        self.use_relative_line_numbers = is_relative;
12948        cx.notify();
12949    }
12950
12951    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12952        self.show_gutter = show_gutter;
12953        cx.notify();
12954    }
12955
12956    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12957        self.show_scrollbars = show_scrollbars;
12958        cx.notify();
12959    }
12960
12961    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12962        self.show_line_numbers = Some(show_line_numbers);
12963        cx.notify();
12964    }
12965
12966    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12967        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12968        cx.notify();
12969    }
12970
12971    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12972        self.show_code_actions = Some(show_code_actions);
12973        cx.notify();
12974    }
12975
12976    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12977        self.show_runnables = Some(show_runnables);
12978        cx.notify();
12979    }
12980
12981    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12982        if self.display_map.read(cx).masked != masked {
12983            self.display_map.update(cx, |map, _| map.masked = masked);
12984        }
12985        cx.notify()
12986    }
12987
12988    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12989        self.show_wrap_guides = Some(show_wrap_guides);
12990        cx.notify();
12991    }
12992
12993    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12994        self.show_indent_guides = Some(show_indent_guides);
12995        cx.notify();
12996    }
12997
12998    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12999        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13000            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13001                if let Some(dir) = file.abs_path(cx).parent() {
13002                    return Some(dir.to_owned());
13003                }
13004            }
13005
13006            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13007                return Some(project_path.path.to_path_buf());
13008            }
13009        }
13010
13011        None
13012    }
13013
13014    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13015        self.active_excerpt(cx)?
13016            .1
13017            .read(cx)
13018            .file()
13019            .and_then(|f| f.as_local())
13020    }
13021
13022    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13023        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13024            let buffer = buffer.read(cx);
13025            if let Some(project_path) = buffer.project_path(cx) {
13026                let project = self.project.as_ref()?.read(cx);
13027                project.absolute_path(&project_path, cx)
13028            } else {
13029                buffer
13030                    .file()
13031                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13032            }
13033        })
13034    }
13035
13036    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13037        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13038            let project_path = buffer.read(cx).project_path(cx)?;
13039            let project = self.project.as_ref()?.read(cx);
13040            let entry = project.entry_for_path(&project_path, cx)?;
13041            let path = entry.path.to_path_buf();
13042            Some(path)
13043        })
13044    }
13045
13046    pub fn reveal_in_finder(
13047        &mut self,
13048        _: &RevealInFileManager,
13049        _window: &mut Window,
13050        cx: &mut Context<Self>,
13051    ) {
13052        if let Some(target) = self.target_file(cx) {
13053            cx.reveal_path(&target.abs_path(cx));
13054        }
13055    }
13056
13057    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13058        if let Some(path) = self.target_file_abs_path(cx) {
13059            if let Some(path) = path.to_str() {
13060                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13061            }
13062        }
13063    }
13064
13065    pub fn copy_relative_path(
13066        &mut self,
13067        _: &CopyRelativePath,
13068        _window: &mut Window,
13069        cx: &mut Context<Self>,
13070    ) {
13071        if let Some(path) = self.target_file_path(cx) {
13072            if let Some(path) = path.to_str() {
13073                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13074            }
13075        }
13076    }
13077
13078    pub fn copy_file_name_without_extension(
13079        &mut self,
13080        _: &CopyFileNameWithoutExtension,
13081        _: &mut Window,
13082        cx: &mut Context<Self>,
13083    ) {
13084        if let Some(file) = self.target_file(cx) {
13085            if let Some(file_stem) = file.path().file_stem() {
13086                if let Some(name) = file_stem.to_str() {
13087                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13088                }
13089            }
13090        }
13091    }
13092
13093    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13094        if let Some(file) = self.target_file(cx) {
13095            if let Some(file_name) = file.path().file_name() {
13096                if let Some(name) = file_name.to_str() {
13097                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13098                }
13099            }
13100        }
13101    }
13102
13103    pub fn toggle_git_blame(
13104        &mut self,
13105        _: &ToggleGitBlame,
13106        window: &mut Window,
13107        cx: &mut Context<Self>,
13108    ) {
13109        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13110
13111        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13112            self.start_git_blame(true, window, cx);
13113        }
13114
13115        cx.notify();
13116    }
13117
13118    pub fn toggle_git_blame_inline(
13119        &mut self,
13120        _: &ToggleGitBlameInline,
13121        window: &mut Window,
13122        cx: &mut Context<Self>,
13123    ) {
13124        self.toggle_git_blame_inline_internal(true, window, cx);
13125        cx.notify();
13126    }
13127
13128    pub fn git_blame_inline_enabled(&self) -> bool {
13129        self.git_blame_inline_enabled
13130    }
13131
13132    pub fn toggle_selection_menu(
13133        &mut self,
13134        _: &ToggleSelectionMenu,
13135        _: &mut Window,
13136        cx: &mut Context<Self>,
13137    ) {
13138        self.show_selection_menu = self
13139            .show_selection_menu
13140            .map(|show_selections_menu| !show_selections_menu)
13141            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13142
13143        cx.notify();
13144    }
13145
13146    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13147        self.show_selection_menu
13148            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13149    }
13150
13151    fn start_git_blame(
13152        &mut self,
13153        user_triggered: bool,
13154        window: &mut Window,
13155        cx: &mut Context<Self>,
13156    ) {
13157        if let Some(project) = self.project.as_ref() {
13158            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13159                return;
13160            };
13161
13162            if buffer.read(cx).file().is_none() {
13163                return;
13164            }
13165
13166            let focused = self.focus_handle(cx).contains_focused(window, cx);
13167
13168            let project = project.clone();
13169            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13170            self.blame_subscription =
13171                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13172            self.blame = Some(blame);
13173        }
13174    }
13175
13176    fn toggle_git_blame_inline_internal(
13177        &mut self,
13178        user_triggered: bool,
13179        window: &mut Window,
13180        cx: &mut Context<Self>,
13181    ) {
13182        if self.git_blame_inline_enabled {
13183            self.git_blame_inline_enabled = false;
13184            self.show_git_blame_inline = false;
13185            self.show_git_blame_inline_delay_task.take();
13186        } else {
13187            self.git_blame_inline_enabled = true;
13188            self.start_git_blame_inline(user_triggered, window, cx);
13189        }
13190
13191        cx.notify();
13192    }
13193
13194    fn start_git_blame_inline(
13195        &mut self,
13196        user_triggered: bool,
13197        window: &mut Window,
13198        cx: &mut Context<Self>,
13199    ) {
13200        self.start_git_blame(user_triggered, window, cx);
13201
13202        if ProjectSettings::get_global(cx)
13203            .git
13204            .inline_blame_delay()
13205            .is_some()
13206        {
13207            self.start_inline_blame_timer(window, cx);
13208        } else {
13209            self.show_git_blame_inline = true
13210        }
13211    }
13212
13213    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13214        self.blame.as_ref()
13215    }
13216
13217    pub fn show_git_blame_gutter(&self) -> bool {
13218        self.show_git_blame_gutter
13219    }
13220
13221    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13222        self.show_git_blame_gutter && self.has_blame_entries(cx)
13223    }
13224
13225    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13226        self.show_git_blame_inline
13227            && self.focus_handle.is_focused(window)
13228            && !self.newest_selection_head_on_empty_line(cx)
13229            && self.has_blame_entries(cx)
13230    }
13231
13232    fn has_blame_entries(&self, cx: &App) -> bool {
13233        self.blame()
13234            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13235    }
13236
13237    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13238        let cursor_anchor = self.selections.newest_anchor().head();
13239
13240        let snapshot = self.buffer.read(cx).snapshot(cx);
13241        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13242
13243        snapshot.line_len(buffer_row) == 0
13244    }
13245
13246    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13247        let buffer_and_selection = maybe!({
13248            let selection = self.selections.newest::<Point>(cx);
13249            let selection_range = selection.range();
13250
13251            let multi_buffer = self.buffer().read(cx);
13252            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13253            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13254
13255            let (buffer, range, _) = if selection.reversed {
13256                buffer_ranges.first()
13257            } else {
13258                buffer_ranges.last()
13259            }?;
13260
13261            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13262                ..text::ToPoint::to_point(&range.end, &buffer).row;
13263            Some((
13264                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13265                selection,
13266            ))
13267        });
13268
13269        let Some((buffer, selection)) = buffer_and_selection else {
13270            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13271        };
13272
13273        let Some(project) = self.project.as_ref() else {
13274            return Task::ready(Err(anyhow!("editor does not have project")));
13275        };
13276
13277        project.update(cx, |project, cx| {
13278            project.get_permalink_to_line(&buffer, selection, cx)
13279        })
13280    }
13281
13282    pub fn copy_permalink_to_line(
13283        &mut self,
13284        _: &CopyPermalinkToLine,
13285        window: &mut Window,
13286        cx: &mut Context<Self>,
13287    ) {
13288        let permalink_task = self.get_permalink_to_line(cx);
13289        let workspace = self.workspace();
13290
13291        cx.spawn_in(window, |_, mut cx| async move {
13292            match permalink_task.await {
13293                Ok(permalink) => {
13294                    cx.update(|_, cx| {
13295                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13296                    })
13297                    .ok();
13298                }
13299                Err(err) => {
13300                    let message = format!("Failed to copy permalink: {err}");
13301
13302                    Err::<(), anyhow::Error>(err).log_err();
13303
13304                    if let Some(workspace) = workspace {
13305                        workspace
13306                            .update_in(&mut cx, |workspace, _, cx| {
13307                                struct CopyPermalinkToLine;
13308
13309                                workspace.show_toast(
13310                                    Toast::new(
13311                                        NotificationId::unique::<CopyPermalinkToLine>(),
13312                                        message,
13313                                    ),
13314                                    cx,
13315                                )
13316                            })
13317                            .ok();
13318                    }
13319                }
13320            }
13321        })
13322        .detach();
13323    }
13324
13325    pub fn copy_file_location(
13326        &mut self,
13327        _: &CopyFileLocation,
13328        _: &mut Window,
13329        cx: &mut Context<Self>,
13330    ) {
13331        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13332        if let Some(file) = self.target_file(cx) {
13333            if let Some(path) = file.path().to_str() {
13334                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13335            }
13336        }
13337    }
13338
13339    pub fn open_permalink_to_line(
13340        &mut self,
13341        _: &OpenPermalinkToLine,
13342        window: &mut Window,
13343        cx: &mut Context<Self>,
13344    ) {
13345        let permalink_task = self.get_permalink_to_line(cx);
13346        let workspace = self.workspace();
13347
13348        cx.spawn_in(window, |_, mut cx| async move {
13349            match permalink_task.await {
13350                Ok(permalink) => {
13351                    cx.update(|_, cx| {
13352                        cx.open_url(permalink.as_ref());
13353                    })
13354                    .ok();
13355                }
13356                Err(err) => {
13357                    let message = format!("Failed to open permalink: {err}");
13358
13359                    Err::<(), anyhow::Error>(err).log_err();
13360
13361                    if let Some(workspace) = workspace {
13362                        workspace
13363                            .update(&mut cx, |workspace, cx| {
13364                                struct OpenPermalinkToLine;
13365
13366                                workspace.show_toast(
13367                                    Toast::new(
13368                                        NotificationId::unique::<OpenPermalinkToLine>(),
13369                                        message,
13370                                    ),
13371                                    cx,
13372                                )
13373                            })
13374                            .ok();
13375                    }
13376                }
13377            }
13378        })
13379        .detach();
13380    }
13381
13382    pub fn insert_uuid_v4(
13383        &mut self,
13384        _: &InsertUuidV4,
13385        window: &mut Window,
13386        cx: &mut Context<Self>,
13387    ) {
13388        self.insert_uuid(UuidVersion::V4, window, cx);
13389    }
13390
13391    pub fn insert_uuid_v7(
13392        &mut self,
13393        _: &InsertUuidV7,
13394        window: &mut Window,
13395        cx: &mut Context<Self>,
13396    ) {
13397        self.insert_uuid(UuidVersion::V7, window, cx);
13398    }
13399
13400    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13401        self.transact(window, cx, |this, window, cx| {
13402            let edits = this
13403                .selections
13404                .all::<Point>(cx)
13405                .into_iter()
13406                .map(|selection| {
13407                    let uuid = match version {
13408                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13409                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13410                    };
13411
13412                    (selection.range(), uuid.to_string())
13413                });
13414            this.edit(edits, cx);
13415            this.refresh_inline_completion(true, false, window, cx);
13416        });
13417    }
13418
13419    pub fn open_selections_in_multibuffer(
13420        &mut self,
13421        _: &OpenSelectionsInMultibuffer,
13422        window: &mut Window,
13423        cx: &mut Context<Self>,
13424    ) {
13425        let multibuffer = self.buffer.read(cx);
13426
13427        let Some(buffer) = multibuffer.as_singleton() else {
13428            return;
13429        };
13430
13431        let Some(workspace) = self.workspace() else {
13432            return;
13433        };
13434
13435        let locations = self
13436            .selections
13437            .disjoint_anchors()
13438            .iter()
13439            .map(|range| Location {
13440                buffer: buffer.clone(),
13441                range: range.start.text_anchor..range.end.text_anchor,
13442            })
13443            .collect::<Vec<_>>();
13444
13445        let title = multibuffer.title(cx).to_string();
13446
13447        cx.spawn_in(window, |_, mut cx| async move {
13448            workspace.update_in(&mut cx, |workspace, window, cx| {
13449                Self::open_locations_in_multibuffer(
13450                    workspace,
13451                    locations,
13452                    format!("Selections for '{title}'"),
13453                    false,
13454                    MultibufferSelectionMode::All,
13455                    window,
13456                    cx,
13457                );
13458            })
13459        })
13460        .detach();
13461    }
13462
13463    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13464    /// last highlight added will be used.
13465    ///
13466    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13467    pub fn highlight_rows<T: 'static>(
13468        &mut self,
13469        range: Range<Anchor>,
13470        color: Hsla,
13471        should_autoscroll: bool,
13472        cx: &mut Context<Self>,
13473    ) {
13474        let snapshot = self.buffer().read(cx).snapshot(cx);
13475        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13476        let ix = row_highlights.binary_search_by(|highlight| {
13477            Ordering::Equal
13478                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13479                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13480        });
13481
13482        if let Err(mut ix) = ix {
13483            let index = post_inc(&mut self.highlight_order);
13484
13485            // If this range intersects with the preceding highlight, then merge it with
13486            // the preceding highlight. Otherwise insert a new highlight.
13487            let mut merged = false;
13488            if ix > 0 {
13489                let prev_highlight = &mut row_highlights[ix - 1];
13490                if prev_highlight
13491                    .range
13492                    .end
13493                    .cmp(&range.start, &snapshot)
13494                    .is_ge()
13495                {
13496                    ix -= 1;
13497                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13498                        prev_highlight.range.end = range.end;
13499                    }
13500                    merged = true;
13501                    prev_highlight.index = index;
13502                    prev_highlight.color = color;
13503                    prev_highlight.should_autoscroll = should_autoscroll;
13504                }
13505            }
13506
13507            if !merged {
13508                row_highlights.insert(
13509                    ix,
13510                    RowHighlight {
13511                        range: range.clone(),
13512                        index,
13513                        color,
13514                        should_autoscroll,
13515                    },
13516                );
13517            }
13518
13519            // If any of the following highlights intersect with this one, merge them.
13520            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13521                let highlight = &row_highlights[ix];
13522                if next_highlight
13523                    .range
13524                    .start
13525                    .cmp(&highlight.range.end, &snapshot)
13526                    .is_le()
13527                {
13528                    if next_highlight
13529                        .range
13530                        .end
13531                        .cmp(&highlight.range.end, &snapshot)
13532                        .is_gt()
13533                    {
13534                        row_highlights[ix].range.end = next_highlight.range.end;
13535                    }
13536                    row_highlights.remove(ix + 1);
13537                } else {
13538                    break;
13539                }
13540            }
13541        }
13542    }
13543
13544    /// Remove any highlighted row ranges of the given type that intersect the
13545    /// given ranges.
13546    pub fn remove_highlighted_rows<T: 'static>(
13547        &mut self,
13548        ranges_to_remove: Vec<Range<Anchor>>,
13549        cx: &mut Context<Self>,
13550    ) {
13551        let snapshot = self.buffer().read(cx).snapshot(cx);
13552        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13553        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13554        row_highlights.retain(|highlight| {
13555            while let Some(range_to_remove) = ranges_to_remove.peek() {
13556                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13557                    Ordering::Less | Ordering::Equal => {
13558                        ranges_to_remove.next();
13559                    }
13560                    Ordering::Greater => {
13561                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13562                            Ordering::Less | Ordering::Equal => {
13563                                return false;
13564                            }
13565                            Ordering::Greater => break,
13566                        }
13567                    }
13568                }
13569            }
13570
13571            true
13572        })
13573    }
13574
13575    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13576    pub fn clear_row_highlights<T: 'static>(&mut self) {
13577        self.highlighted_rows.remove(&TypeId::of::<T>());
13578    }
13579
13580    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13581    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13582        self.highlighted_rows
13583            .get(&TypeId::of::<T>())
13584            .map_or(&[] as &[_], |vec| vec.as_slice())
13585            .iter()
13586            .map(|highlight| (highlight.range.clone(), highlight.color))
13587    }
13588
13589    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13590    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13591    /// Allows to ignore certain kinds of highlights.
13592    pub fn highlighted_display_rows(
13593        &self,
13594        window: &mut Window,
13595        cx: &mut App,
13596    ) -> BTreeMap<DisplayRow, Background> {
13597        let snapshot = self.snapshot(window, cx);
13598        let mut used_highlight_orders = HashMap::default();
13599        self.highlighted_rows
13600            .iter()
13601            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13602            .fold(
13603                BTreeMap::<DisplayRow, Background>::new(),
13604                |mut unique_rows, highlight| {
13605                    let start = highlight.range.start.to_display_point(&snapshot);
13606                    let end = highlight.range.end.to_display_point(&snapshot);
13607                    let start_row = start.row().0;
13608                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13609                        && end.column() == 0
13610                    {
13611                        end.row().0.saturating_sub(1)
13612                    } else {
13613                        end.row().0
13614                    };
13615                    for row in start_row..=end_row {
13616                        let used_index =
13617                            used_highlight_orders.entry(row).or_insert(highlight.index);
13618                        if highlight.index >= *used_index {
13619                            *used_index = highlight.index;
13620                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13621                        }
13622                    }
13623                    unique_rows
13624                },
13625            )
13626    }
13627
13628    pub fn highlighted_display_row_for_autoscroll(
13629        &self,
13630        snapshot: &DisplaySnapshot,
13631    ) -> Option<DisplayRow> {
13632        self.highlighted_rows
13633            .values()
13634            .flat_map(|highlighted_rows| highlighted_rows.iter())
13635            .filter_map(|highlight| {
13636                if highlight.should_autoscroll {
13637                    Some(highlight.range.start.to_display_point(snapshot).row())
13638                } else {
13639                    None
13640                }
13641            })
13642            .min()
13643    }
13644
13645    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13646        self.highlight_background::<SearchWithinRange>(
13647            ranges,
13648            |colors| colors.editor_document_highlight_read_background,
13649            cx,
13650        )
13651    }
13652
13653    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13654        self.breadcrumb_header = Some(new_header);
13655    }
13656
13657    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13658        self.clear_background_highlights::<SearchWithinRange>(cx);
13659    }
13660
13661    pub fn highlight_background<T: 'static>(
13662        &mut self,
13663        ranges: &[Range<Anchor>],
13664        color_fetcher: fn(&ThemeColors) -> Hsla,
13665        cx: &mut Context<Self>,
13666    ) {
13667        self.background_highlights
13668            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13669        self.scrollbar_marker_state.dirty = true;
13670        cx.notify();
13671    }
13672
13673    pub fn clear_background_highlights<T: 'static>(
13674        &mut self,
13675        cx: &mut Context<Self>,
13676    ) -> Option<BackgroundHighlight> {
13677        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13678        if !text_highlights.1.is_empty() {
13679            self.scrollbar_marker_state.dirty = true;
13680            cx.notify();
13681        }
13682        Some(text_highlights)
13683    }
13684
13685    pub fn highlight_gutter<T: 'static>(
13686        &mut self,
13687        ranges: &[Range<Anchor>],
13688        color_fetcher: fn(&App) -> Hsla,
13689        cx: &mut Context<Self>,
13690    ) {
13691        self.gutter_highlights
13692            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13693        cx.notify();
13694    }
13695
13696    pub fn clear_gutter_highlights<T: 'static>(
13697        &mut self,
13698        cx: &mut Context<Self>,
13699    ) -> Option<GutterHighlight> {
13700        cx.notify();
13701        self.gutter_highlights.remove(&TypeId::of::<T>())
13702    }
13703
13704    #[cfg(feature = "test-support")]
13705    pub fn all_text_background_highlights(
13706        &self,
13707        window: &mut Window,
13708        cx: &mut Context<Self>,
13709    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13710        let snapshot = self.snapshot(window, cx);
13711        let buffer = &snapshot.buffer_snapshot;
13712        let start = buffer.anchor_before(0);
13713        let end = buffer.anchor_after(buffer.len());
13714        let theme = cx.theme().colors();
13715        self.background_highlights_in_range(start..end, &snapshot, theme)
13716    }
13717
13718    #[cfg(feature = "test-support")]
13719    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13720        let snapshot = self.buffer().read(cx).snapshot(cx);
13721
13722        let highlights = self
13723            .background_highlights
13724            .get(&TypeId::of::<items::BufferSearchHighlights>());
13725
13726        if let Some((_color, ranges)) = highlights {
13727            ranges
13728                .iter()
13729                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13730                .collect_vec()
13731        } else {
13732            vec![]
13733        }
13734    }
13735
13736    fn document_highlights_for_position<'a>(
13737        &'a self,
13738        position: Anchor,
13739        buffer: &'a MultiBufferSnapshot,
13740    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13741        let read_highlights = self
13742            .background_highlights
13743            .get(&TypeId::of::<DocumentHighlightRead>())
13744            .map(|h| &h.1);
13745        let write_highlights = self
13746            .background_highlights
13747            .get(&TypeId::of::<DocumentHighlightWrite>())
13748            .map(|h| &h.1);
13749        let left_position = position.bias_left(buffer);
13750        let right_position = position.bias_right(buffer);
13751        read_highlights
13752            .into_iter()
13753            .chain(write_highlights)
13754            .flat_map(move |ranges| {
13755                let start_ix = match ranges.binary_search_by(|probe| {
13756                    let cmp = probe.end.cmp(&left_position, buffer);
13757                    if cmp.is_ge() {
13758                        Ordering::Greater
13759                    } else {
13760                        Ordering::Less
13761                    }
13762                }) {
13763                    Ok(i) | Err(i) => i,
13764                };
13765
13766                ranges[start_ix..]
13767                    .iter()
13768                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13769            })
13770    }
13771
13772    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13773        self.background_highlights
13774            .get(&TypeId::of::<T>())
13775            .map_or(false, |(_, highlights)| !highlights.is_empty())
13776    }
13777
13778    pub fn background_highlights_in_range(
13779        &self,
13780        search_range: Range<Anchor>,
13781        display_snapshot: &DisplaySnapshot,
13782        theme: &ThemeColors,
13783    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13784        let mut results = Vec::new();
13785        for (color_fetcher, ranges) in self.background_highlights.values() {
13786            let color = color_fetcher(theme);
13787            let start_ix = match ranges.binary_search_by(|probe| {
13788                let cmp = probe
13789                    .end
13790                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13791                if cmp.is_gt() {
13792                    Ordering::Greater
13793                } else {
13794                    Ordering::Less
13795                }
13796            }) {
13797                Ok(i) | Err(i) => i,
13798            };
13799            for range in &ranges[start_ix..] {
13800                if range
13801                    .start
13802                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13803                    .is_ge()
13804                {
13805                    break;
13806                }
13807
13808                let start = range.start.to_display_point(display_snapshot);
13809                let end = range.end.to_display_point(display_snapshot);
13810                results.push((start..end, color))
13811            }
13812        }
13813        results
13814    }
13815
13816    pub fn background_highlight_row_ranges<T: 'static>(
13817        &self,
13818        search_range: Range<Anchor>,
13819        display_snapshot: &DisplaySnapshot,
13820        count: usize,
13821    ) -> Vec<RangeInclusive<DisplayPoint>> {
13822        let mut results = Vec::new();
13823        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13824            return vec![];
13825        };
13826
13827        let start_ix = match ranges.binary_search_by(|probe| {
13828            let cmp = probe
13829                .end
13830                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13831            if cmp.is_gt() {
13832                Ordering::Greater
13833            } else {
13834                Ordering::Less
13835            }
13836        }) {
13837            Ok(i) | Err(i) => i,
13838        };
13839        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13840            if let (Some(start_display), Some(end_display)) = (start, end) {
13841                results.push(
13842                    start_display.to_display_point(display_snapshot)
13843                        ..=end_display.to_display_point(display_snapshot),
13844                );
13845            }
13846        };
13847        let mut start_row: Option<Point> = None;
13848        let mut end_row: Option<Point> = None;
13849        if ranges.len() > count {
13850            return Vec::new();
13851        }
13852        for range in &ranges[start_ix..] {
13853            if range
13854                .start
13855                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13856                .is_ge()
13857            {
13858                break;
13859            }
13860            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13861            if let Some(current_row) = &end_row {
13862                if end.row == current_row.row {
13863                    continue;
13864                }
13865            }
13866            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13867            if start_row.is_none() {
13868                assert_eq!(end_row, None);
13869                start_row = Some(start);
13870                end_row = Some(end);
13871                continue;
13872            }
13873            if let Some(current_end) = end_row.as_mut() {
13874                if start.row > current_end.row + 1 {
13875                    push_region(start_row, end_row);
13876                    start_row = Some(start);
13877                    end_row = Some(end);
13878                } else {
13879                    // Merge two hunks.
13880                    *current_end = end;
13881                }
13882            } else {
13883                unreachable!();
13884            }
13885        }
13886        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13887        push_region(start_row, end_row);
13888        results
13889    }
13890
13891    pub fn gutter_highlights_in_range(
13892        &self,
13893        search_range: Range<Anchor>,
13894        display_snapshot: &DisplaySnapshot,
13895        cx: &App,
13896    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13897        let mut results = Vec::new();
13898        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13899            let color = color_fetcher(cx);
13900            let start_ix = match ranges.binary_search_by(|probe| {
13901                let cmp = probe
13902                    .end
13903                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13904                if cmp.is_gt() {
13905                    Ordering::Greater
13906                } else {
13907                    Ordering::Less
13908                }
13909            }) {
13910                Ok(i) | Err(i) => i,
13911            };
13912            for range in &ranges[start_ix..] {
13913                if range
13914                    .start
13915                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13916                    .is_ge()
13917                {
13918                    break;
13919                }
13920
13921                let start = range.start.to_display_point(display_snapshot);
13922                let end = range.end.to_display_point(display_snapshot);
13923                results.push((start..end, color))
13924            }
13925        }
13926        results
13927    }
13928
13929    /// Get the text ranges corresponding to the redaction query
13930    pub fn redacted_ranges(
13931        &self,
13932        search_range: Range<Anchor>,
13933        display_snapshot: &DisplaySnapshot,
13934        cx: &App,
13935    ) -> Vec<Range<DisplayPoint>> {
13936        display_snapshot
13937            .buffer_snapshot
13938            .redacted_ranges(search_range, |file| {
13939                if let Some(file) = file {
13940                    file.is_private()
13941                        && EditorSettings::get(
13942                            Some(SettingsLocation {
13943                                worktree_id: file.worktree_id(cx),
13944                                path: file.path().as_ref(),
13945                            }),
13946                            cx,
13947                        )
13948                        .redact_private_values
13949                } else {
13950                    false
13951                }
13952            })
13953            .map(|range| {
13954                range.start.to_display_point(display_snapshot)
13955                    ..range.end.to_display_point(display_snapshot)
13956            })
13957            .collect()
13958    }
13959
13960    pub fn highlight_text<T: 'static>(
13961        &mut self,
13962        ranges: Vec<Range<Anchor>>,
13963        style: HighlightStyle,
13964        cx: &mut Context<Self>,
13965    ) {
13966        self.display_map.update(cx, |map, _| {
13967            map.highlight_text(TypeId::of::<T>(), ranges, style)
13968        });
13969        cx.notify();
13970    }
13971
13972    pub(crate) fn highlight_inlays<T: 'static>(
13973        &mut self,
13974        highlights: Vec<InlayHighlight>,
13975        style: HighlightStyle,
13976        cx: &mut Context<Self>,
13977    ) {
13978        self.display_map.update(cx, |map, _| {
13979            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13980        });
13981        cx.notify();
13982    }
13983
13984    pub fn text_highlights<'a, T: 'static>(
13985        &'a self,
13986        cx: &'a App,
13987    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13988        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13989    }
13990
13991    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13992        let cleared = self
13993            .display_map
13994            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13995        if cleared {
13996            cx.notify();
13997        }
13998    }
13999
14000    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14001        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14002            && self.focus_handle.is_focused(window)
14003    }
14004
14005    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14006        self.show_cursor_when_unfocused = is_enabled;
14007        cx.notify();
14008    }
14009
14010    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14011        self.project
14012            .as_ref()
14013            .map(|project| project.read(cx).lsp_store())
14014    }
14015
14016    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14017        cx.notify();
14018    }
14019
14020    fn on_buffer_event(
14021        &mut self,
14022        multibuffer: &Entity<MultiBuffer>,
14023        event: &multi_buffer::Event,
14024        window: &mut Window,
14025        cx: &mut Context<Self>,
14026    ) {
14027        match event {
14028            multi_buffer::Event::Edited {
14029                singleton_buffer_edited,
14030                edited_buffer: buffer_edited,
14031            } => {
14032                self.scrollbar_marker_state.dirty = true;
14033                self.active_indent_guides_state.dirty = true;
14034                self.refresh_active_diagnostics(cx);
14035                self.refresh_code_actions(window, cx);
14036                if self.has_active_inline_completion() {
14037                    self.update_visible_inline_completion(window, cx);
14038                }
14039                if let Some(buffer) = buffer_edited {
14040                    let buffer_id = buffer.read(cx).remote_id();
14041                    if !self.registered_buffers.contains_key(&buffer_id) {
14042                        if let Some(lsp_store) = self.lsp_store(cx) {
14043                            lsp_store.update(cx, |lsp_store, cx| {
14044                                self.registered_buffers.insert(
14045                                    buffer_id,
14046                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
14047                                );
14048                            })
14049                        }
14050                    }
14051                }
14052                cx.emit(EditorEvent::BufferEdited);
14053                cx.emit(SearchEvent::MatchesInvalidated);
14054                if *singleton_buffer_edited {
14055                    if let Some(project) = &self.project {
14056                        let project = project.read(cx);
14057                        #[allow(clippy::mutable_key_type)]
14058                        let languages_affected = multibuffer
14059                            .read(cx)
14060                            .all_buffers()
14061                            .into_iter()
14062                            .filter_map(|buffer| {
14063                                let buffer = buffer.read(cx);
14064                                let language = buffer.language()?;
14065                                if project.is_local()
14066                                    && project
14067                                        .language_servers_for_local_buffer(buffer, cx)
14068                                        .count()
14069                                        == 0
14070                                {
14071                                    None
14072                                } else {
14073                                    Some(language)
14074                                }
14075                            })
14076                            .cloned()
14077                            .collect::<HashSet<_>>();
14078                        if !languages_affected.is_empty() {
14079                            self.refresh_inlay_hints(
14080                                InlayHintRefreshReason::BufferEdited(languages_affected),
14081                                cx,
14082                            );
14083                        }
14084                    }
14085                }
14086
14087                let Some(project) = &self.project else { return };
14088                let (telemetry, is_via_ssh) = {
14089                    let project = project.read(cx);
14090                    let telemetry = project.client().telemetry().clone();
14091                    let is_via_ssh = project.is_via_ssh();
14092                    (telemetry, is_via_ssh)
14093                };
14094                refresh_linked_ranges(self, window, cx);
14095                telemetry.log_edit_event("editor", is_via_ssh);
14096            }
14097            multi_buffer::Event::ExcerptsAdded {
14098                buffer,
14099                predecessor,
14100                excerpts,
14101            } => {
14102                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14103                let buffer_id = buffer.read(cx).remote_id();
14104                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14105                    if let Some(project) = &self.project {
14106                        get_uncommitted_diff_for_buffer(
14107                            project,
14108                            [buffer.clone()],
14109                            self.buffer.clone(),
14110                            cx,
14111                        );
14112                    }
14113                }
14114                cx.emit(EditorEvent::ExcerptsAdded {
14115                    buffer: buffer.clone(),
14116                    predecessor: *predecessor,
14117                    excerpts: excerpts.clone(),
14118                });
14119                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14120            }
14121            multi_buffer::Event::ExcerptsRemoved { ids } => {
14122                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14123                let buffer = self.buffer.read(cx);
14124                self.registered_buffers
14125                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14126                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14127            }
14128            multi_buffer::Event::ExcerptsEdited { ids } => {
14129                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14130            }
14131            multi_buffer::Event::ExcerptsExpanded { ids } => {
14132                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14133                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14134            }
14135            multi_buffer::Event::Reparsed(buffer_id) => {
14136                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14137
14138                cx.emit(EditorEvent::Reparsed(*buffer_id));
14139            }
14140            multi_buffer::Event::DiffHunksToggled => {
14141                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14142            }
14143            multi_buffer::Event::LanguageChanged(buffer_id) => {
14144                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14145                cx.emit(EditorEvent::Reparsed(*buffer_id));
14146                cx.notify();
14147            }
14148            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14149            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14150            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14151                cx.emit(EditorEvent::TitleChanged)
14152            }
14153            // multi_buffer::Event::DiffBaseChanged => {
14154            //     self.scrollbar_marker_state.dirty = true;
14155            //     cx.emit(EditorEvent::DiffBaseChanged);
14156            //     cx.notify();
14157            // }
14158            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14159            multi_buffer::Event::DiagnosticsUpdated => {
14160                self.refresh_active_diagnostics(cx);
14161                self.scrollbar_marker_state.dirty = true;
14162                cx.notify();
14163            }
14164            _ => {}
14165        };
14166    }
14167
14168    fn on_display_map_changed(
14169        &mut self,
14170        _: Entity<DisplayMap>,
14171        _: &mut Window,
14172        cx: &mut Context<Self>,
14173    ) {
14174        cx.notify();
14175    }
14176
14177    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14178        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14179        self.refresh_inline_completion(true, false, window, cx);
14180        self.refresh_inlay_hints(
14181            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14182                self.selections.newest_anchor().head(),
14183                &self.buffer.read(cx).snapshot(cx),
14184                cx,
14185            )),
14186            cx,
14187        );
14188
14189        let old_cursor_shape = self.cursor_shape;
14190
14191        {
14192            let editor_settings = EditorSettings::get_global(cx);
14193            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14194            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14195            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14196        }
14197
14198        if old_cursor_shape != self.cursor_shape {
14199            cx.emit(EditorEvent::CursorShapeChanged);
14200        }
14201
14202        let project_settings = ProjectSettings::get_global(cx);
14203        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14204
14205        if self.mode == EditorMode::Full {
14206            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14207            if self.git_blame_inline_enabled != inline_blame_enabled {
14208                self.toggle_git_blame_inline_internal(false, window, cx);
14209            }
14210        }
14211
14212        cx.notify();
14213    }
14214
14215    pub fn set_searchable(&mut self, searchable: bool) {
14216        self.searchable = searchable;
14217    }
14218
14219    pub fn searchable(&self) -> bool {
14220        self.searchable
14221    }
14222
14223    fn open_proposed_changes_editor(
14224        &mut self,
14225        _: &OpenProposedChangesEditor,
14226        window: &mut Window,
14227        cx: &mut Context<Self>,
14228    ) {
14229        let Some(workspace) = self.workspace() else {
14230            cx.propagate();
14231            return;
14232        };
14233
14234        let selections = self.selections.all::<usize>(cx);
14235        let multi_buffer = self.buffer.read(cx);
14236        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14237        let mut new_selections_by_buffer = HashMap::default();
14238        for selection in selections {
14239            for (buffer, range, _) in
14240                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14241            {
14242                let mut range = range.to_point(buffer);
14243                range.start.column = 0;
14244                range.end.column = buffer.line_len(range.end.row);
14245                new_selections_by_buffer
14246                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14247                    .or_insert(Vec::new())
14248                    .push(range)
14249            }
14250        }
14251
14252        let proposed_changes_buffers = new_selections_by_buffer
14253            .into_iter()
14254            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14255            .collect::<Vec<_>>();
14256        let proposed_changes_editor = cx.new(|cx| {
14257            ProposedChangesEditor::new(
14258                "Proposed changes",
14259                proposed_changes_buffers,
14260                self.project.clone(),
14261                window,
14262                cx,
14263            )
14264        });
14265
14266        window.defer(cx, move |window, cx| {
14267            workspace.update(cx, |workspace, cx| {
14268                workspace.active_pane().update(cx, |pane, cx| {
14269                    pane.add_item(
14270                        Box::new(proposed_changes_editor),
14271                        true,
14272                        true,
14273                        None,
14274                        window,
14275                        cx,
14276                    );
14277                });
14278            });
14279        });
14280    }
14281
14282    pub fn open_excerpts_in_split(
14283        &mut self,
14284        _: &OpenExcerptsSplit,
14285        window: &mut Window,
14286        cx: &mut Context<Self>,
14287    ) {
14288        self.open_excerpts_common(None, true, window, cx)
14289    }
14290
14291    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14292        self.open_excerpts_common(None, false, window, cx)
14293    }
14294
14295    fn open_excerpts_common(
14296        &mut self,
14297        jump_data: Option<JumpData>,
14298        split: bool,
14299        window: &mut Window,
14300        cx: &mut Context<Self>,
14301    ) {
14302        let Some(workspace) = self.workspace() else {
14303            cx.propagate();
14304            return;
14305        };
14306
14307        if self.buffer.read(cx).is_singleton() {
14308            cx.propagate();
14309            return;
14310        }
14311
14312        let mut new_selections_by_buffer = HashMap::default();
14313        match &jump_data {
14314            Some(JumpData::MultiBufferPoint {
14315                excerpt_id,
14316                position,
14317                anchor,
14318                line_offset_from_top,
14319            }) => {
14320                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14321                if let Some(buffer) = multi_buffer_snapshot
14322                    .buffer_id_for_excerpt(*excerpt_id)
14323                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14324                {
14325                    let buffer_snapshot = buffer.read(cx).snapshot();
14326                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14327                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14328                    } else {
14329                        buffer_snapshot.clip_point(*position, Bias::Left)
14330                    };
14331                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14332                    new_selections_by_buffer.insert(
14333                        buffer,
14334                        (
14335                            vec![jump_to_offset..jump_to_offset],
14336                            Some(*line_offset_from_top),
14337                        ),
14338                    );
14339                }
14340            }
14341            Some(JumpData::MultiBufferRow {
14342                row,
14343                line_offset_from_top,
14344            }) => {
14345                let point = MultiBufferPoint::new(row.0, 0);
14346                if let Some((buffer, buffer_point, _)) =
14347                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14348                {
14349                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14350                    new_selections_by_buffer
14351                        .entry(buffer)
14352                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14353                        .0
14354                        .push(buffer_offset..buffer_offset)
14355                }
14356            }
14357            None => {
14358                let selections = self.selections.all::<usize>(cx);
14359                let multi_buffer = self.buffer.read(cx);
14360                for selection in selections {
14361                    for (buffer, mut range, _) in multi_buffer
14362                        .snapshot(cx)
14363                        .range_to_buffer_ranges(selection.range())
14364                    {
14365                        // When editing branch buffers, jump to the corresponding location
14366                        // in their base buffer.
14367                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14368                        let buffer = buffer_handle.read(cx);
14369                        if let Some(base_buffer) = buffer.base_buffer() {
14370                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14371                            buffer_handle = base_buffer;
14372                        }
14373
14374                        if selection.reversed {
14375                            mem::swap(&mut range.start, &mut range.end);
14376                        }
14377                        new_selections_by_buffer
14378                            .entry(buffer_handle)
14379                            .or_insert((Vec::new(), None))
14380                            .0
14381                            .push(range)
14382                    }
14383                }
14384            }
14385        }
14386
14387        if new_selections_by_buffer.is_empty() {
14388            return;
14389        }
14390
14391        // We defer the pane interaction because we ourselves are a workspace item
14392        // and activating a new item causes the pane to call a method on us reentrantly,
14393        // which panics if we're on the stack.
14394        window.defer(cx, move |window, cx| {
14395            workspace.update(cx, |workspace, cx| {
14396                let pane = if split {
14397                    workspace.adjacent_pane(window, cx)
14398                } else {
14399                    workspace.active_pane().clone()
14400                };
14401
14402                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14403                    let editor = buffer
14404                        .read(cx)
14405                        .file()
14406                        .is_none()
14407                        .then(|| {
14408                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14409                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14410                            // Instead, we try to activate the existing editor in the pane first.
14411                            let (editor, pane_item_index) =
14412                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14413                                    let editor = item.downcast::<Editor>()?;
14414                                    let singleton_buffer =
14415                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14416                                    if singleton_buffer == buffer {
14417                                        Some((editor, i))
14418                                    } else {
14419                                        None
14420                                    }
14421                                })?;
14422                            pane.update(cx, |pane, cx| {
14423                                pane.activate_item(pane_item_index, true, true, window, cx)
14424                            });
14425                            Some(editor)
14426                        })
14427                        .flatten()
14428                        .unwrap_or_else(|| {
14429                            workspace.open_project_item::<Self>(
14430                                pane.clone(),
14431                                buffer,
14432                                true,
14433                                true,
14434                                window,
14435                                cx,
14436                            )
14437                        });
14438
14439                    editor.update(cx, |editor, cx| {
14440                        let autoscroll = match scroll_offset {
14441                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14442                            None => Autoscroll::newest(),
14443                        };
14444                        let nav_history = editor.nav_history.take();
14445                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14446                            s.select_ranges(ranges);
14447                        });
14448                        editor.nav_history = nav_history;
14449                    });
14450                }
14451            })
14452        });
14453    }
14454
14455    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14456        let snapshot = self.buffer.read(cx).read(cx);
14457        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14458        Some(
14459            ranges
14460                .iter()
14461                .map(move |range| {
14462                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14463                })
14464                .collect(),
14465        )
14466    }
14467
14468    fn selection_replacement_ranges(
14469        &self,
14470        range: Range<OffsetUtf16>,
14471        cx: &mut App,
14472    ) -> Vec<Range<OffsetUtf16>> {
14473        let selections = self.selections.all::<OffsetUtf16>(cx);
14474        let newest_selection = selections
14475            .iter()
14476            .max_by_key(|selection| selection.id)
14477            .unwrap();
14478        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14479        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14480        let snapshot = self.buffer.read(cx).read(cx);
14481        selections
14482            .into_iter()
14483            .map(|mut selection| {
14484                selection.start.0 =
14485                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14486                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14487                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14488                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14489            })
14490            .collect()
14491    }
14492
14493    fn report_editor_event(
14494        &self,
14495        event_type: &'static str,
14496        file_extension: Option<String>,
14497        cx: &App,
14498    ) {
14499        if cfg!(any(test, feature = "test-support")) {
14500            return;
14501        }
14502
14503        let Some(project) = &self.project else { return };
14504
14505        // If None, we are in a file without an extension
14506        let file = self
14507            .buffer
14508            .read(cx)
14509            .as_singleton()
14510            .and_then(|b| b.read(cx).file());
14511        let file_extension = file_extension.or(file
14512            .as_ref()
14513            .and_then(|file| Path::new(file.file_name(cx)).extension())
14514            .and_then(|e| e.to_str())
14515            .map(|a| a.to_string()));
14516
14517        let vim_mode = cx
14518            .global::<SettingsStore>()
14519            .raw_user_settings()
14520            .get("vim_mode")
14521            == Some(&serde_json::Value::Bool(true));
14522
14523        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14524        let copilot_enabled = edit_predictions_provider
14525            == language::language_settings::EditPredictionProvider::Copilot;
14526        let copilot_enabled_for_language = self
14527            .buffer
14528            .read(cx)
14529            .settings_at(0, cx)
14530            .show_edit_predictions;
14531
14532        let project = project.read(cx);
14533        telemetry::event!(
14534            event_type,
14535            file_extension,
14536            vim_mode,
14537            copilot_enabled,
14538            copilot_enabled_for_language,
14539            edit_predictions_provider,
14540            is_via_ssh = project.is_via_ssh(),
14541        );
14542    }
14543
14544    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14545    /// with each line being an array of {text, highlight} objects.
14546    fn copy_highlight_json(
14547        &mut self,
14548        _: &CopyHighlightJson,
14549        window: &mut Window,
14550        cx: &mut Context<Self>,
14551    ) {
14552        #[derive(Serialize)]
14553        struct Chunk<'a> {
14554            text: String,
14555            highlight: Option<&'a str>,
14556        }
14557
14558        let snapshot = self.buffer.read(cx).snapshot(cx);
14559        let range = self
14560            .selected_text_range(false, window, cx)
14561            .and_then(|selection| {
14562                if selection.range.is_empty() {
14563                    None
14564                } else {
14565                    Some(selection.range)
14566                }
14567            })
14568            .unwrap_or_else(|| 0..snapshot.len());
14569
14570        let chunks = snapshot.chunks(range, true);
14571        let mut lines = Vec::new();
14572        let mut line: VecDeque<Chunk> = VecDeque::new();
14573
14574        let Some(style) = self.style.as_ref() else {
14575            return;
14576        };
14577
14578        for chunk in chunks {
14579            let highlight = chunk
14580                .syntax_highlight_id
14581                .and_then(|id| id.name(&style.syntax));
14582            let mut chunk_lines = chunk.text.split('\n').peekable();
14583            while let Some(text) = chunk_lines.next() {
14584                let mut merged_with_last_token = false;
14585                if let Some(last_token) = line.back_mut() {
14586                    if last_token.highlight == highlight {
14587                        last_token.text.push_str(text);
14588                        merged_with_last_token = true;
14589                    }
14590                }
14591
14592                if !merged_with_last_token {
14593                    line.push_back(Chunk {
14594                        text: text.into(),
14595                        highlight,
14596                    });
14597                }
14598
14599                if chunk_lines.peek().is_some() {
14600                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14601                        line.pop_front();
14602                    }
14603                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14604                        line.pop_back();
14605                    }
14606
14607                    lines.push(mem::take(&mut line));
14608                }
14609            }
14610        }
14611
14612        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14613            return;
14614        };
14615        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14616    }
14617
14618    pub fn open_context_menu(
14619        &mut self,
14620        _: &OpenContextMenu,
14621        window: &mut Window,
14622        cx: &mut Context<Self>,
14623    ) {
14624        self.request_autoscroll(Autoscroll::newest(), cx);
14625        let position = self.selections.newest_display(cx).start;
14626        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14627    }
14628
14629    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14630        &self.inlay_hint_cache
14631    }
14632
14633    pub fn replay_insert_event(
14634        &mut self,
14635        text: &str,
14636        relative_utf16_range: Option<Range<isize>>,
14637        window: &mut Window,
14638        cx: &mut Context<Self>,
14639    ) {
14640        if !self.input_enabled {
14641            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14642            return;
14643        }
14644        if let Some(relative_utf16_range) = relative_utf16_range {
14645            let selections = self.selections.all::<OffsetUtf16>(cx);
14646            self.change_selections(None, window, cx, |s| {
14647                let new_ranges = selections.into_iter().map(|range| {
14648                    let start = OffsetUtf16(
14649                        range
14650                            .head()
14651                            .0
14652                            .saturating_add_signed(relative_utf16_range.start),
14653                    );
14654                    let end = OffsetUtf16(
14655                        range
14656                            .head()
14657                            .0
14658                            .saturating_add_signed(relative_utf16_range.end),
14659                    );
14660                    start..end
14661                });
14662                s.select_ranges(new_ranges);
14663            });
14664        }
14665
14666        self.handle_input(text, window, cx);
14667    }
14668
14669    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14670        let Some(provider) = self.semantics_provider.as_ref() else {
14671            return false;
14672        };
14673
14674        let mut supports = false;
14675        self.buffer().read(cx).for_each_buffer(|buffer| {
14676            supports |= provider.supports_inlay_hints(buffer, cx);
14677        });
14678        supports
14679    }
14680
14681    pub fn is_focused(&self, window: &Window) -> bool {
14682        self.focus_handle.is_focused(window)
14683    }
14684
14685    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14686        cx.emit(EditorEvent::Focused);
14687
14688        if let Some(descendant) = self
14689            .last_focused_descendant
14690            .take()
14691            .and_then(|descendant| descendant.upgrade())
14692        {
14693            window.focus(&descendant);
14694        } else {
14695            if let Some(blame) = self.blame.as_ref() {
14696                blame.update(cx, GitBlame::focus)
14697            }
14698
14699            self.blink_manager.update(cx, BlinkManager::enable);
14700            self.show_cursor_names(window, cx);
14701            self.buffer.update(cx, |buffer, cx| {
14702                buffer.finalize_last_transaction(cx);
14703                if self.leader_peer_id.is_none() {
14704                    buffer.set_active_selections(
14705                        &self.selections.disjoint_anchors(),
14706                        self.selections.line_mode,
14707                        self.cursor_shape,
14708                        cx,
14709                    );
14710                }
14711            });
14712        }
14713    }
14714
14715    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14716        cx.emit(EditorEvent::FocusedIn)
14717    }
14718
14719    fn handle_focus_out(
14720        &mut self,
14721        event: FocusOutEvent,
14722        _window: &mut Window,
14723        _cx: &mut Context<Self>,
14724    ) {
14725        if event.blurred != self.focus_handle {
14726            self.last_focused_descendant = Some(event.blurred);
14727        }
14728    }
14729
14730    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14731        self.blink_manager.update(cx, BlinkManager::disable);
14732        self.buffer
14733            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14734
14735        if let Some(blame) = self.blame.as_ref() {
14736            blame.update(cx, GitBlame::blur)
14737        }
14738        if !self.hover_state.focused(window, cx) {
14739            hide_hover(self, cx);
14740        }
14741
14742        self.hide_context_menu(window, cx);
14743        self.discard_inline_completion(false, cx);
14744        cx.emit(EditorEvent::Blurred);
14745        cx.notify();
14746    }
14747
14748    pub fn register_action<A: Action>(
14749        &mut self,
14750        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14751    ) -> Subscription {
14752        let id = self.next_editor_action_id.post_inc();
14753        let listener = Arc::new(listener);
14754        self.editor_actions.borrow_mut().insert(
14755            id,
14756            Box::new(move |window, _| {
14757                let listener = listener.clone();
14758                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14759                    let action = action.downcast_ref().unwrap();
14760                    if phase == DispatchPhase::Bubble {
14761                        listener(action, window, cx)
14762                    }
14763                })
14764            }),
14765        );
14766
14767        let editor_actions = self.editor_actions.clone();
14768        Subscription::new(move || {
14769            editor_actions.borrow_mut().remove(&id);
14770        })
14771    }
14772
14773    pub fn file_header_size(&self) -> u32 {
14774        FILE_HEADER_HEIGHT
14775    }
14776
14777    pub fn revert(
14778        &mut self,
14779        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14780        window: &mut Window,
14781        cx: &mut Context<Self>,
14782    ) {
14783        self.buffer().update(cx, |multi_buffer, cx| {
14784            for (buffer_id, changes) in revert_changes {
14785                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14786                    buffer.update(cx, |buffer, cx| {
14787                        buffer.edit(
14788                            changes.into_iter().map(|(range, text)| {
14789                                (range, text.to_string().map(Arc::<str>::from))
14790                            }),
14791                            None,
14792                            cx,
14793                        );
14794                    });
14795                }
14796            }
14797        });
14798        self.change_selections(None, window, cx, |selections| selections.refresh());
14799    }
14800
14801    pub fn to_pixel_point(
14802        &self,
14803        source: multi_buffer::Anchor,
14804        editor_snapshot: &EditorSnapshot,
14805        window: &mut Window,
14806    ) -> Option<gpui::Point<Pixels>> {
14807        let source_point = source.to_display_point(editor_snapshot);
14808        self.display_to_pixel_point(source_point, editor_snapshot, window)
14809    }
14810
14811    pub fn display_to_pixel_point(
14812        &self,
14813        source: DisplayPoint,
14814        editor_snapshot: &EditorSnapshot,
14815        window: &mut Window,
14816    ) -> Option<gpui::Point<Pixels>> {
14817        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14818        let text_layout_details = self.text_layout_details(window);
14819        let scroll_top = text_layout_details
14820            .scroll_anchor
14821            .scroll_position(editor_snapshot)
14822            .y;
14823
14824        if source.row().as_f32() < scroll_top.floor() {
14825            return None;
14826        }
14827        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14828        let source_y = line_height * (source.row().as_f32() - scroll_top);
14829        Some(gpui::Point::new(source_x, source_y))
14830    }
14831
14832    pub fn has_visible_completions_menu(&self) -> bool {
14833        !self.edit_prediction_preview_is_active()
14834            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14835                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14836            })
14837    }
14838
14839    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14840        self.addons
14841            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14842    }
14843
14844    pub fn unregister_addon<T: Addon>(&mut self) {
14845        self.addons.remove(&std::any::TypeId::of::<T>());
14846    }
14847
14848    pub fn addon<T: Addon>(&self) -> Option<&T> {
14849        let type_id = std::any::TypeId::of::<T>();
14850        self.addons
14851            .get(&type_id)
14852            .and_then(|item| item.to_any().downcast_ref::<T>())
14853    }
14854
14855    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14856        let text_layout_details = self.text_layout_details(window);
14857        let style = &text_layout_details.editor_style;
14858        let font_id = window.text_system().resolve_font(&style.text.font());
14859        let font_size = style.text.font_size.to_pixels(window.rem_size());
14860        let line_height = style.text.line_height_in_pixels(window.rem_size());
14861        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14862
14863        gpui::Size::new(em_width, line_height)
14864    }
14865}
14866
14867fn get_uncommitted_diff_for_buffer(
14868    project: &Entity<Project>,
14869    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14870    buffer: Entity<MultiBuffer>,
14871    cx: &mut App,
14872) {
14873    let mut tasks = Vec::new();
14874    project.update(cx, |project, cx| {
14875        for buffer in buffers {
14876            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14877        }
14878    });
14879    cx.spawn(|mut cx| async move {
14880        let diffs = futures::future::join_all(tasks).await;
14881        buffer
14882            .update(&mut cx, |buffer, cx| {
14883                for diff in diffs.into_iter().flatten() {
14884                    buffer.add_diff(diff, cx);
14885                }
14886            })
14887            .ok();
14888    })
14889    .detach();
14890}
14891
14892fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14893    let tab_size = tab_size.get() as usize;
14894    let mut width = offset;
14895
14896    for ch in text.chars() {
14897        width += if ch == '\t' {
14898            tab_size - (width % tab_size)
14899        } else {
14900            1
14901        };
14902    }
14903
14904    width - offset
14905}
14906
14907#[cfg(test)]
14908mod tests {
14909    use super::*;
14910
14911    #[test]
14912    fn test_string_size_with_expanded_tabs() {
14913        let nz = |val| NonZeroU32::new(val).unwrap();
14914        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14915        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14916        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14917        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14918        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14919        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14920        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14921        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14922    }
14923}
14924
14925/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14926struct WordBreakingTokenizer<'a> {
14927    input: &'a str,
14928}
14929
14930impl<'a> WordBreakingTokenizer<'a> {
14931    fn new(input: &'a str) -> Self {
14932        Self { input }
14933    }
14934}
14935
14936fn is_char_ideographic(ch: char) -> bool {
14937    use unicode_script::Script::*;
14938    use unicode_script::UnicodeScript;
14939    matches!(ch.script(), Han | Tangut | Yi)
14940}
14941
14942fn is_grapheme_ideographic(text: &str) -> bool {
14943    text.chars().any(is_char_ideographic)
14944}
14945
14946fn is_grapheme_whitespace(text: &str) -> bool {
14947    text.chars().any(|x| x.is_whitespace())
14948}
14949
14950fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14951    text.chars().next().map_or(false, |ch| {
14952        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14953    })
14954}
14955
14956#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14957struct WordBreakToken<'a> {
14958    token: &'a str,
14959    grapheme_len: usize,
14960    is_whitespace: bool,
14961}
14962
14963impl<'a> Iterator for WordBreakingTokenizer<'a> {
14964    /// Yields a span, the count of graphemes in the token, and whether it was
14965    /// whitespace. Note that it also breaks at word boundaries.
14966    type Item = WordBreakToken<'a>;
14967
14968    fn next(&mut self) -> Option<Self::Item> {
14969        use unicode_segmentation::UnicodeSegmentation;
14970        if self.input.is_empty() {
14971            return None;
14972        }
14973
14974        let mut iter = self.input.graphemes(true).peekable();
14975        let mut offset = 0;
14976        let mut graphemes = 0;
14977        if let Some(first_grapheme) = iter.next() {
14978            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14979            offset += first_grapheme.len();
14980            graphemes += 1;
14981            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14982                if let Some(grapheme) = iter.peek().copied() {
14983                    if should_stay_with_preceding_ideograph(grapheme) {
14984                        offset += grapheme.len();
14985                        graphemes += 1;
14986                    }
14987                }
14988            } else {
14989                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14990                let mut next_word_bound = words.peek().copied();
14991                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14992                    next_word_bound = words.next();
14993                }
14994                while let Some(grapheme) = iter.peek().copied() {
14995                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14996                        break;
14997                    };
14998                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14999                        break;
15000                    };
15001                    offset += grapheme.len();
15002                    graphemes += 1;
15003                    iter.next();
15004                }
15005            }
15006            let token = &self.input[..offset];
15007            self.input = &self.input[offset..];
15008            if is_whitespace {
15009                Some(WordBreakToken {
15010                    token: " ",
15011                    grapheme_len: 1,
15012                    is_whitespace: true,
15013                })
15014            } else {
15015                Some(WordBreakToken {
15016                    token,
15017                    grapheme_len: graphemes,
15018                    is_whitespace: false,
15019                })
15020            }
15021        } else {
15022            None
15023        }
15024    }
15025}
15026
15027#[test]
15028fn test_word_breaking_tokenizer() {
15029    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15030        ("", &[]),
15031        ("  ", &[(" ", 1, true)]),
15032        ("Ʒ", &[("Ʒ", 1, false)]),
15033        ("Ǽ", &[("Ǽ", 1, false)]),
15034        ("", &[("", 1, false)]),
15035        ("⋑⋑", &[("⋑⋑", 2, false)]),
15036        (
15037            "原理,进而",
15038            &[
15039                ("", 1, false),
15040                ("理,", 2, false),
15041                ("", 1, false),
15042                ("", 1, false),
15043            ],
15044        ),
15045        (
15046            "hello world",
15047            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15048        ),
15049        (
15050            "hello, world",
15051            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15052        ),
15053        (
15054            "  hello world",
15055            &[
15056                (" ", 1, true),
15057                ("hello", 5, false),
15058                (" ", 1, true),
15059                ("world", 5, false),
15060            ],
15061        ),
15062        (
15063            "这是什么 \n 钢笔",
15064            &[
15065                ("", 1, false),
15066                ("", 1, false),
15067                ("", 1, false),
15068                ("", 1, false),
15069                (" ", 1, true),
15070                ("", 1, false),
15071                ("", 1, false),
15072            ],
15073        ),
15074        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15075    ];
15076
15077    for (input, result) in tests {
15078        assert_eq!(
15079            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15080            result
15081                .iter()
15082                .copied()
15083                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15084                    token,
15085                    grapheme_len,
15086                    is_whitespace,
15087                })
15088                .collect::<Vec<_>>()
15089        );
15090    }
15091}
15092
15093fn wrap_with_prefix(
15094    line_prefix: String,
15095    unwrapped_text: String,
15096    wrap_column: usize,
15097    tab_size: NonZeroU32,
15098) -> String {
15099    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15100    let mut wrapped_text = String::new();
15101    let mut current_line = line_prefix.clone();
15102
15103    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15104    let mut current_line_len = line_prefix_len;
15105    for WordBreakToken {
15106        token,
15107        grapheme_len,
15108        is_whitespace,
15109    } in tokenizer
15110    {
15111        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15112            wrapped_text.push_str(current_line.trim_end());
15113            wrapped_text.push('\n');
15114            current_line.truncate(line_prefix.len());
15115            current_line_len = line_prefix_len;
15116            if !is_whitespace {
15117                current_line.push_str(token);
15118                current_line_len += grapheme_len;
15119            }
15120        } else if !is_whitespace {
15121            current_line.push_str(token);
15122            current_line_len += grapheme_len;
15123        } else if current_line_len != line_prefix_len {
15124            current_line.push(' ');
15125            current_line_len += 1;
15126        }
15127    }
15128
15129    if !current_line.is_empty() {
15130        wrapped_text.push_str(&current_line);
15131    }
15132    wrapped_text
15133}
15134
15135#[test]
15136fn test_wrap_with_prefix() {
15137    assert_eq!(
15138        wrap_with_prefix(
15139            "# ".to_string(),
15140            "abcdefg".to_string(),
15141            4,
15142            NonZeroU32::new(4).unwrap()
15143        ),
15144        "# abcdefg"
15145    );
15146    assert_eq!(
15147        wrap_with_prefix(
15148            "".to_string(),
15149            "\thello world".to_string(),
15150            8,
15151            NonZeroU32::new(4).unwrap()
15152        ),
15153        "hello\nworld"
15154    );
15155    assert_eq!(
15156        wrap_with_prefix(
15157            "// ".to_string(),
15158            "xx \nyy zz aa bb cc".to_string(),
15159            12,
15160            NonZeroU32::new(4).unwrap()
15161        ),
15162        "// xx yy zz\n// aa bb cc"
15163    );
15164    assert_eq!(
15165        wrap_with_prefix(
15166            String::new(),
15167            "这是什么 \n 钢笔".to_string(),
15168            3,
15169            NonZeroU32::new(4).unwrap()
15170        ),
15171        "这是什\n么 钢\n"
15172    );
15173}
15174
15175pub trait CollaborationHub {
15176    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15177    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15178    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15179}
15180
15181impl CollaborationHub for Entity<Project> {
15182    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15183        self.read(cx).collaborators()
15184    }
15185
15186    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15187        self.read(cx).user_store().read(cx).participant_indices()
15188    }
15189
15190    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15191        let this = self.read(cx);
15192        let user_ids = this.collaborators().values().map(|c| c.user_id);
15193        this.user_store().read_with(cx, |user_store, cx| {
15194            user_store.participant_names(user_ids, cx)
15195        })
15196    }
15197}
15198
15199pub trait SemanticsProvider {
15200    fn hover(
15201        &self,
15202        buffer: &Entity<Buffer>,
15203        position: text::Anchor,
15204        cx: &mut App,
15205    ) -> Option<Task<Vec<project::Hover>>>;
15206
15207    fn inlay_hints(
15208        &self,
15209        buffer_handle: Entity<Buffer>,
15210        range: Range<text::Anchor>,
15211        cx: &mut App,
15212    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15213
15214    fn resolve_inlay_hint(
15215        &self,
15216        hint: InlayHint,
15217        buffer_handle: Entity<Buffer>,
15218        server_id: LanguageServerId,
15219        cx: &mut App,
15220    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15221
15222    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15223
15224    fn document_highlights(
15225        &self,
15226        buffer: &Entity<Buffer>,
15227        position: text::Anchor,
15228        cx: &mut App,
15229    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15230
15231    fn definitions(
15232        &self,
15233        buffer: &Entity<Buffer>,
15234        position: text::Anchor,
15235        kind: GotoDefinitionKind,
15236        cx: &mut App,
15237    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15238
15239    fn range_for_rename(
15240        &self,
15241        buffer: &Entity<Buffer>,
15242        position: text::Anchor,
15243        cx: &mut App,
15244    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15245
15246    fn perform_rename(
15247        &self,
15248        buffer: &Entity<Buffer>,
15249        position: text::Anchor,
15250        new_name: String,
15251        cx: &mut App,
15252    ) -> Option<Task<Result<ProjectTransaction>>>;
15253}
15254
15255pub trait CompletionProvider {
15256    fn completions(
15257        &self,
15258        buffer: &Entity<Buffer>,
15259        buffer_position: text::Anchor,
15260        trigger: CompletionContext,
15261        window: &mut Window,
15262        cx: &mut Context<Editor>,
15263    ) -> Task<Result<Vec<Completion>>>;
15264
15265    fn resolve_completions(
15266        &self,
15267        buffer: Entity<Buffer>,
15268        completion_indices: Vec<usize>,
15269        completions: Rc<RefCell<Box<[Completion]>>>,
15270        cx: &mut Context<Editor>,
15271    ) -> Task<Result<bool>>;
15272
15273    fn apply_additional_edits_for_completion(
15274        &self,
15275        _buffer: Entity<Buffer>,
15276        _completions: Rc<RefCell<Box<[Completion]>>>,
15277        _completion_index: usize,
15278        _push_to_history: bool,
15279        _cx: &mut Context<Editor>,
15280    ) -> Task<Result<Option<language::Transaction>>> {
15281        Task::ready(Ok(None))
15282    }
15283
15284    fn is_completion_trigger(
15285        &self,
15286        buffer: &Entity<Buffer>,
15287        position: language::Anchor,
15288        text: &str,
15289        trigger_in_words: bool,
15290        cx: &mut Context<Editor>,
15291    ) -> bool;
15292
15293    fn sort_completions(&self) -> bool {
15294        true
15295    }
15296}
15297
15298pub trait CodeActionProvider {
15299    fn id(&self) -> Arc<str>;
15300
15301    fn code_actions(
15302        &self,
15303        buffer: &Entity<Buffer>,
15304        range: Range<text::Anchor>,
15305        window: &mut Window,
15306        cx: &mut App,
15307    ) -> Task<Result<Vec<CodeAction>>>;
15308
15309    fn apply_code_action(
15310        &self,
15311        buffer_handle: Entity<Buffer>,
15312        action: CodeAction,
15313        excerpt_id: ExcerptId,
15314        push_to_history: bool,
15315        window: &mut Window,
15316        cx: &mut App,
15317    ) -> Task<Result<ProjectTransaction>>;
15318}
15319
15320impl CodeActionProvider for Entity<Project> {
15321    fn id(&self) -> Arc<str> {
15322        "project".into()
15323    }
15324
15325    fn code_actions(
15326        &self,
15327        buffer: &Entity<Buffer>,
15328        range: Range<text::Anchor>,
15329        _window: &mut Window,
15330        cx: &mut App,
15331    ) -> Task<Result<Vec<CodeAction>>> {
15332        self.update(cx, |project, cx| {
15333            project.code_actions(buffer, range, None, cx)
15334        })
15335    }
15336
15337    fn apply_code_action(
15338        &self,
15339        buffer_handle: Entity<Buffer>,
15340        action: CodeAction,
15341        _excerpt_id: ExcerptId,
15342        push_to_history: bool,
15343        _window: &mut Window,
15344        cx: &mut App,
15345    ) -> Task<Result<ProjectTransaction>> {
15346        self.update(cx, |project, cx| {
15347            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15348        })
15349    }
15350}
15351
15352fn snippet_completions(
15353    project: &Project,
15354    buffer: &Entity<Buffer>,
15355    buffer_position: text::Anchor,
15356    cx: &mut App,
15357) -> Task<Result<Vec<Completion>>> {
15358    let language = buffer.read(cx).language_at(buffer_position);
15359    let language_name = language.as_ref().map(|language| language.lsp_id());
15360    let snippet_store = project.snippets().read(cx);
15361    let snippets = snippet_store.snippets_for(language_name, cx);
15362
15363    if snippets.is_empty() {
15364        return Task::ready(Ok(vec![]));
15365    }
15366    let snapshot = buffer.read(cx).text_snapshot();
15367    let chars: String = snapshot
15368        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15369        .collect();
15370
15371    let scope = language.map(|language| language.default_scope());
15372    let executor = cx.background_executor().clone();
15373
15374    cx.background_executor().spawn(async move {
15375        let classifier = CharClassifier::new(scope).for_completion(true);
15376        let mut last_word = chars
15377            .chars()
15378            .take_while(|c| classifier.is_word(*c))
15379            .collect::<String>();
15380        last_word = last_word.chars().rev().collect();
15381
15382        if last_word.is_empty() {
15383            return Ok(vec![]);
15384        }
15385
15386        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15387        let to_lsp = |point: &text::Anchor| {
15388            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15389            point_to_lsp(end)
15390        };
15391        let lsp_end = to_lsp(&buffer_position);
15392
15393        let candidates = snippets
15394            .iter()
15395            .enumerate()
15396            .flat_map(|(ix, snippet)| {
15397                snippet
15398                    .prefix
15399                    .iter()
15400                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15401            })
15402            .collect::<Vec<StringMatchCandidate>>();
15403
15404        let mut matches = fuzzy::match_strings(
15405            &candidates,
15406            &last_word,
15407            last_word.chars().any(|c| c.is_uppercase()),
15408            100,
15409            &Default::default(),
15410            executor,
15411        )
15412        .await;
15413
15414        // Remove all candidates where the query's start does not match the start of any word in the candidate
15415        if let Some(query_start) = last_word.chars().next() {
15416            matches.retain(|string_match| {
15417                split_words(&string_match.string).any(|word| {
15418                    // Check that the first codepoint of the word as lowercase matches the first
15419                    // codepoint of the query as lowercase
15420                    word.chars()
15421                        .flat_map(|codepoint| codepoint.to_lowercase())
15422                        .zip(query_start.to_lowercase())
15423                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15424                })
15425            });
15426        }
15427
15428        let matched_strings = matches
15429            .into_iter()
15430            .map(|m| m.string)
15431            .collect::<HashSet<_>>();
15432
15433        let result: Vec<Completion> = snippets
15434            .into_iter()
15435            .filter_map(|snippet| {
15436                let matching_prefix = snippet
15437                    .prefix
15438                    .iter()
15439                    .find(|prefix| matched_strings.contains(*prefix))?;
15440                let start = as_offset - last_word.len();
15441                let start = snapshot.anchor_before(start);
15442                let range = start..buffer_position;
15443                let lsp_start = to_lsp(&start);
15444                let lsp_range = lsp::Range {
15445                    start: lsp_start,
15446                    end: lsp_end,
15447                };
15448                Some(Completion {
15449                    old_range: range,
15450                    new_text: snippet.body.clone(),
15451                    resolved: false,
15452                    label: CodeLabel {
15453                        text: matching_prefix.clone(),
15454                        runs: vec![],
15455                        filter_range: 0..matching_prefix.len(),
15456                    },
15457                    server_id: LanguageServerId(usize::MAX),
15458                    documentation: snippet
15459                        .description
15460                        .clone()
15461                        .map(CompletionDocumentation::SingleLine),
15462                    lsp_completion: lsp::CompletionItem {
15463                        label: snippet.prefix.first().unwrap().clone(),
15464                        kind: Some(CompletionItemKind::SNIPPET),
15465                        label_details: snippet.description.as_ref().map(|description| {
15466                            lsp::CompletionItemLabelDetails {
15467                                detail: Some(description.clone()),
15468                                description: None,
15469                            }
15470                        }),
15471                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15472                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15473                            lsp::InsertReplaceEdit {
15474                                new_text: snippet.body.clone(),
15475                                insert: lsp_range,
15476                                replace: lsp_range,
15477                            },
15478                        )),
15479                        filter_text: Some(snippet.body.clone()),
15480                        sort_text: Some(char::MAX.to_string()),
15481                        ..Default::default()
15482                    },
15483                    confirm: None,
15484                })
15485            })
15486            .collect();
15487
15488        Ok(result)
15489    })
15490}
15491
15492impl CompletionProvider for Entity<Project> {
15493    fn completions(
15494        &self,
15495        buffer: &Entity<Buffer>,
15496        buffer_position: text::Anchor,
15497        options: CompletionContext,
15498        _window: &mut Window,
15499        cx: &mut Context<Editor>,
15500    ) -> Task<Result<Vec<Completion>>> {
15501        self.update(cx, |project, cx| {
15502            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15503            let project_completions = project.completions(buffer, buffer_position, options, cx);
15504            cx.background_executor().spawn(async move {
15505                let mut completions = project_completions.await?;
15506                let snippets_completions = snippets.await?;
15507                completions.extend(snippets_completions);
15508                Ok(completions)
15509            })
15510        })
15511    }
15512
15513    fn resolve_completions(
15514        &self,
15515        buffer: Entity<Buffer>,
15516        completion_indices: Vec<usize>,
15517        completions: Rc<RefCell<Box<[Completion]>>>,
15518        cx: &mut Context<Editor>,
15519    ) -> Task<Result<bool>> {
15520        self.update(cx, |project, cx| {
15521            project.lsp_store().update(cx, |lsp_store, cx| {
15522                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15523            })
15524        })
15525    }
15526
15527    fn apply_additional_edits_for_completion(
15528        &self,
15529        buffer: Entity<Buffer>,
15530        completions: Rc<RefCell<Box<[Completion]>>>,
15531        completion_index: usize,
15532        push_to_history: bool,
15533        cx: &mut Context<Editor>,
15534    ) -> Task<Result<Option<language::Transaction>>> {
15535        self.update(cx, |project, cx| {
15536            project.lsp_store().update(cx, |lsp_store, cx| {
15537                lsp_store.apply_additional_edits_for_completion(
15538                    buffer,
15539                    completions,
15540                    completion_index,
15541                    push_to_history,
15542                    cx,
15543                )
15544            })
15545        })
15546    }
15547
15548    fn is_completion_trigger(
15549        &self,
15550        buffer: &Entity<Buffer>,
15551        position: language::Anchor,
15552        text: &str,
15553        trigger_in_words: bool,
15554        cx: &mut Context<Editor>,
15555    ) -> bool {
15556        let mut chars = text.chars();
15557        let char = if let Some(char) = chars.next() {
15558            char
15559        } else {
15560            return false;
15561        };
15562        if chars.next().is_some() {
15563            return false;
15564        }
15565
15566        let buffer = buffer.read(cx);
15567        let snapshot = buffer.snapshot();
15568        if !snapshot.settings_at(position, cx).show_completions_on_input {
15569            return false;
15570        }
15571        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15572        if trigger_in_words && classifier.is_word(char) {
15573            return true;
15574        }
15575
15576        buffer.completion_triggers().contains(text)
15577    }
15578}
15579
15580impl SemanticsProvider for Entity<Project> {
15581    fn hover(
15582        &self,
15583        buffer: &Entity<Buffer>,
15584        position: text::Anchor,
15585        cx: &mut App,
15586    ) -> Option<Task<Vec<project::Hover>>> {
15587        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15588    }
15589
15590    fn document_highlights(
15591        &self,
15592        buffer: &Entity<Buffer>,
15593        position: text::Anchor,
15594        cx: &mut App,
15595    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15596        Some(self.update(cx, |project, cx| {
15597            project.document_highlights(buffer, position, cx)
15598        }))
15599    }
15600
15601    fn definitions(
15602        &self,
15603        buffer: &Entity<Buffer>,
15604        position: text::Anchor,
15605        kind: GotoDefinitionKind,
15606        cx: &mut App,
15607    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15608        Some(self.update(cx, |project, cx| match kind {
15609            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15610            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15611            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15612            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15613        }))
15614    }
15615
15616    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15617        // TODO: make this work for remote projects
15618        self.read(cx)
15619            .language_servers_for_local_buffer(buffer.read(cx), cx)
15620            .any(
15621                |(_, server)| match server.capabilities().inlay_hint_provider {
15622                    Some(lsp::OneOf::Left(enabled)) => enabled,
15623                    Some(lsp::OneOf::Right(_)) => true,
15624                    None => false,
15625                },
15626            )
15627    }
15628
15629    fn inlay_hints(
15630        &self,
15631        buffer_handle: Entity<Buffer>,
15632        range: Range<text::Anchor>,
15633        cx: &mut App,
15634    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15635        Some(self.update(cx, |project, cx| {
15636            project.inlay_hints(buffer_handle, range, cx)
15637        }))
15638    }
15639
15640    fn resolve_inlay_hint(
15641        &self,
15642        hint: InlayHint,
15643        buffer_handle: Entity<Buffer>,
15644        server_id: LanguageServerId,
15645        cx: &mut App,
15646    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15647        Some(self.update(cx, |project, cx| {
15648            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15649        }))
15650    }
15651
15652    fn range_for_rename(
15653        &self,
15654        buffer: &Entity<Buffer>,
15655        position: text::Anchor,
15656        cx: &mut App,
15657    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15658        Some(self.update(cx, |project, cx| {
15659            let buffer = buffer.clone();
15660            let task = project.prepare_rename(buffer.clone(), position, cx);
15661            cx.spawn(|_, mut cx| async move {
15662                Ok(match task.await? {
15663                    PrepareRenameResponse::Success(range) => Some(range),
15664                    PrepareRenameResponse::InvalidPosition => None,
15665                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15666                        // Fallback on using TreeSitter info to determine identifier range
15667                        buffer.update(&mut cx, |buffer, _| {
15668                            let snapshot = buffer.snapshot();
15669                            let (range, kind) = snapshot.surrounding_word(position);
15670                            if kind != Some(CharKind::Word) {
15671                                return None;
15672                            }
15673                            Some(
15674                                snapshot.anchor_before(range.start)
15675                                    ..snapshot.anchor_after(range.end),
15676                            )
15677                        })?
15678                    }
15679                })
15680            })
15681        }))
15682    }
15683
15684    fn perform_rename(
15685        &self,
15686        buffer: &Entity<Buffer>,
15687        position: text::Anchor,
15688        new_name: String,
15689        cx: &mut App,
15690    ) -> Option<Task<Result<ProjectTransaction>>> {
15691        Some(self.update(cx, |project, cx| {
15692            project.perform_rename(buffer.clone(), position, new_name, cx)
15693        }))
15694    }
15695}
15696
15697fn inlay_hint_settings(
15698    location: Anchor,
15699    snapshot: &MultiBufferSnapshot,
15700    cx: &mut Context<Editor>,
15701) -> InlayHintSettings {
15702    let file = snapshot.file_at(location);
15703    let language = snapshot.language_at(location).map(|l| l.name());
15704    language_settings(language, file, cx).inlay_hints
15705}
15706
15707fn consume_contiguous_rows(
15708    contiguous_row_selections: &mut Vec<Selection<Point>>,
15709    selection: &Selection<Point>,
15710    display_map: &DisplaySnapshot,
15711    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15712) -> (MultiBufferRow, MultiBufferRow) {
15713    contiguous_row_selections.push(selection.clone());
15714    let start_row = MultiBufferRow(selection.start.row);
15715    let mut end_row = ending_row(selection, display_map);
15716
15717    while let Some(next_selection) = selections.peek() {
15718        if next_selection.start.row <= end_row.0 {
15719            end_row = ending_row(next_selection, display_map);
15720            contiguous_row_selections.push(selections.next().unwrap().clone());
15721        } else {
15722            break;
15723        }
15724    }
15725    (start_row, end_row)
15726}
15727
15728fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15729    if next_selection.end.column > 0 || next_selection.is_empty() {
15730        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15731    } else {
15732        MultiBufferRow(next_selection.end.row)
15733    }
15734}
15735
15736impl EditorSnapshot {
15737    pub fn remote_selections_in_range<'a>(
15738        &'a self,
15739        range: &'a Range<Anchor>,
15740        collaboration_hub: &dyn CollaborationHub,
15741        cx: &'a App,
15742    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15743        let participant_names = collaboration_hub.user_names(cx);
15744        let participant_indices = collaboration_hub.user_participant_indices(cx);
15745        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15746        let collaborators_by_replica_id = collaborators_by_peer_id
15747            .iter()
15748            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15749            .collect::<HashMap<_, _>>();
15750        self.buffer_snapshot
15751            .selections_in_range(range, false)
15752            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15753                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15754                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15755                let user_name = participant_names.get(&collaborator.user_id).cloned();
15756                Some(RemoteSelection {
15757                    replica_id,
15758                    selection,
15759                    cursor_shape,
15760                    line_mode,
15761                    participant_index,
15762                    peer_id: collaborator.peer_id,
15763                    user_name,
15764                })
15765            })
15766    }
15767
15768    pub fn hunks_for_ranges(
15769        &self,
15770        ranges: impl Iterator<Item = Range<Point>>,
15771    ) -> Vec<MultiBufferDiffHunk> {
15772        let mut hunks = Vec::new();
15773        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15774            HashMap::default();
15775        for query_range in ranges {
15776            let query_rows =
15777                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15778            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15779                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15780            ) {
15781                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15782                // when the caret is just above or just below the deleted hunk.
15783                let allow_adjacent = hunk.status().is_removed();
15784                let related_to_selection = if allow_adjacent {
15785                    hunk.row_range.overlaps(&query_rows)
15786                        || hunk.row_range.start == query_rows.end
15787                        || hunk.row_range.end == query_rows.start
15788                } else {
15789                    hunk.row_range.overlaps(&query_rows)
15790                };
15791                if related_to_selection {
15792                    if !processed_buffer_rows
15793                        .entry(hunk.buffer_id)
15794                        .or_default()
15795                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15796                    {
15797                        continue;
15798                    }
15799                    hunks.push(hunk);
15800                }
15801            }
15802        }
15803
15804        hunks
15805    }
15806
15807    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15808        self.display_snapshot.buffer_snapshot.language_at(position)
15809    }
15810
15811    pub fn is_focused(&self) -> bool {
15812        self.is_focused
15813    }
15814
15815    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15816        self.placeholder_text.as_ref()
15817    }
15818
15819    pub fn scroll_position(&self) -> gpui::Point<f32> {
15820        self.scroll_anchor.scroll_position(&self.display_snapshot)
15821    }
15822
15823    fn gutter_dimensions(
15824        &self,
15825        font_id: FontId,
15826        font_size: Pixels,
15827        max_line_number_width: Pixels,
15828        cx: &App,
15829    ) -> Option<GutterDimensions> {
15830        if !self.show_gutter {
15831            return None;
15832        }
15833
15834        let descent = cx.text_system().descent(font_id, font_size);
15835        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15836        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15837
15838        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15839            matches!(
15840                ProjectSettings::get_global(cx).git.git_gutter,
15841                Some(GitGutterSetting::TrackedFiles)
15842            )
15843        });
15844        let gutter_settings = EditorSettings::get_global(cx).gutter;
15845        let show_line_numbers = self
15846            .show_line_numbers
15847            .unwrap_or(gutter_settings.line_numbers);
15848        let line_gutter_width = if show_line_numbers {
15849            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15850            let min_width_for_number_on_gutter = em_advance * 4.0;
15851            max_line_number_width.max(min_width_for_number_on_gutter)
15852        } else {
15853            0.0.into()
15854        };
15855
15856        let show_code_actions = self
15857            .show_code_actions
15858            .unwrap_or(gutter_settings.code_actions);
15859
15860        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15861
15862        let git_blame_entries_width =
15863            self.git_blame_gutter_max_author_length
15864                .map(|max_author_length| {
15865                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15866
15867                    /// The number of characters to dedicate to gaps and margins.
15868                    const SPACING_WIDTH: usize = 4;
15869
15870                    let max_char_count = max_author_length
15871                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15872                        + ::git::SHORT_SHA_LENGTH
15873                        + MAX_RELATIVE_TIMESTAMP.len()
15874                        + SPACING_WIDTH;
15875
15876                    em_advance * max_char_count
15877                });
15878
15879        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15880        left_padding += if show_code_actions || show_runnables {
15881            em_width * 3.0
15882        } else if show_git_gutter && show_line_numbers {
15883            em_width * 2.0
15884        } else if show_git_gutter || show_line_numbers {
15885            em_width
15886        } else {
15887            px(0.)
15888        };
15889
15890        let right_padding = if gutter_settings.folds && show_line_numbers {
15891            em_width * 4.0
15892        } else if gutter_settings.folds {
15893            em_width * 3.0
15894        } else if show_line_numbers {
15895            em_width
15896        } else {
15897            px(0.)
15898        };
15899
15900        Some(GutterDimensions {
15901            left_padding,
15902            right_padding,
15903            width: line_gutter_width + left_padding + right_padding,
15904            margin: -descent,
15905            git_blame_entries_width,
15906        })
15907    }
15908
15909    pub fn render_crease_toggle(
15910        &self,
15911        buffer_row: MultiBufferRow,
15912        row_contains_cursor: bool,
15913        editor: Entity<Editor>,
15914        window: &mut Window,
15915        cx: &mut App,
15916    ) -> Option<AnyElement> {
15917        let folded = self.is_line_folded(buffer_row);
15918        let mut is_foldable = false;
15919
15920        if let Some(crease) = self
15921            .crease_snapshot
15922            .query_row(buffer_row, &self.buffer_snapshot)
15923        {
15924            is_foldable = true;
15925            match crease {
15926                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15927                    if let Some(render_toggle) = render_toggle {
15928                        let toggle_callback =
15929                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15930                                if folded {
15931                                    editor.update(cx, |editor, cx| {
15932                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15933                                    });
15934                                } else {
15935                                    editor.update(cx, |editor, cx| {
15936                                        editor.unfold_at(
15937                                            &crate::UnfoldAt { buffer_row },
15938                                            window,
15939                                            cx,
15940                                        )
15941                                    });
15942                                }
15943                            });
15944                        return Some((render_toggle)(
15945                            buffer_row,
15946                            folded,
15947                            toggle_callback,
15948                            window,
15949                            cx,
15950                        ));
15951                    }
15952                }
15953            }
15954        }
15955
15956        is_foldable |= self.starts_indent(buffer_row);
15957
15958        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15959            Some(
15960                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15961                    .toggle_state(folded)
15962                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15963                        if folded {
15964                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15965                        } else {
15966                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15967                        }
15968                    }))
15969                    .into_any_element(),
15970            )
15971        } else {
15972            None
15973        }
15974    }
15975
15976    pub fn render_crease_trailer(
15977        &self,
15978        buffer_row: MultiBufferRow,
15979        window: &mut Window,
15980        cx: &mut App,
15981    ) -> Option<AnyElement> {
15982        let folded = self.is_line_folded(buffer_row);
15983        if let Crease::Inline { render_trailer, .. } = self
15984            .crease_snapshot
15985            .query_row(buffer_row, &self.buffer_snapshot)?
15986        {
15987            let render_trailer = render_trailer.as_ref()?;
15988            Some(render_trailer(buffer_row, folded, window, cx))
15989        } else {
15990            None
15991        }
15992    }
15993}
15994
15995impl Deref for EditorSnapshot {
15996    type Target = DisplaySnapshot;
15997
15998    fn deref(&self) -> &Self::Target {
15999        &self.display_snapshot
16000    }
16001}
16002
16003#[derive(Clone, Debug, PartialEq, Eq)]
16004pub enum EditorEvent {
16005    InputIgnored {
16006        text: Arc<str>,
16007    },
16008    InputHandled {
16009        utf16_range_to_replace: Option<Range<isize>>,
16010        text: Arc<str>,
16011    },
16012    ExcerptsAdded {
16013        buffer: Entity<Buffer>,
16014        predecessor: ExcerptId,
16015        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16016    },
16017    ExcerptsRemoved {
16018        ids: Vec<ExcerptId>,
16019    },
16020    BufferFoldToggled {
16021        ids: Vec<ExcerptId>,
16022        folded: bool,
16023    },
16024    ExcerptsEdited {
16025        ids: Vec<ExcerptId>,
16026    },
16027    ExcerptsExpanded {
16028        ids: Vec<ExcerptId>,
16029    },
16030    BufferEdited,
16031    Edited {
16032        transaction_id: clock::Lamport,
16033    },
16034    Reparsed(BufferId),
16035    Focused,
16036    FocusedIn,
16037    Blurred,
16038    DirtyChanged,
16039    Saved,
16040    TitleChanged,
16041    DiffBaseChanged,
16042    SelectionsChanged {
16043        local: bool,
16044    },
16045    ScrollPositionChanged {
16046        local: bool,
16047        autoscroll: bool,
16048    },
16049    Closed,
16050    TransactionUndone {
16051        transaction_id: clock::Lamport,
16052    },
16053    TransactionBegun {
16054        transaction_id: clock::Lamport,
16055    },
16056    Reloaded,
16057    CursorShapeChanged,
16058}
16059
16060impl EventEmitter<EditorEvent> for Editor {}
16061
16062impl Focusable for Editor {
16063    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16064        self.focus_handle.clone()
16065    }
16066}
16067
16068impl Render for Editor {
16069    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16070        let settings = ThemeSettings::get_global(cx);
16071
16072        let mut text_style = match self.mode {
16073            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16074                color: cx.theme().colors().editor_foreground,
16075                font_family: settings.ui_font.family.clone(),
16076                font_features: settings.ui_font.features.clone(),
16077                font_fallbacks: settings.ui_font.fallbacks.clone(),
16078                font_size: rems(0.875).into(),
16079                font_weight: settings.ui_font.weight,
16080                line_height: relative(settings.buffer_line_height.value()),
16081                ..Default::default()
16082            },
16083            EditorMode::Full => TextStyle {
16084                color: cx.theme().colors().editor_foreground,
16085                font_family: settings.buffer_font.family.clone(),
16086                font_features: settings.buffer_font.features.clone(),
16087                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16088                font_size: settings.buffer_font_size().into(),
16089                font_weight: settings.buffer_font.weight,
16090                line_height: relative(settings.buffer_line_height.value()),
16091                ..Default::default()
16092            },
16093        };
16094        if let Some(text_style_refinement) = &self.text_style_refinement {
16095            text_style.refine(text_style_refinement)
16096        }
16097
16098        let background = match self.mode {
16099            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16100            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16101            EditorMode::Full => cx.theme().colors().editor_background,
16102        };
16103
16104        EditorElement::new(
16105            &cx.entity(),
16106            EditorStyle {
16107                background,
16108                local_player: cx.theme().players().local(),
16109                text: text_style,
16110                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16111                syntax: cx.theme().syntax().clone(),
16112                status: cx.theme().status().clone(),
16113                inlay_hints_style: make_inlay_hints_style(cx),
16114                inline_completion_styles: make_suggestion_styles(cx),
16115                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16116            },
16117        )
16118    }
16119}
16120
16121impl EntityInputHandler for Editor {
16122    fn text_for_range(
16123        &mut self,
16124        range_utf16: Range<usize>,
16125        adjusted_range: &mut Option<Range<usize>>,
16126        _: &mut Window,
16127        cx: &mut Context<Self>,
16128    ) -> Option<String> {
16129        let snapshot = self.buffer.read(cx).read(cx);
16130        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16131        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16132        if (start.0..end.0) != range_utf16 {
16133            adjusted_range.replace(start.0..end.0);
16134        }
16135        Some(snapshot.text_for_range(start..end).collect())
16136    }
16137
16138    fn selected_text_range(
16139        &mut self,
16140        ignore_disabled_input: bool,
16141        _: &mut Window,
16142        cx: &mut Context<Self>,
16143    ) -> Option<UTF16Selection> {
16144        // Prevent the IME menu from appearing when holding down an alphabetic key
16145        // while input is disabled.
16146        if !ignore_disabled_input && !self.input_enabled {
16147            return None;
16148        }
16149
16150        let selection = self.selections.newest::<OffsetUtf16>(cx);
16151        let range = selection.range();
16152
16153        Some(UTF16Selection {
16154            range: range.start.0..range.end.0,
16155            reversed: selection.reversed,
16156        })
16157    }
16158
16159    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16160        let snapshot = self.buffer.read(cx).read(cx);
16161        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16162        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16163    }
16164
16165    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16166        self.clear_highlights::<InputComposition>(cx);
16167        self.ime_transaction.take();
16168    }
16169
16170    fn replace_text_in_range(
16171        &mut self,
16172        range_utf16: Option<Range<usize>>,
16173        text: &str,
16174        window: &mut Window,
16175        cx: &mut Context<Self>,
16176    ) {
16177        if !self.input_enabled {
16178            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16179            return;
16180        }
16181
16182        self.transact(window, cx, |this, window, cx| {
16183            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16184                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16185                Some(this.selection_replacement_ranges(range_utf16, cx))
16186            } else {
16187                this.marked_text_ranges(cx)
16188            };
16189
16190            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16191                let newest_selection_id = this.selections.newest_anchor().id;
16192                this.selections
16193                    .all::<OffsetUtf16>(cx)
16194                    .iter()
16195                    .zip(ranges_to_replace.iter())
16196                    .find_map(|(selection, range)| {
16197                        if selection.id == newest_selection_id {
16198                            Some(
16199                                (range.start.0 as isize - selection.head().0 as isize)
16200                                    ..(range.end.0 as isize - selection.head().0 as isize),
16201                            )
16202                        } else {
16203                            None
16204                        }
16205                    })
16206            });
16207
16208            cx.emit(EditorEvent::InputHandled {
16209                utf16_range_to_replace: range_to_replace,
16210                text: text.into(),
16211            });
16212
16213            if let Some(new_selected_ranges) = new_selected_ranges {
16214                this.change_selections(None, window, cx, |selections| {
16215                    selections.select_ranges(new_selected_ranges)
16216                });
16217                this.backspace(&Default::default(), window, cx);
16218            }
16219
16220            this.handle_input(text, window, cx);
16221        });
16222
16223        if let Some(transaction) = self.ime_transaction {
16224            self.buffer.update(cx, |buffer, cx| {
16225                buffer.group_until_transaction(transaction, cx);
16226            });
16227        }
16228
16229        self.unmark_text(window, cx);
16230    }
16231
16232    fn replace_and_mark_text_in_range(
16233        &mut self,
16234        range_utf16: Option<Range<usize>>,
16235        text: &str,
16236        new_selected_range_utf16: Option<Range<usize>>,
16237        window: &mut Window,
16238        cx: &mut Context<Self>,
16239    ) {
16240        if !self.input_enabled {
16241            return;
16242        }
16243
16244        let transaction = self.transact(window, cx, |this, window, cx| {
16245            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16246                let snapshot = this.buffer.read(cx).read(cx);
16247                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16248                    for marked_range in &mut marked_ranges {
16249                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16250                        marked_range.start.0 += relative_range_utf16.start;
16251                        marked_range.start =
16252                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16253                        marked_range.end =
16254                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16255                    }
16256                }
16257                Some(marked_ranges)
16258            } else if let Some(range_utf16) = range_utf16 {
16259                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16260                Some(this.selection_replacement_ranges(range_utf16, cx))
16261            } else {
16262                None
16263            };
16264
16265            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16266                let newest_selection_id = this.selections.newest_anchor().id;
16267                this.selections
16268                    .all::<OffsetUtf16>(cx)
16269                    .iter()
16270                    .zip(ranges_to_replace.iter())
16271                    .find_map(|(selection, range)| {
16272                        if selection.id == newest_selection_id {
16273                            Some(
16274                                (range.start.0 as isize - selection.head().0 as isize)
16275                                    ..(range.end.0 as isize - selection.head().0 as isize),
16276                            )
16277                        } else {
16278                            None
16279                        }
16280                    })
16281            });
16282
16283            cx.emit(EditorEvent::InputHandled {
16284                utf16_range_to_replace: range_to_replace,
16285                text: text.into(),
16286            });
16287
16288            if let Some(ranges) = ranges_to_replace {
16289                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16290            }
16291
16292            let marked_ranges = {
16293                let snapshot = this.buffer.read(cx).read(cx);
16294                this.selections
16295                    .disjoint_anchors()
16296                    .iter()
16297                    .map(|selection| {
16298                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16299                    })
16300                    .collect::<Vec<_>>()
16301            };
16302
16303            if text.is_empty() {
16304                this.unmark_text(window, cx);
16305            } else {
16306                this.highlight_text::<InputComposition>(
16307                    marked_ranges.clone(),
16308                    HighlightStyle {
16309                        underline: Some(UnderlineStyle {
16310                            thickness: px(1.),
16311                            color: None,
16312                            wavy: false,
16313                        }),
16314                        ..Default::default()
16315                    },
16316                    cx,
16317                );
16318            }
16319
16320            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16321            let use_autoclose = this.use_autoclose;
16322            let use_auto_surround = this.use_auto_surround;
16323            this.set_use_autoclose(false);
16324            this.set_use_auto_surround(false);
16325            this.handle_input(text, window, cx);
16326            this.set_use_autoclose(use_autoclose);
16327            this.set_use_auto_surround(use_auto_surround);
16328
16329            if let Some(new_selected_range) = new_selected_range_utf16 {
16330                let snapshot = this.buffer.read(cx).read(cx);
16331                let new_selected_ranges = marked_ranges
16332                    .into_iter()
16333                    .map(|marked_range| {
16334                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16335                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16336                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16337                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16338                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16339                    })
16340                    .collect::<Vec<_>>();
16341
16342                drop(snapshot);
16343                this.change_selections(None, window, cx, |selections| {
16344                    selections.select_ranges(new_selected_ranges)
16345                });
16346            }
16347        });
16348
16349        self.ime_transaction = self.ime_transaction.or(transaction);
16350        if let Some(transaction) = self.ime_transaction {
16351            self.buffer.update(cx, |buffer, cx| {
16352                buffer.group_until_transaction(transaction, cx);
16353            });
16354        }
16355
16356        if self.text_highlights::<InputComposition>(cx).is_none() {
16357            self.ime_transaction.take();
16358        }
16359    }
16360
16361    fn bounds_for_range(
16362        &mut self,
16363        range_utf16: Range<usize>,
16364        element_bounds: gpui::Bounds<Pixels>,
16365        window: &mut Window,
16366        cx: &mut Context<Self>,
16367    ) -> Option<gpui::Bounds<Pixels>> {
16368        let text_layout_details = self.text_layout_details(window);
16369        let gpui::Size {
16370            width: em_width,
16371            height: line_height,
16372        } = self.character_size(window);
16373
16374        let snapshot = self.snapshot(window, cx);
16375        let scroll_position = snapshot.scroll_position();
16376        let scroll_left = scroll_position.x * em_width;
16377
16378        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16379        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16380            + self.gutter_dimensions.width
16381            + self.gutter_dimensions.margin;
16382        let y = line_height * (start.row().as_f32() - scroll_position.y);
16383
16384        Some(Bounds {
16385            origin: element_bounds.origin + point(x, y),
16386            size: size(em_width, line_height),
16387        })
16388    }
16389
16390    fn character_index_for_point(
16391        &mut self,
16392        point: gpui::Point<Pixels>,
16393        _window: &mut Window,
16394        _cx: &mut Context<Self>,
16395    ) -> Option<usize> {
16396        let position_map = self.last_position_map.as_ref()?;
16397        if !position_map.text_hitbox.contains(&point) {
16398            return None;
16399        }
16400        let display_point = position_map.point_for_position(point).previous_valid;
16401        let anchor = position_map
16402            .snapshot
16403            .display_point_to_anchor(display_point, Bias::Left);
16404        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16405        Some(utf16_offset.0)
16406    }
16407}
16408
16409trait SelectionExt {
16410    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16411    fn spanned_rows(
16412        &self,
16413        include_end_if_at_line_start: bool,
16414        map: &DisplaySnapshot,
16415    ) -> Range<MultiBufferRow>;
16416}
16417
16418impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16419    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16420        let start = self
16421            .start
16422            .to_point(&map.buffer_snapshot)
16423            .to_display_point(map);
16424        let end = self
16425            .end
16426            .to_point(&map.buffer_snapshot)
16427            .to_display_point(map);
16428        if self.reversed {
16429            end..start
16430        } else {
16431            start..end
16432        }
16433    }
16434
16435    fn spanned_rows(
16436        &self,
16437        include_end_if_at_line_start: bool,
16438        map: &DisplaySnapshot,
16439    ) -> Range<MultiBufferRow> {
16440        let start = self.start.to_point(&map.buffer_snapshot);
16441        let mut end = self.end.to_point(&map.buffer_snapshot);
16442        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16443            end.row -= 1;
16444        }
16445
16446        let buffer_start = map.prev_line_boundary(start).0;
16447        let buffer_end = map.next_line_boundary(end).0;
16448        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16449    }
16450}
16451
16452impl<T: InvalidationRegion> InvalidationStack<T> {
16453    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16454    where
16455        S: Clone + ToOffset,
16456    {
16457        while let Some(region) = self.last() {
16458            let all_selections_inside_invalidation_ranges =
16459                if selections.len() == region.ranges().len() {
16460                    selections
16461                        .iter()
16462                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16463                        .all(|(selection, invalidation_range)| {
16464                            let head = selection.head().to_offset(buffer);
16465                            invalidation_range.start <= head && invalidation_range.end >= head
16466                        })
16467                } else {
16468                    false
16469                };
16470
16471            if all_selections_inside_invalidation_ranges {
16472                break;
16473            } else {
16474                self.pop();
16475            }
16476        }
16477    }
16478}
16479
16480impl<T> Default for InvalidationStack<T> {
16481    fn default() -> Self {
16482        Self(Default::default())
16483    }
16484}
16485
16486impl<T> Deref for InvalidationStack<T> {
16487    type Target = Vec<T>;
16488
16489    fn deref(&self) -> &Self::Target {
16490        &self.0
16491    }
16492}
16493
16494impl<T> DerefMut for InvalidationStack<T> {
16495    fn deref_mut(&mut self) -> &mut Self::Target {
16496        &mut self.0
16497    }
16498}
16499
16500impl InvalidationRegion for SnippetState {
16501    fn ranges(&self) -> &[Range<Anchor>] {
16502        &self.ranges[self.active_index]
16503    }
16504}
16505
16506pub fn diagnostic_block_renderer(
16507    diagnostic: Diagnostic,
16508    max_message_rows: Option<u8>,
16509    allow_closing: bool,
16510    _is_valid: bool,
16511) -> RenderBlock {
16512    let (text_without_backticks, code_ranges) =
16513        highlight_diagnostic_message(&diagnostic, max_message_rows);
16514
16515    Arc::new(move |cx: &mut BlockContext| {
16516        let group_id: SharedString = cx.block_id.to_string().into();
16517
16518        let mut text_style = cx.window.text_style().clone();
16519        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16520        let theme_settings = ThemeSettings::get_global(cx);
16521        text_style.font_family = theme_settings.buffer_font.family.clone();
16522        text_style.font_style = theme_settings.buffer_font.style;
16523        text_style.font_features = theme_settings.buffer_font.features.clone();
16524        text_style.font_weight = theme_settings.buffer_font.weight;
16525
16526        let multi_line_diagnostic = diagnostic.message.contains('\n');
16527
16528        let buttons = |diagnostic: &Diagnostic| {
16529            if multi_line_diagnostic {
16530                v_flex()
16531            } else {
16532                h_flex()
16533            }
16534            .when(allow_closing, |div| {
16535                div.children(diagnostic.is_primary.then(|| {
16536                    IconButton::new("close-block", IconName::XCircle)
16537                        .icon_color(Color::Muted)
16538                        .size(ButtonSize::Compact)
16539                        .style(ButtonStyle::Transparent)
16540                        .visible_on_hover(group_id.clone())
16541                        .on_click(move |_click, window, cx| {
16542                            window.dispatch_action(Box::new(Cancel), cx)
16543                        })
16544                        .tooltip(|window, cx| {
16545                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16546                        })
16547                }))
16548            })
16549            .child(
16550                IconButton::new("copy-block", IconName::Copy)
16551                    .icon_color(Color::Muted)
16552                    .size(ButtonSize::Compact)
16553                    .style(ButtonStyle::Transparent)
16554                    .visible_on_hover(group_id.clone())
16555                    .on_click({
16556                        let message = diagnostic.message.clone();
16557                        move |_click, _, cx| {
16558                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16559                        }
16560                    })
16561                    .tooltip(Tooltip::text("Copy diagnostic message")),
16562            )
16563        };
16564
16565        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16566            AvailableSpace::min_size(),
16567            cx.window,
16568            cx.app,
16569        );
16570
16571        h_flex()
16572            .id(cx.block_id)
16573            .group(group_id.clone())
16574            .relative()
16575            .size_full()
16576            .block_mouse_down()
16577            .pl(cx.gutter_dimensions.width)
16578            .w(cx.max_width - cx.gutter_dimensions.full_width())
16579            .child(
16580                div()
16581                    .flex()
16582                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16583                    .flex_shrink(),
16584            )
16585            .child(buttons(&diagnostic))
16586            .child(div().flex().flex_shrink_0().child(
16587                StyledText::new(text_without_backticks.clone()).with_highlights(
16588                    &text_style,
16589                    code_ranges.iter().map(|range| {
16590                        (
16591                            range.clone(),
16592                            HighlightStyle {
16593                                font_weight: Some(FontWeight::BOLD),
16594                                ..Default::default()
16595                            },
16596                        )
16597                    }),
16598                ),
16599            ))
16600            .into_any_element()
16601    })
16602}
16603
16604fn inline_completion_edit_text(
16605    current_snapshot: &BufferSnapshot,
16606    edits: &[(Range<Anchor>, String)],
16607    edit_preview: &EditPreview,
16608    include_deletions: bool,
16609    cx: &App,
16610) -> HighlightedText {
16611    let edits = edits
16612        .iter()
16613        .map(|(anchor, text)| {
16614            (
16615                anchor.start.text_anchor..anchor.end.text_anchor,
16616                text.clone(),
16617            )
16618        })
16619        .collect::<Vec<_>>();
16620
16621    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16622}
16623
16624pub fn highlight_diagnostic_message(
16625    diagnostic: &Diagnostic,
16626    mut max_message_rows: Option<u8>,
16627) -> (SharedString, Vec<Range<usize>>) {
16628    let mut text_without_backticks = String::new();
16629    let mut code_ranges = Vec::new();
16630
16631    if let Some(source) = &diagnostic.source {
16632        text_without_backticks.push_str(source);
16633        code_ranges.push(0..source.len());
16634        text_without_backticks.push_str(": ");
16635    }
16636
16637    let mut prev_offset = 0;
16638    let mut in_code_block = false;
16639    let has_row_limit = max_message_rows.is_some();
16640    let mut newline_indices = diagnostic
16641        .message
16642        .match_indices('\n')
16643        .filter(|_| has_row_limit)
16644        .map(|(ix, _)| ix)
16645        .fuse()
16646        .peekable();
16647
16648    for (quote_ix, _) in diagnostic
16649        .message
16650        .match_indices('`')
16651        .chain([(diagnostic.message.len(), "")])
16652    {
16653        let mut first_newline_ix = None;
16654        let mut last_newline_ix = None;
16655        while let Some(newline_ix) = newline_indices.peek() {
16656            if *newline_ix < quote_ix {
16657                if first_newline_ix.is_none() {
16658                    first_newline_ix = Some(*newline_ix);
16659                }
16660                last_newline_ix = Some(*newline_ix);
16661
16662                if let Some(rows_left) = &mut max_message_rows {
16663                    if *rows_left == 0 {
16664                        break;
16665                    } else {
16666                        *rows_left -= 1;
16667                    }
16668                }
16669                let _ = newline_indices.next();
16670            } else {
16671                break;
16672            }
16673        }
16674        let prev_len = text_without_backticks.len();
16675        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16676        text_without_backticks.push_str(new_text);
16677        if in_code_block {
16678            code_ranges.push(prev_len..text_without_backticks.len());
16679        }
16680        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16681        in_code_block = !in_code_block;
16682        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16683            text_without_backticks.push_str("...");
16684            break;
16685        }
16686    }
16687
16688    (text_without_backticks.into(), code_ranges)
16689}
16690
16691fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16692    match severity {
16693        DiagnosticSeverity::ERROR => colors.error,
16694        DiagnosticSeverity::WARNING => colors.warning,
16695        DiagnosticSeverity::INFORMATION => colors.info,
16696        DiagnosticSeverity::HINT => colors.info,
16697        _ => colors.ignored,
16698    }
16699}
16700
16701pub fn styled_runs_for_code_label<'a>(
16702    label: &'a CodeLabel,
16703    syntax_theme: &'a theme::SyntaxTheme,
16704) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16705    let fade_out = HighlightStyle {
16706        fade_out: Some(0.35),
16707        ..Default::default()
16708    };
16709
16710    let mut prev_end = label.filter_range.end;
16711    label
16712        .runs
16713        .iter()
16714        .enumerate()
16715        .flat_map(move |(ix, (range, highlight_id))| {
16716            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16717                style
16718            } else {
16719                return Default::default();
16720            };
16721            let mut muted_style = style;
16722            muted_style.highlight(fade_out);
16723
16724            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16725            if range.start >= label.filter_range.end {
16726                if range.start > prev_end {
16727                    runs.push((prev_end..range.start, fade_out));
16728                }
16729                runs.push((range.clone(), muted_style));
16730            } else if range.end <= label.filter_range.end {
16731                runs.push((range.clone(), style));
16732            } else {
16733                runs.push((range.start..label.filter_range.end, style));
16734                runs.push((label.filter_range.end..range.end, muted_style));
16735            }
16736            prev_end = cmp::max(prev_end, range.end);
16737
16738            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16739                runs.push((prev_end..label.text.len(), fade_out));
16740            }
16741
16742            runs
16743        })
16744}
16745
16746pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16747    let mut prev_index = 0;
16748    let mut prev_codepoint: Option<char> = None;
16749    text.char_indices()
16750        .chain([(text.len(), '\0')])
16751        .filter_map(move |(index, codepoint)| {
16752            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16753            let is_boundary = index == text.len()
16754                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16755                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16756            if is_boundary {
16757                let chunk = &text[prev_index..index];
16758                prev_index = index;
16759                Some(chunk)
16760            } else {
16761                None
16762            }
16763        })
16764}
16765
16766pub trait RangeToAnchorExt: Sized {
16767    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16768
16769    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16770        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16771        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16772    }
16773}
16774
16775impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16776    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16777        let start_offset = self.start.to_offset(snapshot);
16778        let end_offset = self.end.to_offset(snapshot);
16779        if start_offset == end_offset {
16780            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16781        } else {
16782            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16783        }
16784    }
16785}
16786
16787pub trait RowExt {
16788    fn as_f32(&self) -> f32;
16789
16790    fn next_row(&self) -> Self;
16791
16792    fn previous_row(&self) -> Self;
16793
16794    fn minus(&self, other: Self) -> u32;
16795}
16796
16797impl RowExt for DisplayRow {
16798    fn as_f32(&self) -> f32 {
16799        self.0 as f32
16800    }
16801
16802    fn next_row(&self) -> Self {
16803        Self(self.0 + 1)
16804    }
16805
16806    fn previous_row(&self) -> Self {
16807        Self(self.0.saturating_sub(1))
16808    }
16809
16810    fn minus(&self, other: Self) -> u32 {
16811        self.0 - other.0
16812    }
16813}
16814
16815impl RowExt for MultiBufferRow {
16816    fn as_f32(&self) -> f32 {
16817        self.0 as f32
16818    }
16819
16820    fn next_row(&self) -> Self {
16821        Self(self.0 + 1)
16822    }
16823
16824    fn previous_row(&self) -> Self {
16825        Self(self.0.saturating_sub(1))
16826    }
16827
16828    fn minus(&self, other: Self) -> u32 {
16829        self.0 - other.0
16830    }
16831}
16832
16833trait RowRangeExt {
16834    type Row;
16835
16836    fn len(&self) -> usize;
16837
16838    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16839}
16840
16841impl RowRangeExt for Range<MultiBufferRow> {
16842    type Row = MultiBufferRow;
16843
16844    fn len(&self) -> usize {
16845        (self.end.0 - self.start.0) as usize
16846    }
16847
16848    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16849        (self.start.0..self.end.0).map(MultiBufferRow)
16850    }
16851}
16852
16853impl RowRangeExt for Range<DisplayRow> {
16854    type Row = DisplayRow;
16855
16856    fn len(&self) -> usize {
16857        (self.end.0 - self.start.0) as usize
16858    }
16859
16860    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16861        (self.start.0..self.end.0).map(DisplayRow)
16862    }
16863}
16864
16865/// If select range has more than one line, we
16866/// just point the cursor to range.start.
16867fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16868    if range.start.row == range.end.row {
16869        range
16870    } else {
16871        range.start..range.start
16872    }
16873}
16874pub struct KillRing(ClipboardItem);
16875impl Global for KillRing {}
16876
16877const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16878
16879fn all_edits_insertions_or_deletions(
16880    edits: &Vec<(Range<Anchor>, String)>,
16881    snapshot: &MultiBufferSnapshot,
16882) -> bool {
16883    let mut all_insertions = true;
16884    let mut all_deletions = true;
16885
16886    for (range, new_text) in edits.iter() {
16887        let range_is_empty = range.to_offset(&snapshot).is_empty();
16888        let text_is_empty = new_text.is_empty();
16889
16890        if range_is_empty != text_is_empty {
16891            if range_is_empty {
16892                all_deletions = false;
16893            } else {
16894                all_insertions = false;
16895            }
16896        } else {
16897            return false;
16898        }
16899
16900        if !all_insertions && !all_deletions {
16901            return false;
16902        }
16903    }
16904    all_insertions || all_deletions
16905}