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