editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{future, FutureExt};
   71use fuzzy::StringMatchCandidate;
   72
   73use code_context_menus::{
   74    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   75    CompletionsMenu, ContextMenuOrigin,
   76};
   77use git::blame::GitBlame;
   78use gpui::{
   79    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   80    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   81    ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
   82    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   83    HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
   84    PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
   85    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   86    WeakEntity, WeakFocusHandle, Window,
   87};
   88use highlight_matching_bracket::refresh_matching_bracket_highlights;
   89use hover_popover::{hide_hover, HoverState};
   90use indent_guides::ActiveIndentGuidesState;
   91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   92pub use inline_completion::Direction;
   93use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   94pub use items::MAX_TAB_TITLE_LEN;
   95use itertools::Itertools;
   96use language::{
   97    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   98    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   99    CompletionDocumentation, CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview,
  100    HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
  101    SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  102};
  103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  104use linked_editing_ranges::refresh_linked_ranges;
  105use mouse_context_menu::MouseContextMenu;
  106pub use proposed_changes_editor::{
  107    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  108};
  109use similar::{ChangeTag, TextDiff};
  110use std::iter::Peekable;
  111use task::{ResolvedTask, TaskTemplate, TaskVariables};
  112
  113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  114pub use lsp::CompletionContext;
  115use lsp::{
  116    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  117    LanguageServerId, LanguageServerName,
  118};
  119
  120use language::BufferSnapshot;
  121use movement::TextLayoutDetails;
  122pub use multi_buffer::{
  123    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  124    ToOffset, ToPoint,
  125};
  126use multi_buffer::{
  127    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  128    ToOffsetUtf16,
  129};
  130use project::{
  131    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  132    project_settings::{GitGutterSetting, ProjectSettings},
  133    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  134    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  135};
  136use rand::prelude::*;
  137use rpc::{proto::*, ErrorExt};
  138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  139use selections_collection::{
  140    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  141};
  142use serde::{Deserialize, Serialize};
  143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  144use smallvec::SmallVec;
  145use snippet::Snippet;
  146use std::{
  147    any::TypeId,
  148    borrow::Cow,
  149    cell::RefCell,
  150    cmp::{self, Ordering, Reverse},
  151    mem,
  152    num::NonZeroU32,
  153    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  154    path::{Path, PathBuf},
  155    rc::Rc,
  156    sync::Arc,
  157    time::{Duration, Instant},
  158};
  159pub use sum_tree::Bias;
  160use sum_tree::TreeMap;
  161use text::{BufferId, OffsetUtf16, Rope};
  162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  163use ui::{
  164    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  165    Tooltip,
  166};
  167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  168use workspace::item::{ItemHandle, PreviewTabsSettings};
  169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  170use workspace::{
  171    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  172};
  173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  174
  175use crate::hover_links::{find_url, find_url_from_range};
  176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  177
  178pub const FILE_HEADER_HEIGHT: u32 = 2;
  179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  183const MAX_LINE_LEN: usize = 1024;
  184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  187#[doc(hidden)]
  188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  194pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  195
  196pub fn render_parsed_markdown(
  197    element_id: impl Into<ElementId>,
  198    parsed: &language::ParsedMarkdown,
  199    editor_style: &EditorStyle,
  200    workspace: Option<WeakEntity<Workspace>>,
  201    cx: &mut App,
  202) -> InteractiveText {
  203    let code_span_background_color = cx
  204        .theme()
  205        .colors()
  206        .editor_document_highlight_read_background;
  207
  208    let highlights = gpui::combine_highlights(
  209        parsed.highlights.iter().filter_map(|(range, highlight)| {
  210            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  211            Some((range.clone(), highlight))
  212        }),
  213        parsed
  214            .regions
  215            .iter()
  216            .zip(&parsed.region_ranges)
  217            .filter_map(|(region, range)| {
  218                if region.code {
  219                    Some((
  220                        range.clone(),
  221                        HighlightStyle {
  222                            background_color: Some(code_span_background_color),
  223                            ..Default::default()
  224                        },
  225                    ))
  226                } else {
  227                    None
  228                }
  229            }),
  230    );
  231
  232    let mut links = Vec::new();
  233    let mut link_ranges = Vec::new();
  234    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  235        if let Some(link) = region.link.clone() {
  236            links.push(link);
  237            link_ranges.push(range.clone());
  238        }
  239    }
  240
  241    InteractiveText::new(
  242        element_id,
  243        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  244    )
  245    .on_click(
  246        link_ranges,
  247        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  248            markdown::Link::Web { url } => cx.open_url(url),
  249            markdown::Link::Path { path } => {
  250                if let Some(workspace) = &workspace {
  251                    _ = workspace.update(cx, |workspace, cx| {
  252                        workspace
  253                            .open_abs_path(path.clone(), false, window, cx)
  254                            .detach();
  255                    });
  256                }
  257            }
  258        },
  259    )
  260}
  261
  262#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  263pub enum InlayId {
  264    InlineCompletion(usize),
  265    Hint(usize),
  266}
  267
  268impl InlayId {
  269    fn id(&self) -> usize {
  270        match self {
  271            Self::InlineCompletion(id) => *id,
  272            Self::Hint(id) => *id,
  273        }
  274    }
  275}
  276
  277enum DocumentHighlightRead {}
  278enum DocumentHighlightWrite {}
  279enum InputComposition {}
  280
  281#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  282pub enum Navigated {
  283    Yes,
  284    No,
  285}
  286
  287impl Navigated {
  288    pub fn from_bool(yes: bool) -> Navigated {
  289        if yes {
  290            Navigated::Yes
  291        } else {
  292            Navigated::No
  293        }
  294    }
  295}
  296
  297pub fn init_settings(cx: &mut App) {
  298    EditorSettings::register(cx);
  299}
  300
  301pub fn init(cx: &mut App) {
  302    init_settings(cx);
  303
  304    workspace::register_project_item::<Editor>(cx);
  305    workspace::FollowableViewRegistry::register::<Editor>(cx);
  306    workspace::register_serializable_item::<Editor>(cx);
  307
  308    cx.observe_new(
  309        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  310            workspace.register_action(Editor::new_file);
  311            workspace.register_action(Editor::new_file_vertical);
  312            workspace.register_action(Editor::new_file_horizontal);
  313            workspace.register_action(Editor::cancel_language_server_work);
  314        },
  315    )
  316    .detach();
  317
  318    cx.on_action(move |_: &workspace::NewFile, cx| {
  319        let app_state = workspace::AppState::global(cx);
  320        if let Some(app_state) = app_state.upgrade() {
  321            workspace::open_new(
  322                Default::default(),
  323                app_state,
  324                cx,
  325                |workspace, window, cx| {
  326                    Editor::new_file(workspace, &Default::default(), window, cx)
  327                },
  328            )
  329            .detach();
  330        }
  331    });
  332    cx.on_action(move |_: &workspace::NewWindow, cx| {
  333        let app_state = workspace::AppState::global(cx);
  334        if let Some(app_state) = app_state.upgrade() {
  335            workspace::open_new(
  336                Default::default(),
  337                app_state,
  338                cx,
  339                |workspace, window, cx| {
  340                    cx.activate(true);
  341                    Editor::new_file(workspace, &Default::default(), window, cx)
  342                },
  343            )
  344            .detach();
  345        }
  346    });
  347}
  348
  349pub struct SearchWithinRange;
  350
  351trait InvalidationRegion {
  352    fn ranges(&self) -> &[Range<Anchor>];
  353}
  354
  355#[derive(Clone, Debug, PartialEq)]
  356pub enum SelectPhase {
  357    Begin {
  358        position: DisplayPoint,
  359        add: bool,
  360        click_count: usize,
  361    },
  362    BeginColumnar {
  363        position: DisplayPoint,
  364        reset: bool,
  365        goal_column: u32,
  366    },
  367    Extend {
  368        position: DisplayPoint,
  369        click_count: usize,
  370    },
  371    Update {
  372        position: DisplayPoint,
  373        goal_column: u32,
  374        scroll_delta: gpui::Point<f32>,
  375    },
  376    End,
  377}
  378
  379#[derive(Clone, Debug)]
  380pub enum SelectMode {
  381    Character,
  382    Word(Range<Anchor>),
  383    Line(Range<Anchor>),
  384    All,
  385}
  386
  387#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  388pub enum EditorMode {
  389    SingleLine { auto_width: bool },
  390    AutoHeight { max_lines: usize },
  391    Full,
  392}
  393
  394#[derive(Copy, Clone, Debug)]
  395pub enum SoftWrap {
  396    /// Prefer not to wrap at all.
  397    ///
  398    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  399    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  400    GitDiff,
  401    /// Prefer a single line generally, unless an overly long line is encountered.
  402    None,
  403    /// Soft wrap lines that exceed the editor width.
  404    EditorWidth,
  405    /// Soft wrap lines at the preferred line length.
  406    Column(u32),
  407    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  408    Bounded(u32),
  409}
  410
  411#[derive(Clone)]
  412pub struct EditorStyle {
  413    pub background: Hsla,
  414    pub local_player: PlayerColor,
  415    pub text: TextStyle,
  416    pub scrollbar_width: Pixels,
  417    pub syntax: Arc<SyntaxTheme>,
  418    pub status: StatusColors,
  419    pub inlay_hints_style: HighlightStyle,
  420    pub inline_completion_styles: InlineCompletionStyles,
  421    pub unnecessary_code_fade: f32,
  422}
  423
  424impl Default for EditorStyle {
  425    fn default() -> Self {
  426        Self {
  427            background: Hsla::default(),
  428            local_player: PlayerColor::default(),
  429            text: TextStyle::default(),
  430            scrollbar_width: Pixels::default(),
  431            syntax: Default::default(),
  432            // HACK: Status colors don't have a real default.
  433            // We should look into removing the status colors from the editor
  434            // style and retrieve them directly from the theme.
  435            status: StatusColors::dark(),
  436            inlay_hints_style: HighlightStyle::default(),
  437            inline_completion_styles: InlineCompletionStyles {
  438                insertion: HighlightStyle::default(),
  439                whitespace: HighlightStyle::default(),
  440            },
  441            unnecessary_code_fade: Default::default(),
  442        }
  443    }
  444}
  445
  446pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  447    let show_background = language_settings::language_settings(None, None, cx)
  448        .inlay_hints
  449        .show_background;
  450
  451    HighlightStyle {
  452        color: Some(cx.theme().status().hint),
  453        background_color: show_background.then(|| cx.theme().status().hint_background),
  454        ..HighlightStyle::default()
  455    }
  456}
  457
  458pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  459    InlineCompletionStyles {
  460        insertion: HighlightStyle {
  461            color: Some(cx.theme().status().predictive),
  462            ..HighlightStyle::default()
  463        },
  464        whitespace: HighlightStyle {
  465            background_color: Some(cx.theme().status().created_background),
  466            ..HighlightStyle::default()
  467        },
  468    }
  469}
  470
  471type CompletionId = usize;
  472
  473pub(crate) enum EditDisplayMode {
  474    TabAccept,
  475    DiffPopover,
  476    Inline,
  477}
  478
  479enum InlineCompletion {
  480    Edit {
  481        edits: Vec<(Range<Anchor>, String)>,
  482        edit_preview: Option<EditPreview>,
  483        display_mode: EditDisplayMode,
  484        snapshot: BufferSnapshot,
  485    },
  486    Move {
  487        target: Anchor,
  488        snapshot: BufferSnapshot,
  489    },
  490}
  491
  492struct InlineCompletionState {
  493    inlay_ids: Vec<InlayId>,
  494    completion: InlineCompletion,
  495    completion_id: Option<SharedString>,
  496    invalidation_range: Range<Anchor>,
  497}
  498
  499enum EditPredictionSettings {
  500    Disabled,
  501    Enabled {
  502        show_in_menu: bool,
  503        preview_requires_modifier: bool,
  504    },
  505}
  506
  507impl EditPredictionSettings {
  508    pub fn is_enabled(&self) -> bool {
  509        match self {
  510            EditPredictionSettings::Disabled => false,
  511            EditPredictionSettings::Enabled { .. } => true,
  512        }
  513    }
  514}
  515
  516enum InlineCompletionHighlight {}
  517
  518pub enum MenuInlineCompletionsPolicy {
  519    Never,
  520    ByProvider,
  521}
  522
  523pub enum EditPredictionPreview {
  524    /// Modifier is not pressed
  525    Inactive,
  526    /// Modifier pressed
  527    Active {
  528        previous_scroll_position: Option<ScrollAnchor>,
  529    },
  530}
  531
  532#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  533struct EditorActionId(usize);
  534
  535impl EditorActionId {
  536    pub fn post_inc(&mut self) -> Self {
  537        let answer = self.0;
  538
  539        *self = Self(answer + 1);
  540
  541        Self(answer)
  542    }
  543}
  544
  545// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  546// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  547
  548type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  549type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  550
  551#[derive(Default)]
  552struct ScrollbarMarkerState {
  553    scrollbar_size: Size<Pixels>,
  554    dirty: bool,
  555    markers: Arc<[PaintQuad]>,
  556    pending_refresh: Option<Task<Result<()>>>,
  557}
  558
  559impl ScrollbarMarkerState {
  560    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  561        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  562    }
  563}
  564
  565#[derive(Clone, Debug)]
  566struct RunnableTasks {
  567    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  568    offset: MultiBufferOffset,
  569    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  570    column: u32,
  571    // Values of all named captures, including those starting with '_'
  572    extra_variables: HashMap<String, String>,
  573    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  574    context_range: Range<BufferOffset>,
  575}
  576
  577impl RunnableTasks {
  578    fn resolve<'a>(
  579        &'a self,
  580        cx: &'a task::TaskContext,
  581    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  582        self.templates.iter().filter_map(|(kind, template)| {
  583            template
  584                .resolve_task(&kind.to_id_base(), cx)
  585                .map(|task| (kind.clone(), task))
  586        })
  587    }
  588}
  589
  590#[derive(Clone)]
  591struct ResolvedTasks {
  592    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  593    position: Anchor,
  594}
  595#[derive(Copy, Clone, Debug)]
  596struct MultiBufferOffset(usize);
  597#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  598struct BufferOffset(usize);
  599
  600// Addons allow storing per-editor state in other crates (e.g. Vim)
  601pub trait Addon: 'static {
  602    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  603
  604    fn render_buffer_header_controls(
  605        &self,
  606        _: &ExcerptInfo,
  607        _: &Window,
  608        _: &App,
  609    ) -> Option<AnyElement> {
  610        None
  611    }
  612
  613    fn to_any(&self) -> &dyn std::any::Any;
  614}
  615
  616#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  617pub enum IsVimMode {
  618    Yes,
  619    No,
  620}
  621
  622/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  623///
  624/// See the [module level documentation](self) for more information.
  625pub struct Editor {
  626    focus_handle: FocusHandle,
  627    last_focused_descendant: Option<WeakFocusHandle>,
  628    /// The text buffer being edited
  629    buffer: Entity<MultiBuffer>,
  630    /// Map of how text in the buffer should be displayed.
  631    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  632    pub display_map: Entity<DisplayMap>,
  633    pub selections: SelectionsCollection,
  634    pub scroll_manager: ScrollManager,
  635    /// When inline assist editors are linked, they all render cursors because
  636    /// typing enters text into each of them, even the ones that aren't focused.
  637    pub(crate) show_cursor_when_unfocused: bool,
  638    columnar_selection_tail: Option<Anchor>,
  639    add_selections_state: Option<AddSelectionsState>,
  640    select_next_state: Option<SelectNextState>,
  641    select_prev_state: Option<SelectNextState>,
  642    selection_history: SelectionHistory,
  643    autoclose_regions: Vec<AutocloseRegion>,
  644    snippet_stack: InvalidationStack<SnippetState>,
  645    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  646    ime_transaction: Option<TransactionId>,
  647    active_diagnostics: Option<ActiveDiagnosticGroup>,
  648    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  649
  650    // TODO: make this a access method
  651    pub project: Option<Entity<Project>>,
  652    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  653    completion_provider: Option<Box<dyn CompletionProvider>>,
  654    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  655    blink_manager: Entity<BlinkManager>,
  656    show_cursor_names: bool,
  657    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  658    pub show_local_selections: bool,
  659    mode: EditorMode,
  660    show_breadcrumbs: bool,
  661    show_gutter: bool,
  662    show_scrollbars: bool,
  663    show_line_numbers: Option<bool>,
  664    use_relative_line_numbers: Option<bool>,
  665    show_git_diff_gutter: Option<bool>,
  666    show_code_actions: Option<bool>,
  667    show_runnables: Option<bool>,
  668    show_wrap_guides: Option<bool>,
  669    show_indent_guides: Option<bool>,
  670    placeholder_text: Option<Arc<str>>,
  671    highlight_order: usize,
  672    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  673    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  674    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  675    scrollbar_marker_state: ScrollbarMarkerState,
  676    active_indent_guides_state: ActiveIndentGuidesState,
  677    nav_history: Option<ItemNavHistory>,
  678    context_menu: RefCell<Option<CodeContextMenu>>,
  679    mouse_context_menu: Option<MouseContextMenu>,
  680    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  681    signature_help_state: SignatureHelpState,
  682    auto_signature_help: Option<bool>,
  683    find_all_references_task_sources: Vec<Anchor>,
  684    next_completion_id: CompletionId,
  685    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  686    code_actions_task: Option<Task<Result<()>>>,
  687    document_highlights_task: Option<Task<()>>,
  688    linked_editing_range_task: Option<Task<Option<()>>>,
  689    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  690    pending_rename: Option<RenameState>,
  691    searchable: bool,
  692    cursor_shape: CursorShape,
  693    current_line_highlight: Option<CurrentLineHighlight>,
  694    collapse_matches: bool,
  695    autoindent_mode: Option<AutoindentMode>,
  696    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  697    input_enabled: bool,
  698    use_modal_editing: bool,
  699    read_only: bool,
  700    leader_peer_id: Option<PeerId>,
  701    remote_id: Option<ViewId>,
  702    hover_state: HoverState,
  703    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  704    gutter_hovered: bool,
  705    hovered_link_state: Option<HoveredLinkState>,
  706    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  707    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  708    active_inline_completion: Option<InlineCompletionState>,
  709    /// Used to prevent flickering as the user types while the menu is open
  710    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  711    edit_prediction_settings: EditPredictionSettings,
  712    inline_completions_hidden_for_vim_mode: bool,
  713    show_inline_completions_override: Option<bool>,
  714    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  715    edit_prediction_preview: EditPredictionPreview,
  716    edit_prediction_cursor_on_leading_whitespace: bool,
  717    edit_prediction_requires_modifier_in_leading_space: bool,
  718    inlay_hint_cache: InlayHintCache,
  719    next_inlay_id: usize,
  720    _subscriptions: Vec<Subscription>,
  721    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  722    gutter_dimensions: GutterDimensions,
  723    style: Option<EditorStyle>,
  724    text_style_refinement: Option<TextStyleRefinement>,
  725    next_editor_action_id: EditorActionId,
  726    editor_actions:
  727        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  728    use_autoclose: bool,
  729    use_auto_surround: bool,
  730    auto_replace_emoji_shortcode: bool,
  731    show_git_blame_gutter: bool,
  732    show_git_blame_inline: bool,
  733    show_git_blame_inline_delay_task: Option<Task<()>>,
  734    distinguish_unstaged_diff_hunks: bool,
  735    git_blame_inline_enabled: bool,
  736    serialize_dirty_buffers: bool,
  737    show_selection_menu: Option<bool>,
  738    blame: Option<Entity<GitBlame>>,
  739    blame_subscription: Option<Subscription>,
  740    custom_context_menu: Option<
  741        Box<
  742            dyn 'static
  743                + Fn(
  744                    &mut Self,
  745                    DisplayPoint,
  746                    &mut Window,
  747                    &mut Context<Self>,
  748                ) -> Option<Entity<ui::ContextMenu>>,
  749        >,
  750    >,
  751    last_bounds: Option<Bounds<Pixels>>,
  752    last_position_map: Option<Rc<PositionMap>>,
  753    expect_bounds_change: Option<Bounds<Pixels>>,
  754    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  755    tasks_update_task: Option<Task<()>>,
  756    in_project_search: bool,
  757    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  758    breadcrumb_header: Option<String>,
  759    focused_block: Option<FocusedBlock>,
  760    next_scroll_position: NextScrollCursorCenterTopBottom,
  761    addons: HashMap<TypeId, Box<dyn Addon>>,
  762    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  763    selection_mark_mode: bool,
  764    toggle_fold_multiple_buffers: Task<()>,
  765    _scroll_cursor_center_top_bottom_task: Task<()>,
  766}
  767
  768#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  769enum NextScrollCursorCenterTopBottom {
  770    #[default]
  771    Center,
  772    Top,
  773    Bottom,
  774}
  775
  776impl NextScrollCursorCenterTopBottom {
  777    fn next(&self) -> Self {
  778        match self {
  779            Self::Center => Self::Top,
  780            Self::Top => Self::Bottom,
  781            Self::Bottom => Self::Center,
  782        }
  783    }
  784}
  785
  786#[derive(Clone)]
  787pub struct EditorSnapshot {
  788    pub mode: EditorMode,
  789    show_gutter: bool,
  790    show_line_numbers: Option<bool>,
  791    show_git_diff_gutter: Option<bool>,
  792    show_code_actions: Option<bool>,
  793    show_runnables: Option<bool>,
  794    git_blame_gutter_max_author_length: Option<usize>,
  795    pub display_snapshot: DisplaySnapshot,
  796    pub placeholder_text: Option<Arc<str>>,
  797    is_focused: bool,
  798    scroll_anchor: ScrollAnchor,
  799    ongoing_scroll: OngoingScroll,
  800    current_line_highlight: CurrentLineHighlight,
  801    gutter_hovered: bool,
  802}
  803
  804const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  805
  806#[derive(Default, Debug, Clone, Copy)]
  807pub struct GutterDimensions {
  808    pub left_padding: Pixels,
  809    pub right_padding: Pixels,
  810    pub width: Pixels,
  811    pub margin: Pixels,
  812    pub git_blame_entries_width: Option<Pixels>,
  813}
  814
  815impl GutterDimensions {
  816    /// The full width of the space taken up by the gutter.
  817    pub fn full_width(&self) -> Pixels {
  818        self.margin + self.width
  819    }
  820
  821    /// The width of the space reserved for the fold indicators,
  822    /// use alongside 'justify_end' and `gutter_width` to
  823    /// right align content with the line numbers
  824    pub fn fold_area_width(&self) -> Pixels {
  825        self.margin + self.right_padding
  826    }
  827}
  828
  829#[derive(Debug)]
  830pub struct RemoteSelection {
  831    pub replica_id: ReplicaId,
  832    pub selection: Selection<Anchor>,
  833    pub cursor_shape: CursorShape,
  834    pub peer_id: PeerId,
  835    pub line_mode: bool,
  836    pub participant_index: Option<ParticipantIndex>,
  837    pub user_name: Option<SharedString>,
  838}
  839
  840#[derive(Clone, Debug)]
  841struct SelectionHistoryEntry {
  842    selections: Arc<[Selection<Anchor>]>,
  843    select_next_state: Option<SelectNextState>,
  844    select_prev_state: Option<SelectNextState>,
  845    add_selections_state: Option<AddSelectionsState>,
  846}
  847
  848enum SelectionHistoryMode {
  849    Normal,
  850    Undoing,
  851    Redoing,
  852}
  853
  854#[derive(Clone, PartialEq, Eq, Hash)]
  855struct HoveredCursor {
  856    replica_id: u16,
  857    selection_id: usize,
  858}
  859
  860impl Default for SelectionHistoryMode {
  861    fn default() -> Self {
  862        Self::Normal
  863    }
  864}
  865
  866#[derive(Default)]
  867struct SelectionHistory {
  868    #[allow(clippy::type_complexity)]
  869    selections_by_transaction:
  870        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  871    mode: SelectionHistoryMode,
  872    undo_stack: VecDeque<SelectionHistoryEntry>,
  873    redo_stack: VecDeque<SelectionHistoryEntry>,
  874}
  875
  876impl SelectionHistory {
  877    fn insert_transaction(
  878        &mut self,
  879        transaction_id: TransactionId,
  880        selections: Arc<[Selection<Anchor>]>,
  881    ) {
  882        self.selections_by_transaction
  883            .insert(transaction_id, (selections, None));
  884    }
  885
  886    #[allow(clippy::type_complexity)]
  887    fn transaction(
  888        &self,
  889        transaction_id: TransactionId,
  890    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  891        self.selections_by_transaction.get(&transaction_id)
  892    }
  893
  894    #[allow(clippy::type_complexity)]
  895    fn transaction_mut(
  896        &mut self,
  897        transaction_id: TransactionId,
  898    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  899        self.selections_by_transaction.get_mut(&transaction_id)
  900    }
  901
  902    fn push(&mut self, entry: SelectionHistoryEntry) {
  903        if !entry.selections.is_empty() {
  904            match self.mode {
  905                SelectionHistoryMode::Normal => {
  906                    self.push_undo(entry);
  907                    self.redo_stack.clear();
  908                }
  909                SelectionHistoryMode::Undoing => self.push_redo(entry),
  910                SelectionHistoryMode::Redoing => self.push_undo(entry),
  911            }
  912        }
  913    }
  914
  915    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  916        if self
  917            .undo_stack
  918            .back()
  919            .map_or(true, |e| e.selections != entry.selections)
  920        {
  921            self.undo_stack.push_back(entry);
  922            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  923                self.undo_stack.pop_front();
  924            }
  925        }
  926    }
  927
  928    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  929        if self
  930            .redo_stack
  931            .back()
  932            .map_or(true, |e| e.selections != entry.selections)
  933        {
  934            self.redo_stack.push_back(entry);
  935            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  936                self.redo_stack.pop_front();
  937            }
  938        }
  939    }
  940}
  941
  942struct RowHighlight {
  943    index: usize,
  944    range: Range<Anchor>,
  945    color: Hsla,
  946    should_autoscroll: bool,
  947}
  948
  949#[derive(Clone, Debug)]
  950struct AddSelectionsState {
  951    above: bool,
  952    stack: Vec<usize>,
  953}
  954
  955#[derive(Clone)]
  956struct SelectNextState {
  957    query: AhoCorasick,
  958    wordwise: bool,
  959    done: bool,
  960}
  961
  962impl std::fmt::Debug for SelectNextState {
  963    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  964        f.debug_struct(std::any::type_name::<Self>())
  965            .field("wordwise", &self.wordwise)
  966            .field("done", &self.done)
  967            .finish()
  968    }
  969}
  970
  971#[derive(Debug)]
  972struct AutocloseRegion {
  973    selection_id: usize,
  974    range: Range<Anchor>,
  975    pair: BracketPair,
  976}
  977
  978#[derive(Debug)]
  979struct SnippetState {
  980    ranges: Vec<Vec<Range<Anchor>>>,
  981    active_index: usize,
  982    choices: Vec<Option<Vec<String>>>,
  983}
  984
  985#[doc(hidden)]
  986pub struct RenameState {
  987    pub range: Range<Anchor>,
  988    pub old_name: Arc<str>,
  989    pub editor: Entity<Editor>,
  990    block_id: CustomBlockId,
  991}
  992
  993struct InvalidationStack<T>(Vec<T>);
  994
  995struct RegisteredInlineCompletionProvider {
  996    provider: Arc<dyn InlineCompletionProviderHandle>,
  997    _subscription: Subscription,
  998}
  999
 1000#[derive(Debug)]
 1001struct ActiveDiagnosticGroup {
 1002    primary_range: Range<Anchor>,
 1003    primary_message: String,
 1004    group_id: usize,
 1005    blocks: HashMap<CustomBlockId, Diagnostic>,
 1006    is_valid: bool,
 1007}
 1008
 1009#[derive(Serialize, Deserialize, Clone, Debug)]
 1010pub struct ClipboardSelection {
 1011    pub len: usize,
 1012    pub is_entire_line: bool,
 1013    pub first_line_indent: u32,
 1014}
 1015
 1016#[derive(Debug)]
 1017pub(crate) struct NavigationData {
 1018    cursor_anchor: Anchor,
 1019    cursor_position: Point,
 1020    scroll_anchor: ScrollAnchor,
 1021    scroll_top_row: u32,
 1022}
 1023
 1024#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1025pub enum GotoDefinitionKind {
 1026    Symbol,
 1027    Declaration,
 1028    Type,
 1029    Implementation,
 1030}
 1031
 1032#[derive(Debug, Clone)]
 1033enum InlayHintRefreshReason {
 1034    Toggle(bool),
 1035    SettingsChange(InlayHintSettings),
 1036    NewLinesShown,
 1037    BufferEdited(HashSet<Arc<Language>>),
 1038    RefreshRequested,
 1039    ExcerptsRemoved(Vec<ExcerptId>),
 1040}
 1041
 1042impl InlayHintRefreshReason {
 1043    fn description(&self) -> &'static str {
 1044        match self {
 1045            Self::Toggle(_) => "toggle",
 1046            Self::SettingsChange(_) => "settings change",
 1047            Self::NewLinesShown => "new lines shown",
 1048            Self::BufferEdited(_) => "buffer edited",
 1049            Self::RefreshRequested => "refresh requested",
 1050            Self::ExcerptsRemoved(_) => "excerpts removed",
 1051        }
 1052    }
 1053}
 1054
 1055pub enum FormatTarget {
 1056    Buffers,
 1057    Ranges(Vec<Range<MultiBufferPoint>>),
 1058}
 1059
 1060pub(crate) struct FocusedBlock {
 1061    id: BlockId,
 1062    focus_handle: WeakFocusHandle,
 1063}
 1064
 1065#[derive(Clone)]
 1066enum JumpData {
 1067    MultiBufferRow {
 1068        row: MultiBufferRow,
 1069        line_offset_from_top: u32,
 1070    },
 1071    MultiBufferPoint {
 1072        excerpt_id: ExcerptId,
 1073        position: Point,
 1074        anchor: text::Anchor,
 1075        line_offset_from_top: u32,
 1076    },
 1077}
 1078
 1079pub enum MultibufferSelectionMode {
 1080    First,
 1081    All,
 1082}
 1083
 1084impl Editor {
 1085    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1086        let buffer = cx.new(|cx| Buffer::local("", cx));
 1087        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1088        Self::new(
 1089            EditorMode::SingleLine { auto_width: false },
 1090            buffer,
 1091            None,
 1092            false,
 1093            window,
 1094            cx,
 1095        )
 1096    }
 1097
 1098    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1099        let buffer = cx.new(|cx| Buffer::local("", cx));
 1100        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1101        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1102    }
 1103
 1104    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1105        let buffer = cx.new(|cx| Buffer::local("", cx));
 1106        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1107        Self::new(
 1108            EditorMode::SingleLine { auto_width: true },
 1109            buffer,
 1110            None,
 1111            false,
 1112            window,
 1113            cx,
 1114        )
 1115    }
 1116
 1117    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1118        let buffer = cx.new(|cx| Buffer::local("", cx));
 1119        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1120        Self::new(
 1121            EditorMode::AutoHeight { max_lines },
 1122            buffer,
 1123            None,
 1124            false,
 1125            window,
 1126            cx,
 1127        )
 1128    }
 1129
 1130    pub fn for_buffer(
 1131        buffer: Entity<Buffer>,
 1132        project: Option<Entity<Project>>,
 1133        window: &mut Window,
 1134        cx: &mut Context<Self>,
 1135    ) -> Self {
 1136        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1137        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1138    }
 1139
 1140    pub fn for_multibuffer(
 1141        buffer: Entity<MultiBuffer>,
 1142        project: Option<Entity<Project>>,
 1143        show_excerpt_controls: bool,
 1144        window: &mut Window,
 1145        cx: &mut Context<Self>,
 1146    ) -> Self {
 1147        Self::new(
 1148            EditorMode::Full,
 1149            buffer,
 1150            project,
 1151            show_excerpt_controls,
 1152            window,
 1153            cx,
 1154        )
 1155    }
 1156
 1157    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1158        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1159        let mut clone = Self::new(
 1160            self.mode,
 1161            self.buffer.clone(),
 1162            self.project.clone(),
 1163            show_excerpt_controls,
 1164            window,
 1165            cx,
 1166        );
 1167        self.display_map.update(cx, |display_map, cx| {
 1168            let snapshot = display_map.snapshot(cx);
 1169            clone.display_map.update(cx, |display_map, cx| {
 1170                display_map.set_state(&snapshot, cx);
 1171            });
 1172        });
 1173        clone.selections.clone_state(&self.selections);
 1174        clone.scroll_manager.clone_state(&self.scroll_manager);
 1175        clone.searchable = self.searchable;
 1176        clone
 1177    }
 1178
 1179    pub fn new(
 1180        mode: EditorMode,
 1181        buffer: Entity<MultiBuffer>,
 1182        project: Option<Entity<Project>>,
 1183        show_excerpt_controls: bool,
 1184        window: &mut Window,
 1185        cx: &mut Context<Self>,
 1186    ) -> Self {
 1187        let style = window.text_style();
 1188        let font_size = style.font_size.to_pixels(window.rem_size());
 1189        let editor = cx.entity().downgrade();
 1190        let fold_placeholder = FoldPlaceholder {
 1191            constrain_width: true,
 1192            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1193                let editor = editor.clone();
 1194                div()
 1195                    .id(fold_id)
 1196                    .bg(cx.theme().colors().ghost_element_background)
 1197                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1198                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1199                    .rounded_sm()
 1200                    .size_full()
 1201                    .cursor_pointer()
 1202                    .child("")
 1203                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1204                    .on_click(move |_, _window, cx| {
 1205                        editor
 1206                            .update(cx, |editor, cx| {
 1207                                editor.unfold_ranges(
 1208                                    &[fold_range.start..fold_range.end],
 1209                                    true,
 1210                                    false,
 1211                                    cx,
 1212                                );
 1213                                cx.stop_propagation();
 1214                            })
 1215                            .ok();
 1216                    })
 1217                    .into_any()
 1218            }),
 1219            merge_adjacent: true,
 1220            ..Default::default()
 1221        };
 1222        let display_map = cx.new(|cx| {
 1223            DisplayMap::new(
 1224                buffer.clone(),
 1225                style.font(),
 1226                font_size,
 1227                None,
 1228                show_excerpt_controls,
 1229                FILE_HEADER_HEIGHT,
 1230                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1231                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1232                fold_placeholder,
 1233                cx,
 1234            )
 1235        });
 1236
 1237        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1238
 1239        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1240
 1241        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1242            .then(|| language_settings::SoftWrap::None);
 1243
 1244        let mut project_subscriptions = Vec::new();
 1245        if mode == EditorMode::Full {
 1246            if let Some(project) = project.as_ref() {
 1247                if buffer.read(cx).is_singleton() {
 1248                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1249                        cx.emit(EditorEvent::TitleChanged);
 1250                    }));
 1251                }
 1252                project_subscriptions.push(cx.subscribe_in(
 1253                    project,
 1254                    window,
 1255                    |editor, _, event, window, cx| {
 1256                        if let project::Event::RefreshInlayHints = event {
 1257                            editor
 1258                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1259                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1260                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1261                                let focus_handle = editor.focus_handle(cx);
 1262                                if focus_handle.is_focused(window) {
 1263                                    let snapshot = buffer.read(cx).snapshot();
 1264                                    for (range, snippet) in snippet_edits {
 1265                                        let editor_range =
 1266                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1267                                        editor
 1268                                            .insert_snippet(
 1269                                                &[editor_range],
 1270                                                snippet.clone(),
 1271                                                window,
 1272                                                cx,
 1273                                            )
 1274                                            .ok();
 1275                                    }
 1276                                }
 1277                            }
 1278                        }
 1279                    },
 1280                ));
 1281                if let Some(task_inventory) = project
 1282                    .read(cx)
 1283                    .task_store()
 1284                    .read(cx)
 1285                    .task_inventory()
 1286                    .cloned()
 1287                {
 1288                    project_subscriptions.push(cx.observe_in(
 1289                        &task_inventory,
 1290                        window,
 1291                        |editor, _, window, cx| {
 1292                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1293                        },
 1294                    ));
 1295                }
 1296            }
 1297        }
 1298
 1299        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1300
 1301        let inlay_hint_settings =
 1302            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1303        let focus_handle = cx.focus_handle();
 1304        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1305            .detach();
 1306        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1307            .detach();
 1308        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1309            .detach();
 1310        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1311            .detach();
 1312
 1313        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1314            Some(false)
 1315        } else {
 1316            None
 1317        };
 1318
 1319        let mut code_action_providers = Vec::new();
 1320        if let Some(project) = project.clone() {
 1321            get_uncommitted_diff_for_buffer(
 1322                &project,
 1323                buffer.read(cx).all_buffers(),
 1324                buffer.clone(),
 1325                cx,
 1326            );
 1327            code_action_providers.push(Rc::new(project) as Rc<_>);
 1328        }
 1329
 1330        let mut this = Self {
 1331            focus_handle,
 1332            show_cursor_when_unfocused: false,
 1333            last_focused_descendant: None,
 1334            buffer: buffer.clone(),
 1335            display_map: display_map.clone(),
 1336            selections,
 1337            scroll_manager: ScrollManager::new(cx),
 1338            columnar_selection_tail: None,
 1339            add_selections_state: None,
 1340            select_next_state: None,
 1341            select_prev_state: None,
 1342            selection_history: Default::default(),
 1343            autoclose_regions: Default::default(),
 1344            snippet_stack: Default::default(),
 1345            select_larger_syntax_node_stack: Vec::new(),
 1346            ime_transaction: Default::default(),
 1347            active_diagnostics: None,
 1348            soft_wrap_mode_override,
 1349            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1350            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1351            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1352            project,
 1353            blink_manager: blink_manager.clone(),
 1354            show_local_selections: true,
 1355            show_scrollbars: true,
 1356            mode,
 1357            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1358            show_gutter: mode == EditorMode::Full,
 1359            show_line_numbers: None,
 1360            use_relative_line_numbers: None,
 1361            show_git_diff_gutter: None,
 1362            show_code_actions: None,
 1363            show_runnables: None,
 1364            show_wrap_guides: None,
 1365            show_indent_guides,
 1366            placeholder_text: None,
 1367            highlight_order: 0,
 1368            highlighted_rows: HashMap::default(),
 1369            background_highlights: Default::default(),
 1370            gutter_highlights: TreeMap::default(),
 1371            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1372            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1373            nav_history: None,
 1374            context_menu: RefCell::new(None),
 1375            mouse_context_menu: None,
 1376            completion_tasks: Default::default(),
 1377            signature_help_state: SignatureHelpState::default(),
 1378            auto_signature_help: None,
 1379            find_all_references_task_sources: Vec::new(),
 1380            next_completion_id: 0,
 1381            next_inlay_id: 0,
 1382            code_action_providers,
 1383            available_code_actions: Default::default(),
 1384            code_actions_task: Default::default(),
 1385            document_highlights_task: Default::default(),
 1386            linked_editing_range_task: Default::default(),
 1387            pending_rename: Default::default(),
 1388            searchable: true,
 1389            cursor_shape: EditorSettings::get_global(cx)
 1390                .cursor_shape
 1391                .unwrap_or_default(),
 1392            current_line_highlight: None,
 1393            autoindent_mode: Some(AutoindentMode::EachLine),
 1394            collapse_matches: false,
 1395            workspace: None,
 1396            input_enabled: true,
 1397            use_modal_editing: mode == EditorMode::Full,
 1398            read_only: false,
 1399            use_autoclose: true,
 1400            use_auto_surround: true,
 1401            auto_replace_emoji_shortcode: false,
 1402            leader_peer_id: None,
 1403            remote_id: None,
 1404            hover_state: Default::default(),
 1405            pending_mouse_down: None,
 1406            hovered_link_state: Default::default(),
 1407            edit_prediction_provider: None,
 1408            active_inline_completion: None,
 1409            stale_inline_completion_in_menu: None,
 1410            edit_prediction_preview: EditPredictionPreview::Inactive,
 1411            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1412
 1413            gutter_hovered: false,
 1414            pixel_position_of_newest_cursor: None,
 1415            last_bounds: None,
 1416            last_position_map: None,
 1417            expect_bounds_change: None,
 1418            gutter_dimensions: GutterDimensions::default(),
 1419            style: None,
 1420            show_cursor_names: false,
 1421            hovered_cursors: Default::default(),
 1422            next_editor_action_id: EditorActionId::default(),
 1423            editor_actions: Rc::default(),
 1424            inline_completions_hidden_for_vim_mode: false,
 1425            show_inline_completions_override: None,
 1426            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1427            edit_prediction_settings: EditPredictionSettings::Disabled,
 1428            edit_prediction_cursor_on_leading_whitespace: false,
 1429            edit_prediction_requires_modifier_in_leading_space: true,
 1430            custom_context_menu: None,
 1431            show_git_blame_gutter: false,
 1432            show_git_blame_inline: false,
 1433            distinguish_unstaged_diff_hunks: false,
 1434            show_selection_menu: None,
 1435            show_git_blame_inline_delay_task: None,
 1436            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1437            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1438                .session
 1439                .restore_unsaved_buffers,
 1440            blame: None,
 1441            blame_subscription: None,
 1442            tasks: Default::default(),
 1443            _subscriptions: vec![
 1444                cx.observe(&buffer, Self::on_buffer_changed),
 1445                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1446                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1447                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1448                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1449                cx.observe_window_activation(window, |editor, window, cx| {
 1450                    let active = window.is_window_active();
 1451                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1452                        if active {
 1453                            blink_manager.enable(cx);
 1454                        } else {
 1455                            blink_manager.disable(cx);
 1456                        }
 1457                    });
 1458                }),
 1459            ],
 1460            tasks_update_task: None,
 1461            linked_edit_ranges: Default::default(),
 1462            in_project_search: false,
 1463            previous_search_ranges: None,
 1464            breadcrumb_header: None,
 1465            focused_block: None,
 1466            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1467            addons: HashMap::default(),
 1468            registered_buffers: HashMap::default(),
 1469            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1470            selection_mark_mode: false,
 1471            toggle_fold_multiple_buffers: Task::ready(()),
 1472            text_style_refinement: None,
 1473        };
 1474        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1475        this._subscriptions.extend(project_subscriptions);
 1476
 1477        this.end_selection(window, cx);
 1478        this.scroll_manager.show_scrollbar(window, cx);
 1479
 1480        if mode == EditorMode::Full {
 1481            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1482            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1483
 1484            if this.git_blame_inline_enabled {
 1485                this.git_blame_inline_enabled = true;
 1486                this.start_git_blame_inline(false, window, cx);
 1487            }
 1488
 1489            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1490                if let Some(project) = this.project.as_ref() {
 1491                    let lsp_store = project.read(cx).lsp_store();
 1492                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1493                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1494                    });
 1495                    this.registered_buffers
 1496                        .insert(buffer.read(cx).remote_id(), handle);
 1497                }
 1498            }
 1499        }
 1500
 1501        this.report_editor_event("Editor Opened", None, cx);
 1502        this
 1503    }
 1504
 1505    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1506        self.mouse_context_menu
 1507            .as_ref()
 1508            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1509    }
 1510
 1511    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1512        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1513    }
 1514
 1515    fn key_context_internal(
 1516        &self,
 1517        has_active_edit_prediction: bool,
 1518        window: &Window,
 1519        cx: &App,
 1520    ) -> KeyContext {
 1521        let mut key_context = KeyContext::new_with_defaults();
 1522        key_context.add("Editor");
 1523        let mode = match self.mode {
 1524            EditorMode::SingleLine { .. } => "single_line",
 1525            EditorMode::AutoHeight { .. } => "auto_height",
 1526            EditorMode::Full => "full",
 1527        };
 1528
 1529        if EditorSettings::jupyter_enabled(cx) {
 1530            key_context.add("jupyter");
 1531        }
 1532
 1533        key_context.set("mode", mode);
 1534        if self.pending_rename.is_some() {
 1535            key_context.add("renaming");
 1536        }
 1537
 1538        match self.context_menu.borrow().as_ref() {
 1539            Some(CodeContextMenu::Completions(_)) => {
 1540                key_context.add("menu");
 1541                key_context.add("showing_completions");
 1542            }
 1543            Some(CodeContextMenu::CodeActions(_)) => {
 1544                key_context.add("menu");
 1545                key_context.add("showing_code_actions")
 1546            }
 1547            None => {}
 1548        }
 1549
 1550        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1551        if !self.focus_handle(cx).contains_focused(window, cx)
 1552            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1553        {
 1554            for addon in self.addons.values() {
 1555                addon.extend_key_context(&mut key_context, cx)
 1556            }
 1557        }
 1558
 1559        if let Some(extension) = self
 1560            .buffer
 1561            .read(cx)
 1562            .as_singleton()
 1563            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1564        {
 1565            key_context.set("extension", extension.to_string());
 1566        }
 1567
 1568        if has_active_edit_prediction {
 1569            if self.edit_prediction_in_conflict() {
 1570                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1571            } else {
 1572                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1573                key_context.add("copilot_suggestion");
 1574            }
 1575        }
 1576
 1577        if self.selection_mark_mode {
 1578            key_context.add("selection_mode");
 1579        }
 1580
 1581        key_context
 1582    }
 1583
 1584    pub fn edit_prediction_in_conflict(&self) -> bool {
 1585        let showing_completions = self
 1586            .context_menu
 1587            .borrow()
 1588            .as_ref()
 1589            .map_or(false, |context| {
 1590                matches!(context, CodeContextMenu::Completions(_))
 1591            });
 1592
 1593        showing_completions
 1594            || self.edit_prediction_requires_modifier()
 1595            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1596            // bindings to insert tab characters.
 1597            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1598    }
 1599
 1600    pub fn accept_edit_prediction_keybind(
 1601        &self,
 1602        window: &Window,
 1603        cx: &App,
 1604    ) -> AcceptEditPredictionBinding {
 1605        let key_context = self.key_context_internal(true, window, cx);
 1606        let in_conflict = self.edit_prediction_in_conflict();
 1607        AcceptEditPredictionBinding(
 1608            window
 1609                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1610                .into_iter()
 1611                .filter(|binding| {
 1612                    !in_conflict
 1613                        || binding
 1614                            .keystrokes()
 1615                            .first()
 1616                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1617                })
 1618                .rev()
 1619                .next(),
 1620        )
 1621    }
 1622
 1623    pub fn new_file(
 1624        workspace: &mut Workspace,
 1625        _: &workspace::NewFile,
 1626        window: &mut Window,
 1627        cx: &mut Context<Workspace>,
 1628    ) {
 1629        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1630            "Failed to create buffer",
 1631            window,
 1632            cx,
 1633            |e, _, _| match e.error_code() {
 1634                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1635                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1636                e.error_tag("required").unwrap_or("the latest version")
 1637            )),
 1638                _ => None,
 1639            },
 1640        );
 1641    }
 1642
 1643    pub fn new_in_workspace(
 1644        workspace: &mut Workspace,
 1645        window: &mut Window,
 1646        cx: &mut Context<Workspace>,
 1647    ) -> Task<Result<Entity<Editor>>> {
 1648        let project = workspace.project().clone();
 1649        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1650
 1651        cx.spawn_in(window, |workspace, mut cx| async move {
 1652            let buffer = create.await?;
 1653            workspace.update_in(&mut cx, |workspace, window, cx| {
 1654                let editor =
 1655                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1656                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1657                editor
 1658            })
 1659        })
 1660    }
 1661
 1662    fn new_file_vertical(
 1663        workspace: &mut Workspace,
 1664        _: &workspace::NewFileSplitVertical,
 1665        window: &mut Window,
 1666        cx: &mut Context<Workspace>,
 1667    ) {
 1668        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1669    }
 1670
 1671    fn new_file_horizontal(
 1672        workspace: &mut Workspace,
 1673        _: &workspace::NewFileSplitHorizontal,
 1674        window: &mut Window,
 1675        cx: &mut Context<Workspace>,
 1676    ) {
 1677        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1678    }
 1679
 1680    fn new_file_in_direction(
 1681        workspace: &mut Workspace,
 1682        direction: SplitDirection,
 1683        window: &mut Window,
 1684        cx: &mut Context<Workspace>,
 1685    ) {
 1686        let project = workspace.project().clone();
 1687        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1688
 1689        cx.spawn_in(window, |workspace, mut cx| async move {
 1690            let buffer = create.await?;
 1691            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1692                workspace.split_item(
 1693                    direction,
 1694                    Box::new(
 1695                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1696                    ),
 1697                    window,
 1698                    cx,
 1699                )
 1700            })?;
 1701            anyhow::Ok(())
 1702        })
 1703        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1704            match e.error_code() {
 1705                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1706                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1707                e.error_tag("required").unwrap_or("the latest version")
 1708            )),
 1709                _ => None,
 1710            }
 1711        });
 1712    }
 1713
 1714    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1715        self.leader_peer_id
 1716    }
 1717
 1718    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1719        &self.buffer
 1720    }
 1721
 1722    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1723        self.workspace.as_ref()?.0.upgrade()
 1724    }
 1725
 1726    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1727        self.buffer().read(cx).title(cx)
 1728    }
 1729
 1730    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1731        let git_blame_gutter_max_author_length = self
 1732            .render_git_blame_gutter(cx)
 1733            .then(|| {
 1734                if let Some(blame) = self.blame.as_ref() {
 1735                    let max_author_length =
 1736                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1737                    Some(max_author_length)
 1738                } else {
 1739                    None
 1740                }
 1741            })
 1742            .flatten();
 1743
 1744        EditorSnapshot {
 1745            mode: self.mode,
 1746            show_gutter: self.show_gutter,
 1747            show_line_numbers: self.show_line_numbers,
 1748            show_git_diff_gutter: self.show_git_diff_gutter,
 1749            show_code_actions: self.show_code_actions,
 1750            show_runnables: self.show_runnables,
 1751            git_blame_gutter_max_author_length,
 1752            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1753            scroll_anchor: self.scroll_manager.anchor(),
 1754            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1755            placeholder_text: self.placeholder_text.clone(),
 1756            is_focused: self.focus_handle.is_focused(window),
 1757            current_line_highlight: self
 1758                .current_line_highlight
 1759                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1760            gutter_hovered: self.gutter_hovered,
 1761        }
 1762    }
 1763
 1764    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1765        self.buffer.read(cx).language_at(point, cx)
 1766    }
 1767
 1768    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1769        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1770    }
 1771
 1772    pub fn active_excerpt(
 1773        &self,
 1774        cx: &App,
 1775    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1776        self.buffer
 1777            .read(cx)
 1778            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1779    }
 1780
 1781    pub fn mode(&self) -> EditorMode {
 1782        self.mode
 1783    }
 1784
 1785    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1786        self.collaboration_hub.as_deref()
 1787    }
 1788
 1789    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1790        self.collaboration_hub = Some(hub);
 1791    }
 1792
 1793    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1794        self.in_project_search = in_project_search;
 1795    }
 1796
 1797    pub fn set_custom_context_menu(
 1798        &mut self,
 1799        f: impl 'static
 1800            + Fn(
 1801                &mut Self,
 1802                DisplayPoint,
 1803                &mut Window,
 1804                &mut Context<Self>,
 1805            ) -> Option<Entity<ui::ContextMenu>>,
 1806    ) {
 1807        self.custom_context_menu = Some(Box::new(f))
 1808    }
 1809
 1810    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1811        self.completion_provider = provider;
 1812    }
 1813
 1814    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1815        self.semantics_provider.clone()
 1816    }
 1817
 1818    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1819        self.semantics_provider = provider;
 1820    }
 1821
 1822    pub fn set_edit_prediction_provider<T>(
 1823        &mut self,
 1824        provider: Option<Entity<T>>,
 1825        window: &mut Window,
 1826        cx: &mut Context<Self>,
 1827    ) where
 1828        T: EditPredictionProvider,
 1829    {
 1830        self.edit_prediction_provider =
 1831            provider.map(|provider| RegisteredInlineCompletionProvider {
 1832                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1833                    if this.focus_handle.is_focused(window) {
 1834                        this.update_visible_inline_completion(window, cx);
 1835                    }
 1836                }),
 1837                provider: Arc::new(provider),
 1838            });
 1839        self.refresh_inline_completion(false, false, window, cx);
 1840    }
 1841
 1842    pub fn placeholder_text(&self) -> Option<&str> {
 1843        self.placeholder_text.as_deref()
 1844    }
 1845
 1846    pub fn set_placeholder_text(
 1847        &mut self,
 1848        placeholder_text: impl Into<Arc<str>>,
 1849        cx: &mut Context<Self>,
 1850    ) {
 1851        let placeholder_text = Some(placeholder_text.into());
 1852        if self.placeholder_text != placeholder_text {
 1853            self.placeholder_text = placeholder_text;
 1854            cx.notify();
 1855        }
 1856    }
 1857
 1858    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1859        self.cursor_shape = cursor_shape;
 1860
 1861        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1862        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1863
 1864        cx.notify();
 1865    }
 1866
 1867    pub fn set_current_line_highlight(
 1868        &mut self,
 1869        current_line_highlight: Option<CurrentLineHighlight>,
 1870    ) {
 1871        self.current_line_highlight = current_line_highlight;
 1872    }
 1873
 1874    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1875        self.collapse_matches = collapse_matches;
 1876    }
 1877
 1878    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1879        let buffers = self.buffer.read(cx).all_buffers();
 1880        let Some(lsp_store) = self.lsp_store(cx) else {
 1881            return;
 1882        };
 1883        lsp_store.update(cx, |lsp_store, cx| {
 1884            for buffer in buffers {
 1885                self.registered_buffers
 1886                    .entry(buffer.read(cx).remote_id())
 1887                    .or_insert_with(|| {
 1888                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1889                    });
 1890            }
 1891        })
 1892    }
 1893
 1894    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1895        if self.collapse_matches {
 1896            return range.start..range.start;
 1897        }
 1898        range.clone()
 1899    }
 1900
 1901    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1902        if self.display_map.read(cx).clip_at_line_ends != clip {
 1903            self.display_map
 1904                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1905        }
 1906    }
 1907
 1908    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1909        self.input_enabled = input_enabled;
 1910    }
 1911
 1912    pub fn set_inline_completions_hidden_for_vim_mode(
 1913        &mut self,
 1914        hidden: bool,
 1915        window: &mut Window,
 1916        cx: &mut Context<Self>,
 1917    ) {
 1918        if hidden != self.inline_completions_hidden_for_vim_mode {
 1919            self.inline_completions_hidden_for_vim_mode = hidden;
 1920            if hidden {
 1921                self.update_visible_inline_completion(window, cx);
 1922            } else {
 1923                self.refresh_inline_completion(true, false, window, cx);
 1924            }
 1925        }
 1926    }
 1927
 1928    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1929        self.menu_inline_completions_policy = value;
 1930    }
 1931
 1932    pub fn set_autoindent(&mut self, autoindent: bool) {
 1933        if autoindent {
 1934            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1935        } else {
 1936            self.autoindent_mode = None;
 1937        }
 1938    }
 1939
 1940    pub fn read_only(&self, cx: &App) -> bool {
 1941        self.read_only || self.buffer.read(cx).read_only()
 1942    }
 1943
 1944    pub fn set_read_only(&mut self, read_only: bool) {
 1945        self.read_only = read_only;
 1946    }
 1947
 1948    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1949        self.use_autoclose = autoclose;
 1950    }
 1951
 1952    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1953        self.use_auto_surround = auto_surround;
 1954    }
 1955
 1956    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1957        self.auto_replace_emoji_shortcode = auto_replace;
 1958    }
 1959
 1960    pub fn toggle_inline_completions(
 1961        &mut self,
 1962        _: &ToggleEditPrediction,
 1963        window: &mut Window,
 1964        cx: &mut Context<Self>,
 1965    ) {
 1966        if self.show_inline_completions_override.is_some() {
 1967            self.set_show_edit_predictions(None, window, cx);
 1968        } else {
 1969            let show_edit_predictions = !self.edit_predictions_enabled();
 1970            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 1971        }
 1972    }
 1973
 1974    pub fn set_show_edit_predictions(
 1975        &mut self,
 1976        show_edit_predictions: Option<bool>,
 1977        window: &mut Window,
 1978        cx: &mut Context<Self>,
 1979    ) {
 1980        self.show_inline_completions_override = show_edit_predictions;
 1981        self.refresh_inline_completion(false, true, window, cx);
 1982    }
 1983
 1984    fn inline_completions_disabled_in_scope(
 1985        &self,
 1986        buffer: &Entity<Buffer>,
 1987        buffer_position: language::Anchor,
 1988        cx: &App,
 1989    ) -> bool {
 1990        let snapshot = buffer.read(cx).snapshot();
 1991        let settings = snapshot.settings_at(buffer_position, cx);
 1992
 1993        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1994            return false;
 1995        };
 1996
 1997        scope.override_name().map_or(false, |scope_name| {
 1998            settings
 1999                .edit_predictions_disabled_in
 2000                .iter()
 2001                .any(|s| s == scope_name)
 2002        })
 2003    }
 2004
 2005    pub fn set_use_modal_editing(&mut self, to: bool) {
 2006        self.use_modal_editing = to;
 2007    }
 2008
 2009    pub fn use_modal_editing(&self) -> bool {
 2010        self.use_modal_editing
 2011    }
 2012
 2013    fn selections_did_change(
 2014        &mut self,
 2015        local: bool,
 2016        old_cursor_position: &Anchor,
 2017        show_completions: bool,
 2018        window: &mut Window,
 2019        cx: &mut Context<Self>,
 2020    ) {
 2021        window.invalidate_character_coordinates();
 2022
 2023        // Copy selections to primary selection buffer
 2024        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2025        if local {
 2026            let selections = self.selections.all::<usize>(cx);
 2027            let buffer_handle = self.buffer.read(cx).read(cx);
 2028
 2029            let mut text = String::new();
 2030            for (index, selection) in selections.iter().enumerate() {
 2031                let text_for_selection = buffer_handle
 2032                    .text_for_range(selection.start..selection.end)
 2033                    .collect::<String>();
 2034
 2035                text.push_str(&text_for_selection);
 2036                if index != selections.len() - 1 {
 2037                    text.push('\n');
 2038                }
 2039            }
 2040
 2041            if !text.is_empty() {
 2042                cx.write_to_primary(ClipboardItem::new_string(text));
 2043            }
 2044        }
 2045
 2046        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2047            self.buffer.update(cx, |buffer, cx| {
 2048                buffer.set_active_selections(
 2049                    &self.selections.disjoint_anchors(),
 2050                    self.selections.line_mode,
 2051                    self.cursor_shape,
 2052                    cx,
 2053                )
 2054            });
 2055        }
 2056        let display_map = self
 2057            .display_map
 2058            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2059        let buffer = &display_map.buffer_snapshot;
 2060        self.add_selections_state = None;
 2061        self.select_next_state = None;
 2062        self.select_prev_state = None;
 2063        self.select_larger_syntax_node_stack.clear();
 2064        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2065        self.snippet_stack
 2066            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2067        self.take_rename(false, window, cx);
 2068
 2069        let new_cursor_position = self.selections.newest_anchor().head();
 2070
 2071        self.push_to_nav_history(
 2072            *old_cursor_position,
 2073            Some(new_cursor_position.to_point(buffer)),
 2074            cx,
 2075        );
 2076
 2077        if local {
 2078            let new_cursor_position = self.selections.newest_anchor().head();
 2079            let mut context_menu = self.context_menu.borrow_mut();
 2080            let completion_menu = match context_menu.as_ref() {
 2081                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2082                _ => {
 2083                    *context_menu = None;
 2084                    None
 2085                }
 2086            };
 2087            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2088                if !self.registered_buffers.contains_key(&buffer_id) {
 2089                    if let Some(lsp_store) = self.lsp_store(cx) {
 2090                        lsp_store.update(cx, |lsp_store, cx| {
 2091                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2092                                return;
 2093                            };
 2094                            self.registered_buffers.insert(
 2095                                buffer_id,
 2096                                lsp_store.register_buffer_with_language_servers(&buffer, cx),
 2097                            );
 2098                        })
 2099                    }
 2100                }
 2101            }
 2102
 2103            if let Some(completion_menu) = completion_menu {
 2104                let cursor_position = new_cursor_position.to_offset(buffer);
 2105                let (word_range, kind) =
 2106                    buffer.surrounding_word(completion_menu.initial_position, true);
 2107                if kind == Some(CharKind::Word)
 2108                    && word_range.to_inclusive().contains(&cursor_position)
 2109                {
 2110                    let mut completion_menu = completion_menu.clone();
 2111                    drop(context_menu);
 2112
 2113                    let query = Self::completion_query(buffer, cursor_position);
 2114                    cx.spawn(move |this, mut cx| async move {
 2115                        completion_menu
 2116                            .filter(query.as_deref(), cx.background_executor().clone())
 2117                            .await;
 2118
 2119                        this.update(&mut cx, |this, cx| {
 2120                            let mut context_menu = this.context_menu.borrow_mut();
 2121                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2122                            else {
 2123                                return;
 2124                            };
 2125
 2126                            if menu.id > completion_menu.id {
 2127                                return;
 2128                            }
 2129
 2130                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2131                            drop(context_menu);
 2132                            cx.notify();
 2133                        })
 2134                    })
 2135                    .detach();
 2136
 2137                    if show_completions {
 2138                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2139                    }
 2140                } else {
 2141                    drop(context_menu);
 2142                    self.hide_context_menu(window, cx);
 2143                }
 2144            } else {
 2145                drop(context_menu);
 2146            }
 2147
 2148            hide_hover(self, cx);
 2149
 2150            if old_cursor_position.to_display_point(&display_map).row()
 2151                != new_cursor_position.to_display_point(&display_map).row()
 2152            {
 2153                self.available_code_actions.take();
 2154            }
 2155            self.refresh_code_actions(window, cx);
 2156            self.refresh_document_highlights(cx);
 2157            refresh_matching_bracket_highlights(self, window, cx);
 2158            self.update_visible_inline_completion(window, cx);
 2159            self.edit_prediction_requires_modifier_in_leading_space = true;
 2160            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2161            if self.git_blame_inline_enabled {
 2162                self.start_inline_blame_timer(window, cx);
 2163            }
 2164        }
 2165
 2166        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2167        cx.emit(EditorEvent::SelectionsChanged { local });
 2168
 2169        if self.selections.disjoint_anchors().len() == 1 {
 2170            cx.emit(SearchEvent::ActiveMatchChanged)
 2171        }
 2172        cx.notify();
 2173    }
 2174
 2175    pub fn change_selections<R>(
 2176        &mut self,
 2177        autoscroll: Option<Autoscroll>,
 2178        window: &mut Window,
 2179        cx: &mut Context<Self>,
 2180        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2181    ) -> R {
 2182        self.change_selections_inner(autoscroll, true, window, cx, change)
 2183    }
 2184
 2185    pub fn change_selections_inner<R>(
 2186        &mut self,
 2187        autoscroll: Option<Autoscroll>,
 2188        request_completions: bool,
 2189        window: &mut Window,
 2190        cx: &mut Context<Self>,
 2191        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2192    ) -> R {
 2193        let old_cursor_position = self.selections.newest_anchor().head();
 2194        self.push_to_selection_history();
 2195
 2196        let (changed, result) = self.selections.change_with(cx, change);
 2197
 2198        if changed {
 2199            if let Some(autoscroll) = autoscroll {
 2200                self.request_autoscroll(autoscroll, cx);
 2201            }
 2202            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2203
 2204            if self.should_open_signature_help_automatically(
 2205                &old_cursor_position,
 2206                self.signature_help_state.backspace_pressed(),
 2207                cx,
 2208            ) {
 2209                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2210            }
 2211            self.signature_help_state.set_backspace_pressed(false);
 2212        }
 2213
 2214        result
 2215    }
 2216
 2217    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2218    where
 2219        I: IntoIterator<Item = (Range<S>, T)>,
 2220        S: ToOffset,
 2221        T: Into<Arc<str>>,
 2222    {
 2223        if self.read_only(cx) {
 2224            return;
 2225        }
 2226
 2227        self.buffer
 2228            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2229    }
 2230
 2231    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2232    where
 2233        I: IntoIterator<Item = (Range<S>, T)>,
 2234        S: ToOffset,
 2235        T: Into<Arc<str>>,
 2236    {
 2237        if self.read_only(cx) {
 2238            return;
 2239        }
 2240
 2241        self.buffer.update(cx, |buffer, cx| {
 2242            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2243        });
 2244    }
 2245
 2246    pub fn edit_with_block_indent<I, S, T>(
 2247        &mut self,
 2248        edits: I,
 2249        original_indent_columns: Vec<u32>,
 2250        cx: &mut Context<Self>,
 2251    ) where
 2252        I: IntoIterator<Item = (Range<S>, T)>,
 2253        S: ToOffset,
 2254        T: Into<Arc<str>>,
 2255    {
 2256        if self.read_only(cx) {
 2257            return;
 2258        }
 2259
 2260        self.buffer.update(cx, |buffer, cx| {
 2261            buffer.edit(
 2262                edits,
 2263                Some(AutoindentMode::Block {
 2264                    original_indent_columns,
 2265                }),
 2266                cx,
 2267            )
 2268        });
 2269    }
 2270
 2271    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2272        self.hide_context_menu(window, cx);
 2273
 2274        match phase {
 2275            SelectPhase::Begin {
 2276                position,
 2277                add,
 2278                click_count,
 2279            } => self.begin_selection(position, add, click_count, window, cx),
 2280            SelectPhase::BeginColumnar {
 2281                position,
 2282                goal_column,
 2283                reset,
 2284            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2285            SelectPhase::Extend {
 2286                position,
 2287                click_count,
 2288            } => self.extend_selection(position, click_count, window, cx),
 2289            SelectPhase::Update {
 2290                position,
 2291                goal_column,
 2292                scroll_delta,
 2293            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2294            SelectPhase::End => self.end_selection(window, cx),
 2295        }
 2296    }
 2297
 2298    fn extend_selection(
 2299        &mut self,
 2300        position: DisplayPoint,
 2301        click_count: usize,
 2302        window: &mut Window,
 2303        cx: &mut Context<Self>,
 2304    ) {
 2305        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2306        let tail = self.selections.newest::<usize>(cx).tail();
 2307        self.begin_selection(position, false, click_count, window, cx);
 2308
 2309        let position = position.to_offset(&display_map, Bias::Left);
 2310        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2311
 2312        let mut pending_selection = self
 2313            .selections
 2314            .pending_anchor()
 2315            .expect("extend_selection not called with pending selection");
 2316        if position >= tail {
 2317            pending_selection.start = tail_anchor;
 2318        } else {
 2319            pending_selection.end = tail_anchor;
 2320            pending_selection.reversed = true;
 2321        }
 2322
 2323        let mut pending_mode = self.selections.pending_mode().unwrap();
 2324        match &mut pending_mode {
 2325            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2326            _ => {}
 2327        }
 2328
 2329        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2330            s.set_pending(pending_selection, pending_mode)
 2331        });
 2332    }
 2333
 2334    fn begin_selection(
 2335        &mut self,
 2336        position: DisplayPoint,
 2337        add: bool,
 2338        click_count: usize,
 2339        window: &mut Window,
 2340        cx: &mut Context<Self>,
 2341    ) {
 2342        if !self.focus_handle.is_focused(window) {
 2343            self.last_focused_descendant = None;
 2344            window.focus(&self.focus_handle);
 2345        }
 2346
 2347        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2348        let buffer = &display_map.buffer_snapshot;
 2349        let newest_selection = self.selections.newest_anchor().clone();
 2350        let position = display_map.clip_point(position, Bias::Left);
 2351
 2352        let start;
 2353        let end;
 2354        let mode;
 2355        let mut auto_scroll;
 2356        match click_count {
 2357            1 => {
 2358                start = buffer.anchor_before(position.to_point(&display_map));
 2359                end = start;
 2360                mode = SelectMode::Character;
 2361                auto_scroll = true;
 2362            }
 2363            2 => {
 2364                let range = movement::surrounding_word(&display_map, position);
 2365                start = buffer.anchor_before(range.start.to_point(&display_map));
 2366                end = buffer.anchor_before(range.end.to_point(&display_map));
 2367                mode = SelectMode::Word(start..end);
 2368                auto_scroll = true;
 2369            }
 2370            3 => {
 2371                let position = display_map
 2372                    .clip_point(position, Bias::Left)
 2373                    .to_point(&display_map);
 2374                let line_start = display_map.prev_line_boundary(position).0;
 2375                let next_line_start = buffer.clip_point(
 2376                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2377                    Bias::Left,
 2378                );
 2379                start = buffer.anchor_before(line_start);
 2380                end = buffer.anchor_before(next_line_start);
 2381                mode = SelectMode::Line(start..end);
 2382                auto_scroll = true;
 2383            }
 2384            _ => {
 2385                start = buffer.anchor_before(0);
 2386                end = buffer.anchor_before(buffer.len());
 2387                mode = SelectMode::All;
 2388                auto_scroll = false;
 2389            }
 2390        }
 2391        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2392
 2393        let point_to_delete: Option<usize> = {
 2394            let selected_points: Vec<Selection<Point>> =
 2395                self.selections.disjoint_in_range(start..end, cx);
 2396
 2397            if !add || click_count > 1 {
 2398                None
 2399            } else if !selected_points.is_empty() {
 2400                Some(selected_points[0].id)
 2401            } else {
 2402                let clicked_point_already_selected =
 2403                    self.selections.disjoint.iter().find(|selection| {
 2404                        selection.start.to_point(buffer) == start.to_point(buffer)
 2405                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2406                    });
 2407
 2408                clicked_point_already_selected.map(|selection| selection.id)
 2409            }
 2410        };
 2411
 2412        let selections_count = self.selections.count();
 2413
 2414        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2415            if let Some(point_to_delete) = point_to_delete {
 2416                s.delete(point_to_delete);
 2417
 2418                if selections_count == 1 {
 2419                    s.set_pending_anchor_range(start..end, mode);
 2420                }
 2421            } else {
 2422                if !add {
 2423                    s.clear_disjoint();
 2424                } else if click_count > 1 {
 2425                    s.delete(newest_selection.id)
 2426                }
 2427
 2428                s.set_pending_anchor_range(start..end, mode);
 2429            }
 2430        });
 2431    }
 2432
 2433    fn begin_columnar_selection(
 2434        &mut self,
 2435        position: DisplayPoint,
 2436        goal_column: u32,
 2437        reset: bool,
 2438        window: &mut Window,
 2439        cx: &mut Context<Self>,
 2440    ) {
 2441        if !self.focus_handle.is_focused(window) {
 2442            self.last_focused_descendant = None;
 2443            window.focus(&self.focus_handle);
 2444        }
 2445
 2446        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2447
 2448        if reset {
 2449            let pointer_position = display_map
 2450                .buffer_snapshot
 2451                .anchor_before(position.to_point(&display_map));
 2452
 2453            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2454                s.clear_disjoint();
 2455                s.set_pending_anchor_range(
 2456                    pointer_position..pointer_position,
 2457                    SelectMode::Character,
 2458                );
 2459            });
 2460        }
 2461
 2462        let tail = self.selections.newest::<Point>(cx).tail();
 2463        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2464
 2465        if !reset {
 2466            self.select_columns(
 2467                tail.to_display_point(&display_map),
 2468                position,
 2469                goal_column,
 2470                &display_map,
 2471                window,
 2472                cx,
 2473            );
 2474        }
 2475    }
 2476
 2477    fn update_selection(
 2478        &mut self,
 2479        position: DisplayPoint,
 2480        goal_column: u32,
 2481        scroll_delta: gpui::Point<f32>,
 2482        window: &mut Window,
 2483        cx: &mut Context<Self>,
 2484    ) {
 2485        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2486
 2487        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2488            let tail = tail.to_display_point(&display_map);
 2489            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2490        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2491            let buffer = self.buffer.read(cx).snapshot(cx);
 2492            let head;
 2493            let tail;
 2494            let mode = self.selections.pending_mode().unwrap();
 2495            match &mode {
 2496                SelectMode::Character => {
 2497                    head = position.to_point(&display_map);
 2498                    tail = pending.tail().to_point(&buffer);
 2499                }
 2500                SelectMode::Word(original_range) => {
 2501                    let original_display_range = original_range.start.to_display_point(&display_map)
 2502                        ..original_range.end.to_display_point(&display_map);
 2503                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2504                        ..original_display_range.end.to_point(&display_map);
 2505                    if movement::is_inside_word(&display_map, position)
 2506                        || original_display_range.contains(&position)
 2507                    {
 2508                        let word_range = movement::surrounding_word(&display_map, position);
 2509                        if word_range.start < original_display_range.start {
 2510                            head = word_range.start.to_point(&display_map);
 2511                        } else {
 2512                            head = word_range.end.to_point(&display_map);
 2513                        }
 2514                    } else {
 2515                        head = position.to_point(&display_map);
 2516                    }
 2517
 2518                    if head <= original_buffer_range.start {
 2519                        tail = original_buffer_range.end;
 2520                    } else {
 2521                        tail = original_buffer_range.start;
 2522                    }
 2523                }
 2524                SelectMode::Line(original_range) => {
 2525                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2526
 2527                    let position = display_map
 2528                        .clip_point(position, Bias::Left)
 2529                        .to_point(&display_map);
 2530                    let line_start = display_map.prev_line_boundary(position).0;
 2531                    let next_line_start = buffer.clip_point(
 2532                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2533                        Bias::Left,
 2534                    );
 2535
 2536                    if line_start < original_range.start {
 2537                        head = line_start
 2538                    } else {
 2539                        head = next_line_start
 2540                    }
 2541
 2542                    if head <= original_range.start {
 2543                        tail = original_range.end;
 2544                    } else {
 2545                        tail = original_range.start;
 2546                    }
 2547                }
 2548                SelectMode::All => {
 2549                    return;
 2550                }
 2551            };
 2552
 2553            if head < tail {
 2554                pending.start = buffer.anchor_before(head);
 2555                pending.end = buffer.anchor_before(tail);
 2556                pending.reversed = true;
 2557            } else {
 2558                pending.start = buffer.anchor_before(tail);
 2559                pending.end = buffer.anchor_before(head);
 2560                pending.reversed = false;
 2561            }
 2562
 2563            self.change_selections(None, window, cx, |s| {
 2564                s.set_pending(pending, mode);
 2565            });
 2566        } else {
 2567            log::error!("update_selection dispatched with no pending selection");
 2568            return;
 2569        }
 2570
 2571        self.apply_scroll_delta(scroll_delta, window, cx);
 2572        cx.notify();
 2573    }
 2574
 2575    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2576        self.columnar_selection_tail.take();
 2577        if self.selections.pending_anchor().is_some() {
 2578            let selections = self.selections.all::<usize>(cx);
 2579            self.change_selections(None, window, cx, |s| {
 2580                s.select(selections);
 2581                s.clear_pending();
 2582            });
 2583        }
 2584    }
 2585
 2586    fn select_columns(
 2587        &mut self,
 2588        tail: DisplayPoint,
 2589        head: DisplayPoint,
 2590        goal_column: u32,
 2591        display_map: &DisplaySnapshot,
 2592        window: &mut Window,
 2593        cx: &mut Context<Self>,
 2594    ) {
 2595        let start_row = cmp::min(tail.row(), head.row());
 2596        let end_row = cmp::max(tail.row(), head.row());
 2597        let start_column = cmp::min(tail.column(), goal_column);
 2598        let end_column = cmp::max(tail.column(), goal_column);
 2599        let reversed = start_column < tail.column();
 2600
 2601        let selection_ranges = (start_row.0..=end_row.0)
 2602            .map(DisplayRow)
 2603            .filter_map(|row| {
 2604                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2605                    let start = display_map
 2606                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2607                        .to_point(display_map);
 2608                    let end = display_map
 2609                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2610                        .to_point(display_map);
 2611                    if reversed {
 2612                        Some(end..start)
 2613                    } else {
 2614                        Some(start..end)
 2615                    }
 2616                } else {
 2617                    None
 2618                }
 2619            })
 2620            .collect::<Vec<_>>();
 2621
 2622        self.change_selections(None, window, cx, |s| {
 2623            s.select_ranges(selection_ranges);
 2624        });
 2625        cx.notify();
 2626    }
 2627
 2628    pub fn has_pending_nonempty_selection(&self) -> bool {
 2629        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2630            Some(Selection { start, end, .. }) => start != end,
 2631            None => false,
 2632        };
 2633
 2634        pending_nonempty_selection
 2635            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2636    }
 2637
 2638    pub fn has_pending_selection(&self) -> bool {
 2639        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2640    }
 2641
 2642    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2643        self.selection_mark_mode = false;
 2644
 2645        if self.clear_expanded_diff_hunks(cx) {
 2646            cx.notify();
 2647            return;
 2648        }
 2649        if self.dismiss_menus_and_popups(true, window, cx) {
 2650            return;
 2651        }
 2652
 2653        if self.mode == EditorMode::Full
 2654            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2655        {
 2656            return;
 2657        }
 2658
 2659        cx.propagate();
 2660    }
 2661
 2662    pub fn dismiss_menus_and_popups(
 2663        &mut self,
 2664        is_user_requested: bool,
 2665        window: &mut Window,
 2666        cx: &mut Context<Self>,
 2667    ) -> bool {
 2668        if self.take_rename(false, window, cx).is_some() {
 2669            return true;
 2670        }
 2671
 2672        if hide_hover(self, cx) {
 2673            return true;
 2674        }
 2675
 2676        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2677            return true;
 2678        }
 2679
 2680        if self.hide_context_menu(window, cx).is_some() {
 2681            return true;
 2682        }
 2683
 2684        if self.mouse_context_menu.take().is_some() {
 2685            return true;
 2686        }
 2687
 2688        if is_user_requested && self.discard_inline_completion(true, cx) {
 2689            return true;
 2690        }
 2691
 2692        if self.snippet_stack.pop().is_some() {
 2693            return true;
 2694        }
 2695
 2696        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2697            self.dismiss_diagnostics(cx);
 2698            return true;
 2699        }
 2700
 2701        false
 2702    }
 2703
 2704    fn linked_editing_ranges_for(
 2705        &self,
 2706        selection: Range<text::Anchor>,
 2707        cx: &App,
 2708    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2709        if self.linked_edit_ranges.is_empty() {
 2710            return None;
 2711        }
 2712        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2713            selection.end.buffer_id.and_then(|end_buffer_id| {
 2714                if selection.start.buffer_id != Some(end_buffer_id) {
 2715                    return None;
 2716                }
 2717                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2718                let snapshot = buffer.read(cx).snapshot();
 2719                self.linked_edit_ranges
 2720                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2721                    .map(|ranges| (ranges, snapshot, buffer))
 2722            })?;
 2723        use text::ToOffset as TO;
 2724        // find offset from the start of current range to current cursor position
 2725        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2726
 2727        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2728        let start_difference = start_offset - start_byte_offset;
 2729        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2730        let end_difference = end_offset - start_byte_offset;
 2731        // Current range has associated linked ranges.
 2732        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2733        for range in linked_ranges.iter() {
 2734            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2735            let end_offset = start_offset + end_difference;
 2736            let start_offset = start_offset + start_difference;
 2737            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2738                continue;
 2739            }
 2740            if self.selections.disjoint_anchor_ranges().any(|s| {
 2741                if s.start.buffer_id != selection.start.buffer_id
 2742                    || s.end.buffer_id != selection.end.buffer_id
 2743                {
 2744                    return false;
 2745                }
 2746                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2747                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2748            }) {
 2749                continue;
 2750            }
 2751            let start = buffer_snapshot.anchor_after(start_offset);
 2752            let end = buffer_snapshot.anchor_after(end_offset);
 2753            linked_edits
 2754                .entry(buffer.clone())
 2755                .or_default()
 2756                .push(start..end);
 2757        }
 2758        Some(linked_edits)
 2759    }
 2760
 2761    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2762        let text: Arc<str> = text.into();
 2763
 2764        if self.read_only(cx) {
 2765            return;
 2766        }
 2767
 2768        let selections = self.selections.all_adjusted(cx);
 2769        let mut bracket_inserted = false;
 2770        let mut edits = Vec::new();
 2771        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2772        let mut new_selections = Vec::with_capacity(selections.len());
 2773        let mut new_autoclose_regions = Vec::new();
 2774        let snapshot = self.buffer.read(cx).read(cx);
 2775
 2776        for (selection, autoclose_region) in
 2777            self.selections_with_autoclose_regions(selections, &snapshot)
 2778        {
 2779            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2780                // Determine if the inserted text matches the opening or closing
 2781                // bracket of any of this language's bracket pairs.
 2782                let mut bracket_pair = None;
 2783                let mut is_bracket_pair_start = false;
 2784                let mut is_bracket_pair_end = false;
 2785                if !text.is_empty() {
 2786                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2787                    //  and they are removing the character that triggered IME popup.
 2788                    for (pair, enabled) in scope.brackets() {
 2789                        if !pair.close && !pair.surround {
 2790                            continue;
 2791                        }
 2792
 2793                        if enabled && pair.start.ends_with(text.as_ref()) {
 2794                            let prefix_len = pair.start.len() - text.len();
 2795                            let preceding_text_matches_prefix = prefix_len == 0
 2796                                || (selection.start.column >= (prefix_len as u32)
 2797                                    && snapshot.contains_str_at(
 2798                                        Point::new(
 2799                                            selection.start.row,
 2800                                            selection.start.column - (prefix_len as u32),
 2801                                        ),
 2802                                        &pair.start[..prefix_len],
 2803                                    ));
 2804                            if preceding_text_matches_prefix {
 2805                                bracket_pair = Some(pair.clone());
 2806                                is_bracket_pair_start = true;
 2807                                break;
 2808                            }
 2809                        }
 2810                        if pair.end.as_str() == text.as_ref() {
 2811                            bracket_pair = Some(pair.clone());
 2812                            is_bracket_pair_end = true;
 2813                            break;
 2814                        }
 2815                    }
 2816                }
 2817
 2818                if let Some(bracket_pair) = bracket_pair {
 2819                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2820                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2821                    let auto_surround =
 2822                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2823                    if selection.is_empty() {
 2824                        if is_bracket_pair_start {
 2825                            // If the inserted text is a suffix of an opening bracket and the
 2826                            // selection is preceded by the rest of the opening bracket, then
 2827                            // insert the closing bracket.
 2828                            let following_text_allows_autoclose = snapshot
 2829                                .chars_at(selection.start)
 2830                                .next()
 2831                                .map_or(true, |c| scope.should_autoclose_before(c));
 2832
 2833                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2834                                && bracket_pair.start.len() == 1
 2835                            {
 2836                                let target = bracket_pair.start.chars().next().unwrap();
 2837                                let current_line_count = snapshot
 2838                                    .reversed_chars_at(selection.start)
 2839                                    .take_while(|&c| c != '\n')
 2840                                    .filter(|&c| c == target)
 2841                                    .count();
 2842                                current_line_count % 2 == 1
 2843                            } else {
 2844                                false
 2845                            };
 2846
 2847                            if autoclose
 2848                                && bracket_pair.close
 2849                                && following_text_allows_autoclose
 2850                                && !is_closing_quote
 2851                            {
 2852                                let anchor = snapshot.anchor_before(selection.end);
 2853                                new_selections.push((selection.map(|_| anchor), text.len()));
 2854                                new_autoclose_regions.push((
 2855                                    anchor,
 2856                                    text.len(),
 2857                                    selection.id,
 2858                                    bracket_pair.clone(),
 2859                                ));
 2860                                edits.push((
 2861                                    selection.range(),
 2862                                    format!("{}{}", text, bracket_pair.end).into(),
 2863                                ));
 2864                                bracket_inserted = true;
 2865                                continue;
 2866                            }
 2867                        }
 2868
 2869                        if let Some(region) = autoclose_region {
 2870                            // If the selection is followed by an auto-inserted closing bracket,
 2871                            // then don't insert that closing bracket again; just move the selection
 2872                            // past the closing bracket.
 2873                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2874                                && text.as_ref() == region.pair.end.as_str();
 2875                            if should_skip {
 2876                                let anchor = snapshot.anchor_after(selection.end);
 2877                                new_selections
 2878                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2879                                continue;
 2880                            }
 2881                        }
 2882
 2883                        let always_treat_brackets_as_autoclosed = snapshot
 2884                            .settings_at(selection.start, cx)
 2885                            .always_treat_brackets_as_autoclosed;
 2886                        if always_treat_brackets_as_autoclosed
 2887                            && is_bracket_pair_end
 2888                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2889                        {
 2890                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2891                            // and the inserted text is a closing bracket and the selection is followed
 2892                            // by the closing bracket then move the selection past the closing bracket.
 2893                            let anchor = snapshot.anchor_after(selection.end);
 2894                            new_selections.push((selection.map(|_| anchor), text.len()));
 2895                            continue;
 2896                        }
 2897                    }
 2898                    // If an opening bracket is 1 character long and is typed while
 2899                    // text is selected, then surround that text with the bracket pair.
 2900                    else if auto_surround
 2901                        && bracket_pair.surround
 2902                        && is_bracket_pair_start
 2903                        && bracket_pair.start.chars().count() == 1
 2904                    {
 2905                        edits.push((selection.start..selection.start, text.clone()));
 2906                        edits.push((
 2907                            selection.end..selection.end,
 2908                            bracket_pair.end.as_str().into(),
 2909                        ));
 2910                        bracket_inserted = true;
 2911                        new_selections.push((
 2912                            Selection {
 2913                                id: selection.id,
 2914                                start: snapshot.anchor_after(selection.start),
 2915                                end: snapshot.anchor_before(selection.end),
 2916                                reversed: selection.reversed,
 2917                                goal: selection.goal,
 2918                            },
 2919                            0,
 2920                        ));
 2921                        continue;
 2922                    }
 2923                }
 2924            }
 2925
 2926            if self.auto_replace_emoji_shortcode
 2927                && selection.is_empty()
 2928                && text.as_ref().ends_with(':')
 2929            {
 2930                if let Some(possible_emoji_short_code) =
 2931                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2932                {
 2933                    if !possible_emoji_short_code.is_empty() {
 2934                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2935                            let emoji_shortcode_start = Point::new(
 2936                                selection.start.row,
 2937                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2938                            );
 2939
 2940                            // Remove shortcode from buffer
 2941                            edits.push((
 2942                                emoji_shortcode_start..selection.start,
 2943                                "".to_string().into(),
 2944                            ));
 2945                            new_selections.push((
 2946                                Selection {
 2947                                    id: selection.id,
 2948                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2949                                    end: snapshot.anchor_before(selection.start),
 2950                                    reversed: selection.reversed,
 2951                                    goal: selection.goal,
 2952                                },
 2953                                0,
 2954                            ));
 2955
 2956                            // Insert emoji
 2957                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2958                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2959                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2960
 2961                            continue;
 2962                        }
 2963                    }
 2964                }
 2965            }
 2966
 2967            // If not handling any auto-close operation, then just replace the selected
 2968            // text with the given input and move the selection to the end of the
 2969            // newly inserted text.
 2970            let anchor = snapshot.anchor_after(selection.end);
 2971            if !self.linked_edit_ranges.is_empty() {
 2972                let start_anchor = snapshot.anchor_before(selection.start);
 2973
 2974                let is_word_char = text.chars().next().map_or(true, |char| {
 2975                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2976                    classifier.is_word(char)
 2977                });
 2978
 2979                if is_word_char {
 2980                    if let Some(ranges) = self
 2981                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2982                    {
 2983                        for (buffer, edits) in ranges {
 2984                            linked_edits
 2985                                .entry(buffer.clone())
 2986                                .or_default()
 2987                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2988                        }
 2989                    }
 2990                }
 2991            }
 2992
 2993            new_selections.push((selection.map(|_| anchor), 0));
 2994            edits.push((selection.start..selection.end, text.clone()));
 2995        }
 2996
 2997        drop(snapshot);
 2998
 2999        self.transact(window, cx, |this, window, cx| {
 3000            this.buffer.update(cx, |buffer, cx| {
 3001                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3002            });
 3003            for (buffer, edits) in linked_edits {
 3004                buffer.update(cx, |buffer, cx| {
 3005                    let snapshot = buffer.snapshot();
 3006                    let edits = edits
 3007                        .into_iter()
 3008                        .map(|(range, text)| {
 3009                            use text::ToPoint as TP;
 3010                            let end_point = TP::to_point(&range.end, &snapshot);
 3011                            let start_point = TP::to_point(&range.start, &snapshot);
 3012                            (start_point..end_point, text)
 3013                        })
 3014                        .sorted_by_key(|(range, _)| range.start)
 3015                        .collect::<Vec<_>>();
 3016                    buffer.edit(edits, None, cx);
 3017                })
 3018            }
 3019            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3020            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3021            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3022            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3023                .zip(new_selection_deltas)
 3024                .map(|(selection, delta)| Selection {
 3025                    id: selection.id,
 3026                    start: selection.start + delta,
 3027                    end: selection.end + delta,
 3028                    reversed: selection.reversed,
 3029                    goal: SelectionGoal::None,
 3030                })
 3031                .collect::<Vec<_>>();
 3032
 3033            let mut i = 0;
 3034            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3035                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3036                let start = map.buffer_snapshot.anchor_before(position);
 3037                let end = map.buffer_snapshot.anchor_after(position);
 3038                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3039                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3040                        Ordering::Less => i += 1,
 3041                        Ordering::Greater => break,
 3042                        Ordering::Equal => {
 3043                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3044                                Ordering::Less => i += 1,
 3045                                Ordering::Equal => break,
 3046                                Ordering::Greater => break,
 3047                            }
 3048                        }
 3049                    }
 3050                }
 3051                this.autoclose_regions.insert(
 3052                    i,
 3053                    AutocloseRegion {
 3054                        selection_id,
 3055                        range: start..end,
 3056                        pair,
 3057                    },
 3058                );
 3059            }
 3060
 3061            let had_active_inline_completion = this.has_active_inline_completion();
 3062            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3063                s.select(new_selections)
 3064            });
 3065
 3066            if !bracket_inserted {
 3067                if let Some(on_type_format_task) =
 3068                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3069                {
 3070                    on_type_format_task.detach_and_log_err(cx);
 3071                }
 3072            }
 3073
 3074            let editor_settings = EditorSettings::get_global(cx);
 3075            if bracket_inserted
 3076                && (editor_settings.auto_signature_help
 3077                    || editor_settings.show_signature_help_after_edits)
 3078            {
 3079                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3080            }
 3081
 3082            let trigger_in_words =
 3083                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3084            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3085            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3086            this.refresh_inline_completion(true, false, window, cx);
 3087        });
 3088    }
 3089
 3090    fn find_possible_emoji_shortcode_at_position(
 3091        snapshot: &MultiBufferSnapshot,
 3092        position: Point,
 3093    ) -> Option<String> {
 3094        let mut chars = Vec::new();
 3095        let mut found_colon = false;
 3096        for char in snapshot.reversed_chars_at(position).take(100) {
 3097            // Found a possible emoji shortcode in the middle of the buffer
 3098            if found_colon {
 3099                if char.is_whitespace() {
 3100                    chars.reverse();
 3101                    return Some(chars.iter().collect());
 3102                }
 3103                // If the previous character is not a whitespace, we are in the middle of a word
 3104                // and we only want to complete the shortcode if the word is made up of other emojis
 3105                let mut containing_word = String::new();
 3106                for ch in snapshot
 3107                    .reversed_chars_at(position)
 3108                    .skip(chars.len() + 1)
 3109                    .take(100)
 3110                {
 3111                    if ch.is_whitespace() {
 3112                        break;
 3113                    }
 3114                    containing_word.push(ch);
 3115                }
 3116                let containing_word = containing_word.chars().rev().collect::<String>();
 3117                if util::word_consists_of_emojis(containing_word.as_str()) {
 3118                    chars.reverse();
 3119                    return Some(chars.iter().collect());
 3120                }
 3121            }
 3122
 3123            if char.is_whitespace() || !char.is_ascii() {
 3124                return None;
 3125            }
 3126            if char == ':' {
 3127                found_colon = true;
 3128            } else {
 3129                chars.push(char);
 3130            }
 3131        }
 3132        // Found a possible emoji shortcode at the beginning of the buffer
 3133        chars.reverse();
 3134        Some(chars.iter().collect())
 3135    }
 3136
 3137    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3138        self.transact(window, cx, |this, window, cx| {
 3139            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3140                let selections = this.selections.all::<usize>(cx);
 3141                let multi_buffer = this.buffer.read(cx);
 3142                let buffer = multi_buffer.snapshot(cx);
 3143                selections
 3144                    .iter()
 3145                    .map(|selection| {
 3146                        let start_point = selection.start.to_point(&buffer);
 3147                        let mut indent =
 3148                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3149                        indent.len = cmp::min(indent.len, start_point.column);
 3150                        let start = selection.start;
 3151                        let end = selection.end;
 3152                        let selection_is_empty = start == end;
 3153                        let language_scope = buffer.language_scope_at(start);
 3154                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3155                            &language_scope
 3156                        {
 3157                            let leading_whitespace_len = buffer
 3158                                .reversed_chars_at(start)
 3159                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3160                                .map(|c| c.len_utf8())
 3161                                .sum::<usize>();
 3162
 3163                            let trailing_whitespace_len = buffer
 3164                                .chars_at(end)
 3165                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3166                                .map(|c| c.len_utf8())
 3167                                .sum::<usize>();
 3168
 3169                            let insert_extra_newline =
 3170                                language.brackets().any(|(pair, enabled)| {
 3171                                    let pair_start = pair.start.trim_end();
 3172                                    let pair_end = pair.end.trim_start();
 3173
 3174                                    enabled
 3175                                        && pair.newline
 3176                                        && buffer.contains_str_at(
 3177                                            end + trailing_whitespace_len,
 3178                                            pair_end,
 3179                                        )
 3180                                        && buffer.contains_str_at(
 3181                                            (start - leading_whitespace_len)
 3182                                                .saturating_sub(pair_start.len()),
 3183                                            pair_start,
 3184                                        )
 3185                                });
 3186
 3187                            // Comment extension on newline is allowed only for cursor selections
 3188                            let comment_delimiter = maybe!({
 3189                                if !selection_is_empty {
 3190                                    return None;
 3191                                }
 3192
 3193                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3194                                    return None;
 3195                                }
 3196
 3197                                let delimiters = language.line_comment_prefixes();
 3198                                let max_len_of_delimiter =
 3199                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3200                                let (snapshot, range) =
 3201                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3202
 3203                                let mut index_of_first_non_whitespace = 0;
 3204                                let comment_candidate = snapshot
 3205                                    .chars_for_range(range)
 3206                                    .skip_while(|c| {
 3207                                        let should_skip = c.is_whitespace();
 3208                                        if should_skip {
 3209                                            index_of_first_non_whitespace += 1;
 3210                                        }
 3211                                        should_skip
 3212                                    })
 3213                                    .take(max_len_of_delimiter)
 3214                                    .collect::<String>();
 3215                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3216                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3217                                })?;
 3218                                let cursor_is_placed_after_comment_marker =
 3219                                    index_of_first_non_whitespace + comment_prefix.len()
 3220                                        <= start_point.column as usize;
 3221                                if cursor_is_placed_after_comment_marker {
 3222                                    Some(comment_prefix.clone())
 3223                                } else {
 3224                                    None
 3225                                }
 3226                            });
 3227                            (comment_delimiter, insert_extra_newline)
 3228                        } else {
 3229                            (None, false)
 3230                        };
 3231
 3232                        let capacity_for_delimiter = comment_delimiter
 3233                            .as_deref()
 3234                            .map(str::len)
 3235                            .unwrap_or_default();
 3236                        let mut new_text =
 3237                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3238                        new_text.push('\n');
 3239                        new_text.extend(indent.chars());
 3240                        if let Some(delimiter) = &comment_delimiter {
 3241                            new_text.push_str(delimiter);
 3242                        }
 3243                        if insert_extra_newline {
 3244                            new_text = new_text.repeat(2);
 3245                        }
 3246
 3247                        let anchor = buffer.anchor_after(end);
 3248                        let new_selection = selection.map(|_| anchor);
 3249                        (
 3250                            (start..end, new_text),
 3251                            (insert_extra_newline, new_selection),
 3252                        )
 3253                    })
 3254                    .unzip()
 3255            };
 3256
 3257            this.edit_with_autoindent(edits, cx);
 3258            let buffer = this.buffer.read(cx).snapshot(cx);
 3259            let new_selections = selection_fixup_info
 3260                .into_iter()
 3261                .map(|(extra_newline_inserted, new_selection)| {
 3262                    let mut cursor = new_selection.end.to_point(&buffer);
 3263                    if extra_newline_inserted {
 3264                        cursor.row -= 1;
 3265                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3266                    }
 3267                    new_selection.map(|_| cursor)
 3268                })
 3269                .collect();
 3270
 3271            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3272                s.select(new_selections)
 3273            });
 3274            this.refresh_inline_completion(true, false, window, cx);
 3275        });
 3276    }
 3277
 3278    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3279        let buffer = self.buffer.read(cx);
 3280        let snapshot = buffer.snapshot(cx);
 3281
 3282        let mut edits = Vec::new();
 3283        let mut rows = Vec::new();
 3284
 3285        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3286            let cursor = selection.head();
 3287            let row = cursor.row;
 3288
 3289            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3290
 3291            let newline = "\n".to_string();
 3292            edits.push((start_of_line..start_of_line, newline));
 3293
 3294            rows.push(row + rows_inserted as u32);
 3295        }
 3296
 3297        self.transact(window, cx, |editor, window, cx| {
 3298            editor.edit(edits, cx);
 3299
 3300            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3301                let mut index = 0;
 3302                s.move_cursors_with(|map, _, _| {
 3303                    let row = rows[index];
 3304                    index += 1;
 3305
 3306                    let point = Point::new(row, 0);
 3307                    let boundary = map.next_line_boundary(point).1;
 3308                    let clipped = map.clip_point(boundary, Bias::Left);
 3309
 3310                    (clipped, SelectionGoal::None)
 3311                });
 3312            });
 3313
 3314            let mut indent_edits = Vec::new();
 3315            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3316            for row in rows {
 3317                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3318                for (row, indent) in indents {
 3319                    if indent.len == 0 {
 3320                        continue;
 3321                    }
 3322
 3323                    let text = match indent.kind {
 3324                        IndentKind::Space => " ".repeat(indent.len as usize),
 3325                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3326                    };
 3327                    let point = Point::new(row.0, 0);
 3328                    indent_edits.push((point..point, text));
 3329                }
 3330            }
 3331            editor.edit(indent_edits, cx);
 3332        });
 3333    }
 3334
 3335    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3336        let buffer = self.buffer.read(cx);
 3337        let snapshot = buffer.snapshot(cx);
 3338
 3339        let mut edits = Vec::new();
 3340        let mut rows = Vec::new();
 3341        let mut rows_inserted = 0;
 3342
 3343        for selection in self.selections.all_adjusted(cx) {
 3344            let cursor = selection.head();
 3345            let row = cursor.row;
 3346
 3347            let point = Point::new(row + 1, 0);
 3348            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3349
 3350            let newline = "\n".to_string();
 3351            edits.push((start_of_line..start_of_line, newline));
 3352
 3353            rows_inserted += 1;
 3354            rows.push(row + rows_inserted);
 3355        }
 3356
 3357        self.transact(window, cx, |editor, window, cx| {
 3358            editor.edit(edits, cx);
 3359
 3360            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3361                let mut index = 0;
 3362                s.move_cursors_with(|map, _, _| {
 3363                    let row = rows[index];
 3364                    index += 1;
 3365
 3366                    let point = Point::new(row, 0);
 3367                    let boundary = map.next_line_boundary(point).1;
 3368                    let clipped = map.clip_point(boundary, Bias::Left);
 3369
 3370                    (clipped, SelectionGoal::None)
 3371                });
 3372            });
 3373
 3374            let mut indent_edits = Vec::new();
 3375            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3376            for row in rows {
 3377                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3378                for (row, indent) in indents {
 3379                    if indent.len == 0 {
 3380                        continue;
 3381                    }
 3382
 3383                    let text = match indent.kind {
 3384                        IndentKind::Space => " ".repeat(indent.len as usize),
 3385                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3386                    };
 3387                    let point = Point::new(row.0, 0);
 3388                    indent_edits.push((point..point, text));
 3389                }
 3390            }
 3391            editor.edit(indent_edits, cx);
 3392        });
 3393    }
 3394
 3395    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3396        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3397            original_indent_columns: Vec::new(),
 3398        });
 3399        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3400    }
 3401
 3402    fn insert_with_autoindent_mode(
 3403        &mut self,
 3404        text: &str,
 3405        autoindent_mode: Option<AutoindentMode>,
 3406        window: &mut Window,
 3407        cx: &mut Context<Self>,
 3408    ) {
 3409        if self.read_only(cx) {
 3410            return;
 3411        }
 3412
 3413        let text: Arc<str> = text.into();
 3414        self.transact(window, cx, |this, window, cx| {
 3415            let old_selections = this.selections.all_adjusted(cx);
 3416            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3417                let anchors = {
 3418                    let snapshot = buffer.read(cx);
 3419                    old_selections
 3420                        .iter()
 3421                        .map(|s| {
 3422                            let anchor = snapshot.anchor_after(s.head());
 3423                            s.map(|_| anchor)
 3424                        })
 3425                        .collect::<Vec<_>>()
 3426                };
 3427                buffer.edit(
 3428                    old_selections
 3429                        .iter()
 3430                        .map(|s| (s.start..s.end, text.clone())),
 3431                    autoindent_mode,
 3432                    cx,
 3433                );
 3434                anchors
 3435            });
 3436
 3437            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3438                s.select_anchors(selection_anchors);
 3439            });
 3440
 3441            cx.notify();
 3442        });
 3443    }
 3444
 3445    fn trigger_completion_on_input(
 3446        &mut self,
 3447        text: &str,
 3448        trigger_in_words: bool,
 3449        window: &mut Window,
 3450        cx: &mut Context<Self>,
 3451    ) {
 3452        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3453            self.show_completions(
 3454                &ShowCompletions {
 3455                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3456                },
 3457                window,
 3458                cx,
 3459            );
 3460        } else {
 3461            self.hide_context_menu(window, cx);
 3462        }
 3463    }
 3464
 3465    fn is_completion_trigger(
 3466        &self,
 3467        text: &str,
 3468        trigger_in_words: bool,
 3469        cx: &mut Context<Self>,
 3470    ) -> bool {
 3471        let position = self.selections.newest_anchor().head();
 3472        let multibuffer = self.buffer.read(cx);
 3473        let Some(buffer) = position
 3474            .buffer_id
 3475            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3476        else {
 3477            return false;
 3478        };
 3479
 3480        if let Some(completion_provider) = &self.completion_provider {
 3481            completion_provider.is_completion_trigger(
 3482                &buffer,
 3483                position.text_anchor,
 3484                text,
 3485                trigger_in_words,
 3486                cx,
 3487            )
 3488        } else {
 3489            false
 3490        }
 3491    }
 3492
 3493    /// If any empty selections is touching the start of its innermost containing autoclose
 3494    /// region, expand it to select the brackets.
 3495    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3496        let selections = self.selections.all::<usize>(cx);
 3497        let buffer = self.buffer.read(cx).read(cx);
 3498        let new_selections = self
 3499            .selections_with_autoclose_regions(selections, &buffer)
 3500            .map(|(mut selection, region)| {
 3501                if !selection.is_empty() {
 3502                    return selection;
 3503                }
 3504
 3505                if let Some(region) = region {
 3506                    let mut range = region.range.to_offset(&buffer);
 3507                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3508                        range.start -= region.pair.start.len();
 3509                        if buffer.contains_str_at(range.start, &region.pair.start)
 3510                            && buffer.contains_str_at(range.end, &region.pair.end)
 3511                        {
 3512                            range.end += region.pair.end.len();
 3513                            selection.start = range.start;
 3514                            selection.end = range.end;
 3515
 3516                            return selection;
 3517                        }
 3518                    }
 3519                }
 3520
 3521                let always_treat_brackets_as_autoclosed = buffer
 3522                    .settings_at(selection.start, cx)
 3523                    .always_treat_brackets_as_autoclosed;
 3524
 3525                if !always_treat_brackets_as_autoclosed {
 3526                    return selection;
 3527                }
 3528
 3529                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3530                    for (pair, enabled) in scope.brackets() {
 3531                        if !enabled || !pair.close {
 3532                            continue;
 3533                        }
 3534
 3535                        if buffer.contains_str_at(selection.start, &pair.end) {
 3536                            let pair_start_len = pair.start.len();
 3537                            if buffer.contains_str_at(
 3538                                selection.start.saturating_sub(pair_start_len),
 3539                                &pair.start,
 3540                            ) {
 3541                                selection.start -= pair_start_len;
 3542                                selection.end += pair.end.len();
 3543
 3544                                return selection;
 3545                            }
 3546                        }
 3547                    }
 3548                }
 3549
 3550                selection
 3551            })
 3552            .collect();
 3553
 3554        drop(buffer);
 3555        self.change_selections(None, window, cx, |selections| {
 3556            selections.select(new_selections)
 3557        });
 3558    }
 3559
 3560    /// Iterate the given selections, and for each one, find the smallest surrounding
 3561    /// autoclose region. This uses the ordering of the selections and the autoclose
 3562    /// regions to avoid repeated comparisons.
 3563    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3564        &'a self,
 3565        selections: impl IntoIterator<Item = Selection<D>>,
 3566        buffer: &'a MultiBufferSnapshot,
 3567    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3568        let mut i = 0;
 3569        let mut regions = self.autoclose_regions.as_slice();
 3570        selections.into_iter().map(move |selection| {
 3571            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3572
 3573            let mut enclosing = None;
 3574            while let Some(pair_state) = regions.get(i) {
 3575                if pair_state.range.end.to_offset(buffer) < range.start {
 3576                    regions = &regions[i + 1..];
 3577                    i = 0;
 3578                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3579                    break;
 3580                } else {
 3581                    if pair_state.selection_id == selection.id {
 3582                        enclosing = Some(pair_state);
 3583                    }
 3584                    i += 1;
 3585                }
 3586            }
 3587
 3588            (selection, enclosing)
 3589        })
 3590    }
 3591
 3592    /// Remove any autoclose regions that no longer contain their selection.
 3593    fn invalidate_autoclose_regions(
 3594        &mut self,
 3595        mut selections: &[Selection<Anchor>],
 3596        buffer: &MultiBufferSnapshot,
 3597    ) {
 3598        self.autoclose_regions.retain(|state| {
 3599            let mut i = 0;
 3600            while let Some(selection) = selections.get(i) {
 3601                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3602                    selections = &selections[1..];
 3603                    continue;
 3604                }
 3605                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3606                    break;
 3607                }
 3608                if selection.id == state.selection_id {
 3609                    return true;
 3610                } else {
 3611                    i += 1;
 3612                }
 3613            }
 3614            false
 3615        });
 3616    }
 3617
 3618    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3619        let offset = position.to_offset(buffer);
 3620        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3621        if offset > word_range.start && kind == Some(CharKind::Word) {
 3622            Some(
 3623                buffer
 3624                    .text_for_range(word_range.start..offset)
 3625                    .collect::<String>(),
 3626            )
 3627        } else {
 3628            None
 3629        }
 3630    }
 3631
 3632    pub fn toggle_inlay_hints(
 3633        &mut self,
 3634        _: &ToggleInlayHints,
 3635        _: &mut Window,
 3636        cx: &mut Context<Self>,
 3637    ) {
 3638        self.refresh_inlay_hints(
 3639            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3640            cx,
 3641        );
 3642    }
 3643
 3644    pub fn inlay_hints_enabled(&self) -> bool {
 3645        self.inlay_hint_cache.enabled
 3646    }
 3647
 3648    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3649        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3650            return;
 3651        }
 3652
 3653        let reason_description = reason.description();
 3654        let ignore_debounce = matches!(
 3655            reason,
 3656            InlayHintRefreshReason::SettingsChange(_)
 3657                | InlayHintRefreshReason::Toggle(_)
 3658                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3659        );
 3660        let (invalidate_cache, required_languages) = match reason {
 3661            InlayHintRefreshReason::Toggle(enabled) => {
 3662                self.inlay_hint_cache.enabled = enabled;
 3663                if enabled {
 3664                    (InvalidationStrategy::RefreshRequested, None)
 3665                } else {
 3666                    self.inlay_hint_cache.clear();
 3667                    self.splice_inlays(
 3668                        &self
 3669                            .visible_inlay_hints(cx)
 3670                            .iter()
 3671                            .map(|inlay| inlay.id)
 3672                            .collect::<Vec<InlayId>>(),
 3673                        Vec::new(),
 3674                        cx,
 3675                    );
 3676                    return;
 3677                }
 3678            }
 3679            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3680                match self.inlay_hint_cache.update_settings(
 3681                    &self.buffer,
 3682                    new_settings,
 3683                    self.visible_inlay_hints(cx),
 3684                    cx,
 3685                ) {
 3686                    ControlFlow::Break(Some(InlaySplice {
 3687                        to_remove,
 3688                        to_insert,
 3689                    })) => {
 3690                        self.splice_inlays(&to_remove, to_insert, cx);
 3691                        return;
 3692                    }
 3693                    ControlFlow::Break(None) => return,
 3694                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3695                }
 3696            }
 3697            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3698                if let Some(InlaySplice {
 3699                    to_remove,
 3700                    to_insert,
 3701                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3702                {
 3703                    self.splice_inlays(&to_remove, to_insert, cx);
 3704                }
 3705                return;
 3706            }
 3707            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3708            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3709                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3710            }
 3711            InlayHintRefreshReason::RefreshRequested => {
 3712                (InvalidationStrategy::RefreshRequested, None)
 3713            }
 3714        };
 3715
 3716        if let Some(InlaySplice {
 3717            to_remove,
 3718            to_insert,
 3719        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3720            reason_description,
 3721            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3722            invalidate_cache,
 3723            ignore_debounce,
 3724            cx,
 3725        ) {
 3726            self.splice_inlays(&to_remove, to_insert, cx);
 3727        }
 3728    }
 3729
 3730    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3731        self.display_map
 3732            .read(cx)
 3733            .current_inlays()
 3734            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3735            .cloned()
 3736            .collect()
 3737    }
 3738
 3739    pub fn excerpts_for_inlay_hints_query(
 3740        &self,
 3741        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3742        cx: &mut Context<Editor>,
 3743    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3744        let Some(project) = self.project.as_ref() else {
 3745            return HashMap::default();
 3746        };
 3747        let project = project.read(cx);
 3748        let multi_buffer = self.buffer().read(cx);
 3749        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3750        let multi_buffer_visible_start = self
 3751            .scroll_manager
 3752            .anchor()
 3753            .anchor
 3754            .to_point(&multi_buffer_snapshot);
 3755        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3756            multi_buffer_visible_start
 3757                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3758            Bias::Left,
 3759        );
 3760        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3761        multi_buffer_snapshot
 3762            .range_to_buffer_ranges(multi_buffer_visible_range)
 3763            .into_iter()
 3764            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3765            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3766                let buffer_file = project::File::from_dyn(buffer.file())?;
 3767                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3768                let worktree_entry = buffer_worktree
 3769                    .read(cx)
 3770                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3771                if worktree_entry.is_ignored {
 3772                    return None;
 3773                }
 3774
 3775                let language = buffer.language()?;
 3776                if let Some(restrict_to_languages) = restrict_to_languages {
 3777                    if !restrict_to_languages.contains(language) {
 3778                        return None;
 3779                    }
 3780                }
 3781                Some((
 3782                    excerpt_id,
 3783                    (
 3784                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3785                        buffer.version().clone(),
 3786                        excerpt_visible_range,
 3787                    ),
 3788                ))
 3789            })
 3790            .collect()
 3791    }
 3792
 3793    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3794        TextLayoutDetails {
 3795            text_system: window.text_system().clone(),
 3796            editor_style: self.style.clone().unwrap(),
 3797            rem_size: window.rem_size(),
 3798            scroll_anchor: self.scroll_manager.anchor(),
 3799            visible_rows: self.visible_line_count(),
 3800            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3801        }
 3802    }
 3803
 3804    pub fn splice_inlays(
 3805        &self,
 3806        to_remove: &[InlayId],
 3807        to_insert: Vec<Inlay>,
 3808        cx: &mut Context<Self>,
 3809    ) {
 3810        self.display_map.update(cx, |display_map, cx| {
 3811            display_map.splice_inlays(to_remove, to_insert, cx)
 3812        });
 3813        cx.notify();
 3814    }
 3815
 3816    fn trigger_on_type_formatting(
 3817        &self,
 3818        input: String,
 3819        window: &mut Window,
 3820        cx: &mut Context<Self>,
 3821    ) -> Option<Task<Result<()>>> {
 3822        if input.len() != 1 {
 3823            return None;
 3824        }
 3825
 3826        let project = self.project.as_ref()?;
 3827        let position = self.selections.newest_anchor().head();
 3828        let (buffer, buffer_position) = self
 3829            .buffer
 3830            .read(cx)
 3831            .text_anchor_for_position(position, cx)?;
 3832
 3833        let settings = language_settings::language_settings(
 3834            buffer
 3835                .read(cx)
 3836                .language_at(buffer_position)
 3837                .map(|l| l.name()),
 3838            buffer.read(cx).file(),
 3839            cx,
 3840        );
 3841        if !settings.use_on_type_format {
 3842            return None;
 3843        }
 3844
 3845        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3846        // hence we do LSP request & edit on host side only — add formats to host's history.
 3847        let push_to_lsp_host_history = true;
 3848        // If this is not the host, append its history with new edits.
 3849        let push_to_client_history = project.read(cx).is_via_collab();
 3850
 3851        let on_type_formatting = project.update(cx, |project, cx| {
 3852            project.on_type_format(
 3853                buffer.clone(),
 3854                buffer_position,
 3855                input,
 3856                push_to_lsp_host_history,
 3857                cx,
 3858            )
 3859        });
 3860        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3861            if let Some(transaction) = on_type_formatting.await? {
 3862                if push_to_client_history {
 3863                    buffer
 3864                        .update(&mut cx, |buffer, _| {
 3865                            buffer.push_transaction(transaction, Instant::now());
 3866                        })
 3867                        .ok();
 3868                }
 3869                editor.update(&mut cx, |editor, cx| {
 3870                    editor.refresh_document_highlights(cx);
 3871                })?;
 3872            }
 3873            Ok(())
 3874        }))
 3875    }
 3876
 3877    pub fn show_completions(
 3878        &mut self,
 3879        options: &ShowCompletions,
 3880        window: &mut Window,
 3881        cx: &mut Context<Self>,
 3882    ) {
 3883        if self.pending_rename.is_some() {
 3884            return;
 3885        }
 3886
 3887        let Some(provider) = self.completion_provider.as_ref() else {
 3888            return;
 3889        };
 3890
 3891        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3892            return;
 3893        }
 3894
 3895        let position = self.selections.newest_anchor().head();
 3896        if position.diff_base_anchor.is_some() {
 3897            return;
 3898        }
 3899        let (buffer, buffer_position) =
 3900            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3901                output
 3902            } else {
 3903                return;
 3904            };
 3905        let show_completion_documentation = buffer
 3906            .read(cx)
 3907            .snapshot()
 3908            .settings_at(buffer_position, cx)
 3909            .show_completion_documentation;
 3910
 3911        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3912
 3913        let trigger_kind = match &options.trigger {
 3914            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3915                CompletionTriggerKind::TRIGGER_CHARACTER
 3916            }
 3917            _ => CompletionTriggerKind::INVOKED,
 3918        };
 3919        let completion_context = CompletionContext {
 3920            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3921                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3922                    Some(String::from(trigger))
 3923                } else {
 3924                    None
 3925                }
 3926            }),
 3927            trigger_kind,
 3928        };
 3929        let completions =
 3930            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3931        let sort_completions = provider.sort_completions();
 3932
 3933        let id = post_inc(&mut self.next_completion_id);
 3934        let task = cx.spawn_in(window, |editor, mut cx| {
 3935            async move {
 3936                editor.update(&mut cx, |this, _| {
 3937                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3938                })?;
 3939                let completions = completions.await.log_err();
 3940                let menu = if let Some(completions) = completions {
 3941                    let mut menu = CompletionsMenu::new(
 3942                        id,
 3943                        sort_completions,
 3944                        show_completion_documentation,
 3945                        position,
 3946                        buffer.clone(),
 3947                        completions.into(),
 3948                    );
 3949
 3950                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3951                        .await;
 3952
 3953                    menu.visible().then_some(menu)
 3954                } else {
 3955                    None
 3956                };
 3957
 3958                editor.update_in(&mut cx, |editor, window, cx| {
 3959                    match editor.context_menu.borrow().as_ref() {
 3960                        None => {}
 3961                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3962                            if prev_menu.id > id {
 3963                                return;
 3964                            }
 3965                        }
 3966                        _ => return,
 3967                    }
 3968
 3969                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3970                        let mut menu = menu.unwrap();
 3971                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3972
 3973                        *editor.context_menu.borrow_mut() =
 3974                            Some(CodeContextMenu::Completions(menu));
 3975
 3976                        if editor.show_edit_predictions_in_menu() {
 3977                            editor.update_visible_inline_completion(window, cx);
 3978                        } else {
 3979                            editor.discard_inline_completion(false, cx);
 3980                        }
 3981
 3982                        cx.notify();
 3983                    } else if editor.completion_tasks.len() <= 1 {
 3984                        // If there are no more completion tasks and the last menu was
 3985                        // empty, we should hide it.
 3986                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3987                        // If it was already hidden and we don't show inline
 3988                        // completions in the menu, we should also show the
 3989                        // inline-completion when available.
 3990                        if was_hidden && editor.show_edit_predictions_in_menu() {
 3991                            editor.update_visible_inline_completion(window, cx);
 3992                        }
 3993                    }
 3994                })?;
 3995
 3996                Ok::<_, anyhow::Error>(())
 3997            }
 3998            .log_err()
 3999        });
 4000
 4001        self.completion_tasks.push((id, task));
 4002    }
 4003
 4004    pub fn confirm_completion(
 4005        &mut self,
 4006        action: &ConfirmCompletion,
 4007        window: &mut Window,
 4008        cx: &mut Context<Self>,
 4009    ) -> Option<Task<Result<()>>> {
 4010        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4011    }
 4012
 4013    pub fn compose_completion(
 4014        &mut self,
 4015        action: &ComposeCompletion,
 4016        window: &mut Window,
 4017        cx: &mut Context<Self>,
 4018    ) -> Option<Task<Result<()>>> {
 4019        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4020    }
 4021
 4022    fn do_completion(
 4023        &mut self,
 4024        item_ix: Option<usize>,
 4025        intent: CompletionIntent,
 4026        window: &mut Window,
 4027        cx: &mut Context<Editor>,
 4028    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4029        use language::ToOffset as _;
 4030
 4031        let completions_menu =
 4032            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4033                menu
 4034            } else {
 4035                return None;
 4036            };
 4037
 4038        let entries = completions_menu.entries.borrow();
 4039        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4040        if self.show_edit_predictions_in_menu() {
 4041            self.discard_inline_completion(true, cx);
 4042        }
 4043        let candidate_id = mat.candidate_id;
 4044        drop(entries);
 4045
 4046        let buffer_handle = completions_menu.buffer;
 4047        let completion = completions_menu
 4048            .completions
 4049            .borrow()
 4050            .get(candidate_id)?
 4051            .clone();
 4052        cx.stop_propagation();
 4053
 4054        let snippet;
 4055        let text;
 4056
 4057        if completion.is_snippet() {
 4058            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4059            text = snippet.as_ref().unwrap().text.clone();
 4060        } else {
 4061            snippet = None;
 4062            text = completion.new_text.clone();
 4063        };
 4064        let selections = self.selections.all::<usize>(cx);
 4065        let buffer = buffer_handle.read(cx);
 4066        let old_range = completion.old_range.to_offset(buffer);
 4067        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4068
 4069        let newest_selection = self.selections.newest_anchor();
 4070        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4071            return None;
 4072        }
 4073
 4074        let lookbehind = newest_selection
 4075            .start
 4076            .text_anchor
 4077            .to_offset(buffer)
 4078            .saturating_sub(old_range.start);
 4079        let lookahead = old_range
 4080            .end
 4081            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4082        let mut common_prefix_len = old_text
 4083            .bytes()
 4084            .zip(text.bytes())
 4085            .take_while(|(a, b)| a == b)
 4086            .count();
 4087
 4088        let snapshot = self.buffer.read(cx).snapshot(cx);
 4089        let mut range_to_replace: Option<Range<isize>> = None;
 4090        let mut ranges = Vec::new();
 4091        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4092        for selection in &selections {
 4093            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4094                let start = selection.start.saturating_sub(lookbehind);
 4095                let end = selection.end + lookahead;
 4096                if selection.id == newest_selection.id {
 4097                    range_to_replace = Some(
 4098                        ((start + common_prefix_len) as isize - selection.start as isize)
 4099                            ..(end as isize - selection.start as isize),
 4100                    );
 4101                }
 4102                ranges.push(start + common_prefix_len..end);
 4103            } else {
 4104                common_prefix_len = 0;
 4105                ranges.clear();
 4106                ranges.extend(selections.iter().map(|s| {
 4107                    if s.id == newest_selection.id {
 4108                        range_to_replace = Some(
 4109                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4110                                - selection.start as isize
 4111                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4112                                    - selection.start as isize,
 4113                        );
 4114                        old_range.clone()
 4115                    } else {
 4116                        s.start..s.end
 4117                    }
 4118                }));
 4119                break;
 4120            }
 4121            if !self.linked_edit_ranges.is_empty() {
 4122                let start_anchor = snapshot.anchor_before(selection.head());
 4123                let end_anchor = snapshot.anchor_after(selection.tail());
 4124                if let Some(ranges) = self
 4125                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4126                {
 4127                    for (buffer, edits) in ranges {
 4128                        linked_edits.entry(buffer.clone()).or_default().extend(
 4129                            edits
 4130                                .into_iter()
 4131                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4132                        );
 4133                    }
 4134                }
 4135            }
 4136        }
 4137        let text = &text[common_prefix_len..];
 4138
 4139        cx.emit(EditorEvent::InputHandled {
 4140            utf16_range_to_replace: range_to_replace,
 4141            text: text.into(),
 4142        });
 4143
 4144        self.transact(window, cx, |this, window, cx| {
 4145            if let Some(mut snippet) = snippet {
 4146                snippet.text = text.to_string();
 4147                for tabstop in snippet
 4148                    .tabstops
 4149                    .iter_mut()
 4150                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4151                {
 4152                    tabstop.start -= common_prefix_len as isize;
 4153                    tabstop.end -= common_prefix_len as isize;
 4154                }
 4155
 4156                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4157            } else {
 4158                this.buffer.update(cx, |buffer, cx| {
 4159                    buffer.edit(
 4160                        ranges.iter().map(|range| (range.clone(), text)),
 4161                        this.autoindent_mode.clone(),
 4162                        cx,
 4163                    );
 4164                });
 4165            }
 4166            for (buffer, edits) in linked_edits {
 4167                buffer.update(cx, |buffer, cx| {
 4168                    let snapshot = buffer.snapshot();
 4169                    let edits = edits
 4170                        .into_iter()
 4171                        .map(|(range, text)| {
 4172                            use text::ToPoint as TP;
 4173                            let end_point = TP::to_point(&range.end, &snapshot);
 4174                            let start_point = TP::to_point(&range.start, &snapshot);
 4175                            (start_point..end_point, text)
 4176                        })
 4177                        .sorted_by_key(|(range, _)| range.start)
 4178                        .collect::<Vec<_>>();
 4179                    buffer.edit(edits, None, cx);
 4180                })
 4181            }
 4182
 4183            this.refresh_inline_completion(true, false, window, cx);
 4184        });
 4185
 4186        let show_new_completions_on_confirm = completion
 4187            .confirm
 4188            .as_ref()
 4189            .map_or(false, |confirm| confirm(intent, window, cx));
 4190        if show_new_completions_on_confirm {
 4191            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4192        }
 4193
 4194        let provider = self.completion_provider.as_ref()?;
 4195        drop(completion);
 4196        let apply_edits = provider.apply_additional_edits_for_completion(
 4197            buffer_handle,
 4198            completions_menu.completions.clone(),
 4199            candidate_id,
 4200            true,
 4201            cx,
 4202        );
 4203
 4204        let editor_settings = EditorSettings::get_global(cx);
 4205        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4206            // After the code completion is finished, users often want to know what signatures are needed.
 4207            // so we should automatically call signature_help
 4208            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4209        }
 4210
 4211        Some(cx.foreground_executor().spawn(async move {
 4212            apply_edits.await?;
 4213            Ok(())
 4214        }))
 4215    }
 4216
 4217    pub fn toggle_code_actions(
 4218        &mut self,
 4219        action: &ToggleCodeActions,
 4220        window: &mut Window,
 4221        cx: &mut Context<Self>,
 4222    ) {
 4223        let mut context_menu = self.context_menu.borrow_mut();
 4224        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4225            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4226                // Toggle if we're selecting the same one
 4227                *context_menu = None;
 4228                cx.notify();
 4229                return;
 4230            } else {
 4231                // Otherwise, clear it and start a new one
 4232                *context_menu = None;
 4233                cx.notify();
 4234            }
 4235        }
 4236        drop(context_menu);
 4237        let snapshot = self.snapshot(window, cx);
 4238        let deployed_from_indicator = action.deployed_from_indicator;
 4239        let mut task = self.code_actions_task.take();
 4240        let action = action.clone();
 4241        cx.spawn_in(window, |editor, mut cx| async move {
 4242            while let Some(prev_task) = task {
 4243                prev_task.await.log_err();
 4244                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4245            }
 4246
 4247            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4248                if editor.focus_handle.is_focused(window) {
 4249                    let multibuffer_point = action
 4250                        .deployed_from_indicator
 4251                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4252                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4253                    let (buffer, buffer_row) = snapshot
 4254                        .buffer_snapshot
 4255                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4256                        .and_then(|(buffer_snapshot, range)| {
 4257                            editor
 4258                                .buffer
 4259                                .read(cx)
 4260                                .buffer(buffer_snapshot.remote_id())
 4261                                .map(|buffer| (buffer, range.start.row))
 4262                        })?;
 4263                    let (_, code_actions) = editor
 4264                        .available_code_actions
 4265                        .clone()
 4266                        .and_then(|(location, code_actions)| {
 4267                            let snapshot = location.buffer.read(cx).snapshot();
 4268                            let point_range = location.range.to_point(&snapshot);
 4269                            let point_range = point_range.start.row..=point_range.end.row;
 4270                            if point_range.contains(&buffer_row) {
 4271                                Some((location, code_actions))
 4272                            } else {
 4273                                None
 4274                            }
 4275                        })
 4276                        .unzip();
 4277                    let buffer_id = buffer.read(cx).remote_id();
 4278                    let tasks = editor
 4279                        .tasks
 4280                        .get(&(buffer_id, buffer_row))
 4281                        .map(|t| Arc::new(t.to_owned()));
 4282                    if tasks.is_none() && code_actions.is_none() {
 4283                        return None;
 4284                    }
 4285
 4286                    editor.completion_tasks.clear();
 4287                    editor.discard_inline_completion(false, cx);
 4288                    let task_context =
 4289                        tasks
 4290                            .as_ref()
 4291                            .zip(editor.project.clone())
 4292                            .map(|(tasks, project)| {
 4293                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4294                            });
 4295
 4296                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4297                        let task_context = match task_context {
 4298                            Some(task_context) => task_context.await,
 4299                            None => None,
 4300                        };
 4301                        let resolved_tasks =
 4302                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4303                                Rc::new(ResolvedTasks {
 4304                                    templates: tasks.resolve(&task_context).collect(),
 4305                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4306                                        multibuffer_point.row,
 4307                                        tasks.column,
 4308                                    )),
 4309                                })
 4310                            });
 4311                        let spawn_straight_away = resolved_tasks
 4312                            .as_ref()
 4313                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4314                            && code_actions
 4315                                .as_ref()
 4316                                .map_or(true, |actions| actions.is_empty());
 4317                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4318                            *editor.context_menu.borrow_mut() =
 4319                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4320                                    buffer,
 4321                                    actions: CodeActionContents {
 4322                                        tasks: resolved_tasks,
 4323                                        actions: code_actions,
 4324                                    },
 4325                                    selected_item: Default::default(),
 4326                                    scroll_handle: UniformListScrollHandle::default(),
 4327                                    deployed_from_indicator,
 4328                                }));
 4329                            if spawn_straight_away {
 4330                                if let Some(task) = editor.confirm_code_action(
 4331                                    &ConfirmCodeAction { item_ix: Some(0) },
 4332                                    window,
 4333                                    cx,
 4334                                ) {
 4335                                    cx.notify();
 4336                                    return task;
 4337                                }
 4338                            }
 4339                            cx.notify();
 4340                            Task::ready(Ok(()))
 4341                        }) {
 4342                            task.await
 4343                        } else {
 4344                            Ok(())
 4345                        }
 4346                    }))
 4347                } else {
 4348                    Some(Task::ready(Ok(())))
 4349                }
 4350            })?;
 4351            if let Some(task) = spawned_test_task {
 4352                task.await?;
 4353            }
 4354
 4355            Ok::<_, anyhow::Error>(())
 4356        })
 4357        .detach_and_log_err(cx);
 4358    }
 4359
 4360    pub fn confirm_code_action(
 4361        &mut self,
 4362        action: &ConfirmCodeAction,
 4363        window: &mut Window,
 4364        cx: &mut Context<Self>,
 4365    ) -> Option<Task<Result<()>>> {
 4366        let actions_menu =
 4367            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4368                menu
 4369            } else {
 4370                return None;
 4371            };
 4372        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4373        let action = actions_menu.actions.get(action_ix)?;
 4374        let title = action.label();
 4375        let buffer = actions_menu.buffer;
 4376        let workspace = self.workspace()?;
 4377
 4378        match action {
 4379            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4380                workspace.update(cx, |workspace, cx| {
 4381                    workspace::tasks::schedule_resolved_task(
 4382                        workspace,
 4383                        task_source_kind,
 4384                        resolved_task,
 4385                        false,
 4386                        cx,
 4387                    );
 4388
 4389                    Some(Task::ready(Ok(())))
 4390                })
 4391            }
 4392            CodeActionsItem::CodeAction {
 4393                excerpt_id,
 4394                action,
 4395                provider,
 4396            } => {
 4397                let apply_code_action =
 4398                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4399                let workspace = workspace.downgrade();
 4400                Some(cx.spawn_in(window, |editor, cx| async move {
 4401                    let project_transaction = apply_code_action.await?;
 4402                    Self::open_project_transaction(
 4403                        &editor,
 4404                        workspace,
 4405                        project_transaction,
 4406                        title,
 4407                        cx,
 4408                    )
 4409                    .await
 4410                }))
 4411            }
 4412        }
 4413    }
 4414
 4415    pub async fn open_project_transaction(
 4416        this: &WeakEntity<Editor>,
 4417        workspace: WeakEntity<Workspace>,
 4418        transaction: ProjectTransaction,
 4419        title: String,
 4420        mut cx: AsyncWindowContext,
 4421    ) -> Result<()> {
 4422        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4423        cx.update(|_, cx| {
 4424            entries.sort_unstable_by_key(|(buffer, _)| {
 4425                buffer.read(cx).file().map(|f| f.path().clone())
 4426            });
 4427        })?;
 4428
 4429        // If the project transaction's edits are all contained within this editor, then
 4430        // avoid opening a new editor to display them.
 4431
 4432        if let Some((buffer, transaction)) = entries.first() {
 4433            if entries.len() == 1 {
 4434                let excerpt = this.update(&mut cx, |editor, cx| {
 4435                    editor
 4436                        .buffer()
 4437                        .read(cx)
 4438                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4439                })?;
 4440                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4441                    if excerpted_buffer == *buffer {
 4442                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4443                            let excerpt_range = excerpt_range.to_offset(buffer);
 4444                            buffer
 4445                                .edited_ranges_for_transaction::<usize>(transaction)
 4446                                .all(|range| {
 4447                                    excerpt_range.start <= range.start
 4448                                        && excerpt_range.end >= range.end
 4449                                })
 4450                        })?;
 4451
 4452                        if all_edits_within_excerpt {
 4453                            return Ok(());
 4454                        }
 4455                    }
 4456                }
 4457            }
 4458        } else {
 4459            return Ok(());
 4460        }
 4461
 4462        let mut ranges_to_highlight = Vec::new();
 4463        let excerpt_buffer = cx.new(|cx| {
 4464            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4465            for (buffer_handle, transaction) in &entries {
 4466                let buffer = buffer_handle.read(cx);
 4467                ranges_to_highlight.extend(
 4468                    multibuffer.push_excerpts_with_context_lines(
 4469                        buffer_handle.clone(),
 4470                        buffer
 4471                            .edited_ranges_for_transaction::<usize>(transaction)
 4472                            .collect(),
 4473                        DEFAULT_MULTIBUFFER_CONTEXT,
 4474                        cx,
 4475                    ),
 4476                );
 4477            }
 4478            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4479            multibuffer
 4480        })?;
 4481
 4482        workspace.update_in(&mut cx, |workspace, window, cx| {
 4483            let project = workspace.project().clone();
 4484            let editor = cx
 4485                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4486            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4487            editor.update(cx, |editor, cx| {
 4488                editor.highlight_background::<Self>(
 4489                    &ranges_to_highlight,
 4490                    |theme| theme.editor_highlighted_line_background,
 4491                    cx,
 4492                );
 4493            });
 4494        })?;
 4495
 4496        Ok(())
 4497    }
 4498
 4499    pub fn clear_code_action_providers(&mut self) {
 4500        self.code_action_providers.clear();
 4501        self.available_code_actions.take();
 4502    }
 4503
 4504    pub fn add_code_action_provider(
 4505        &mut self,
 4506        provider: Rc<dyn CodeActionProvider>,
 4507        window: &mut Window,
 4508        cx: &mut Context<Self>,
 4509    ) {
 4510        if self
 4511            .code_action_providers
 4512            .iter()
 4513            .any(|existing_provider| existing_provider.id() == provider.id())
 4514        {
 4515            return;
 4516        }
 4517
 4518        self.code_action_providers.push(provider);
 4519        self.refresh_code_actions(window, cx);
 4520    }
 4521
 4522    pub fn remove_code_action_provider(
 4523        &mut self,
 4524        id: Arc<str>,
 4525        window: &mut Window,
 4526        cx: &mut Context<Self>,
 4527    ) {
 4528        self.code_action_providers
 4529            .retain(|provider| provider.id() != id);
 4530        self.refresh_code_actions(window, cx);
 4531    }
 4532
 4533    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4534        let buffer = self.buffer.read(cx);
 4535        let newest_selection = self.selections.newest_anchor().clone();
 4536        if newest_selection.head().diff_base_anchor.is_some() {
 4537            return None;
 4538        }
 4539        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4540        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4541        if start_buffer != end_buffer {
 4542            return None;
 4543        }
 4544
 4545        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4546            cx.background_executor()
 4547                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4548                .await;
 4549
 4550            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4551                let providers = this.code_action_providers.clone();
 4552                let tasks = this
 4553                    .code_action_providers
 4554                    .iter()
 4555                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4556                    .collect::<Vec<_>>();
 4557                (providers, tasks)
 4558            })?;
 4559
 4560            let mut actions = Vec::new();
 4561            for (provider, provider_actions) in
 4562                providers.into_iter().zip(future::join_all(tasks).await)
 4563            {
 4564                if let Some(provider_actions) = provider_actions.log_err() {
 4565                    actions.extend(provider_actions.into_iter().map(|action| {
 4566                        AvailableCodeAction {
 4567                            excerpt_id: newest_selection.start.excerpt_id,
 4568                            action,
 4569                            provider: provider.clone(),
 4570                        }
 4571                    }));
 4572                }
 4573            }
 4574
 4575            this.update(&mut cx, |this, cx| {
 4576                this.available_code_actions = if actions.is_empty() {
 4577                    None
 4578                } else {
 4579                    Some((
 4580                        Location {
 4581                            buffer: start_buffer,
 4582                            range: start..end,
 4583                        },
 4584                        actions.into(),
 4585                    ))
 4586                };
 4587                cx.notify();
 4588            })
 4589        }));
 4590        None
 4591    }
 4592
 4593    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4594        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4595            self.show_git_blame_inline = false;
 4596
 4597            self.show_git_blame_inline_delay_task =
 4598                Some(cx.spawn_in(window, |this, mut cx| async move {
 4599                    cx.background_executor().timer(delay).await;
 4600
 4601                    this.update(&mut cx, |this, cx| {
 4602                        this.show_git_blame_inline = true;
 4603                        cx.notify();
 4604                    })
 4605                    .log_err();
 4606                }));
 4607        }
 4608    }
 4609
 4610    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4611        if self.pending_rename.is_some() {
 4612            return None;
 4613        }
 4614
 4615        let provider = self.semantics_provider.clone()?;
 4616        let buffer = self.buffer.read(cx);
 4617        let newest_selection = self.selections.newest_anchor().clone();
 4618        let cursor_position = newest_selection.head();
 4619        let (cursor_buffer, cursor_buffer_position) =
 4620            buffer.text_anchor_for_position(cursor_position, cx)?;
 4621        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4622        if cursor_buffer != tail_buffer {
 4623            return None;
 4624        }
 4625        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4626        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4627            cx.background_executor()
 4628                .timer(Duration::from_millis(debounce))
 4629                .await;
 4630
 4631            let highlights = if let Some(highlights) = cx
 4632                .update(|cx| {
 4633                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4634                })
 4635                .ok()
 4636                .flatten()
 4637            {
 4638                highlights.await.log_err()
 4639            } else {
 4640                None
 4641            };
 4642
 4643            if let Some(highlights) = highlights {
 4644                this.update(&mut cx, |this, cx| {
 4645                    if this.pending_rename.is_some() {
 4646                        return;
 4647                    }
 4648
 4649                    let buffer_id = cursor_position.buffer_id;
 4650                    let buffer = this.buffer.read(cx);
 4651                    if !buffer
 4652                        .text_anchor_for_position(cursor_position, cx)
 4653                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4654                    {
 4655                        return;
 4656                    }
 4657
 4658                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4659                    let mut write_ranges = Vec::new();
 4660                    let mut read_ranges = Vec::new();
 4661                    for highlight in highlights {
 4662                        for (excerpt_id, excerpt_range) in
 4663                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4664                        {
 4665                            let start = highlight
 4666                                .range
 4667                                .start
 4668                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4669                            let end = highlight
 4670                                .range
 4671                                .end
 4672                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4673                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4674                                continue;
 4675                            }
 4676
 4677                            let range = Anchor {
 4678                                buffer_id,
 4679                                excerpt_id,
 4680                                text_anchor: start,
 4681                                diff_base_anchor: None,
 4682                            }..Anchor {
 4683                                buffer_id,
 4684                                excerpt_id,
 4685                                text_anchor: end,
 4686                                diff_base_anchor: None,
 4687                            };
 4688                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4689                                write_ranges.push(range);
 4690                            } else {
 4691                                read_ranges.push(range);
 4692                            }
 4693                        }
 4694                    }
 4695
 4696                    this.highlight_background::<DocumentHighlightRead>(
 4697                        &read_ranges,
 4698                        |theme| theme.editor_document_highlight_read_background,
 4699                        cx,
 4700                    );
 4701                    this.highlight_background::<DocumentHighlightWrite>(
 4702                        &write_ranges,
 4703                        |theme| theme.editor_document_highlight_write_background,
 4704                        cx,
 4705                    );
 4706                    cx.notify();
 4707                })
 4708                .log_err();
 4709            }
 4710        }));
 4711        None
 4712    }
 4713
 4714    pub fn refresh_inline_completion(
 4715        &mut self,
 4716        debounce: bool,
 4717        user_requested: bool,
 4718        window: &mut Window,
 4719        cx: &mut Context<Self>,
 4720    ) -> Option<()> {
 4721        let provider = self.edit_prediction_provider()?;
 4722        let cursor = self.selections.newest_anchor().head();
 4723        let (buffer, cursor_buffer_position) =
 4724            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4725
 4726        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4727            self.discard_inline_completion(false, cx);
 4728            return None;
 4729        }
 4730
 4731        if !user_requested
 4732            && (!self.should_show_edit_predictions()
 4733                || !self.is_focused(window)
 4734                || buffer.read(cx).is_empty())
 4735        {
 4736            self.discard_inline_completion(false, cx);
 4737            return None;
 4738        }
 4739
 4740        self.update_visible_inline_completion(window, cx);
 4741        provider.refresh(
 4742            self.project.clone(),
 4743            buffer,
 4744            cursor_buffer_position,
 4745            debounce,
 4746            cx,
 4747        );
 4748        Some(())
 4749    }
 4750
 4751    fn show_edit_predictions_in_menu(&self) -> bool {
 4752        match self.edit_prediction_settings {
 4753            EditPredictionSettings::Disabled => false,
 4754            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4755        }
 4756    }
 4757
 4758    pub fn edit_predictions_enabled(&self) -> bool {
 4759        match self.edit_prediction_settings {
 4760            EditPredictionSettings::Disabled => false,
 4761            EditPredictionSettings::Enabled { .. } => true,
 4762        }
 4763    }
 4764
 4765    fn edit_prediction_requires_modifier(&self) -> bool {
 4766        match self.edit_prediction_settings {
 4767            EditPredictionSettings::Disabled => false,
 4768            EditPredictionSettings::Enabled {
 4769                preview_requires_modifier,
 4770                ..
 4771            } => preview_requires_modifier,
 4772        }
 4773    }
 4774
 4775    fn edit_prediction_settings_at_position(
 4776        &self,
 4777        buffer: &Entity<Buffer>,
 4778        buffer_position: language::Anchor,
 4779        cx: &App,
 4780    ) -> EditPredictionSettings {
 4781        if self.mode != EditorMode::Full
 4782            || !self.show_inline_completions_override.unwrap_or(true)
 4783            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4784        {
 4785            return EditPredictionSettings::Disabled;
 4786        }
 4787
 4788        let buffer = buffer.read(cx);
 4789
 4790        let file = buffer.file();
 4791
 4792        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4793            return EditPredictionSettings::Disabled;
 4794        };
 4795
 4796        let by_provider = matches!(
 4797            self.menu_inline_completions_policy,
 4798            MenuInlineCompletionsPolicy::ByProvider
 4799        );
 4800
 4801        let show_in_menu = by_provider
 4802            && self
 4803                .edit_prediction_provider
 4804                .as_ref()
 4805                .map_or(false, |provider| {
 4806                    provider.provider.show_completions_in_menu()
 4807                });
 4808
 4809        let preview_requires_modifier =
 4810            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4811
 4812        EditPredictionSettings::Enabled {
 4813            show_in_menu,
 4814            preview_requires_modifier,
 4815        }
 4816    }
 4817
 4818    fn should_show_edit_predictions(&self) -> bool {
 4819        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4820    }
 4821
 4822    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4823        matches!(
 4824            self.edit_prediction_preview,
 4825            EditPredictionPreview::Active { .. }
 4826        )
 4827    }
 4828
 4829    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4830        let cursor = self.selections.newest_anchor().head();
 4831        if let Some((buffer, cursor_position)) =
 4832            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4833        {
 4834            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4835        } else {
 4836            false
 4837        }
 4838    }
 4839
 4840    fn inline_completions_enabled_in_buffer(
 4841        &self,
 4842        buffer: &Entity<Buffer>,
 4843        buffer_position: language::Anchor,
 4844        cx: &App,
 4845    ) -> bool {
 4846        maybe!({
 4847            let provider = self.edit_prediction_provider()?;
 4848            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4849                return Some(false);
 4850            }
 4851            let buffer = buffer.read(cx);
 4852            let Some(file) = buffer.file() else {
 4853                return Some(true);
 4854            };
 4855            let settings = all_language_settings(Some(file), cx);
 4856            Some(settings.inline_completions_enabled_for_path(file.path()))
 4857        })
 4858        .unwrap_or(false)
 4859    }
 4860
 4861    fn cycle_inline_completion(
 4862        &mut self,
 4863        direction: Direction,
 4864        window: &mut Window,
 4865        cx: &mut Context<Self>,
 4866    ) -> Option<()> {
 4867        let provider = self.edit_prediction_provider()?;
 4868        let cursor = self.selections.newest_anchor().head();
 4869        let (buffer, cursor_buffer_position) =
 4870            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4871        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 4872            return None;
 4873        }
 4874
 4875        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4876        self.update_visible_inline_completion(window, cx);
 4877
 4878        Some(())
 4879    }
 4880
 4881    pub fn show_inline_completion(
 4882        &mut self,
 4883        _: &ShowEditPrediction,
 4884        window: &mut Window,
 4885        cx: &mut Context<Self>,
 4886    ) {
 4887        if !self.has_active_inline_completion() {
 4888            self.refresh_inline_completion(false, true, window, cx);
 4889            return;
 4890        }
 4891
 4892        self.update_visible_inline_completion(window, cx);
 4893    }
 4894
 4895    pub fn display_cursor_names(
 4896        &mut self,
 4897        _: &DisplayCursorNames,
 4898        window: &mut Window,
 4899        cx: &mut Context<Self>,
 4900    ) {
 4901        self.show_cursor_names(window, cx);
 4902    }
 4903
 4904    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4905        self.show_cursor_names = true;
 4906        cx.notify();
 4907        cx.spawn_in(window, |this, mut cx| async move {
 4908            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4909            this.update(&mut cx, |this, cx| {
 4910                this.show_cursor_names = false;
 4911                cx.notify()
 4912            })
 4913            .ok()
 4914        })
 4915        .detach();
 4916    }
 4917
 4918    pub fn next_edit_prediction(
 4919        &mut self,
 4920        _: &NextEditPrediction,
 4921        window: &mut Window,
 4922        cx: &mut Context<Self>,
 4923    ) {
 4924        if self.has_active_inline_completion() {
 4925            self.cycle_inline_completion(Direction::Next, window, cx);
 4926        } else {
 4927            let is_copilot_disabled = self
 4928                .refresh_inline_completion(false, true, window, cx)
 4929                .is_none();
 4930            if is_copilot_disabled {
 4931                cx.propagate();
 4932            }
 4933        }
 4934    }
 4935
 4936    pub fn previous_edit_prediction(
 4937        &mut self,
 4938        _: &PreviousEditPrediction,
 4939        window: &mut Window,
 4940        cx: &mut Context<Self>,
 4941    ) {
 4942        if self.has_active_inline_completion() {
 4943            self.cycle_inline_completion(Direction::Prev, window, cx);
 4944        } else {
 4945            let is_copilot_disabled = self
 4946                .refresh_inline_completion(false, true, window, cx)
 4947                .is_none();
 4948            if is_copilot_disabled {
 4949                cx.propagate();
 4950            }
 4951        }
 4952    }
 4953
 4954    pub fn accept_edit_prediction(
 4955        &mut self,
 4956        _: &AcceptEditPrediction,
 4957        window: &mut Window,
 4958        cx: &mut Context<Self>,
 4959    ) {
 4960        if self.show_edit_predictions_in_menu() {
 4961            self.hide_context_menu(window, cx);
 4962        }
 4963
 4964        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4965            return;
 4966        };
 4967
 4968        self.report_inline_completion_event(
 4969            active_inline_completion.completion_id.clone(),
 4970            true,
 4971            cx,
 4972        );
 4973
 4974        match &active_inline_completion.completion {
 4975            InlineCompletion::Move { target, .. } => {
 4976                let target = *target;
 4977
 4978                if let Some(position_map) = &self.last_position_map {
 4979                    if position_map
 4980                        .visible_row_range
 4981                        .contains(&target.to_display_point(&position_map.snapshot).row())
 4982                        || !self.edit_prediction_requires_modifier()
 4983                    {
 4984                        // Note that this is also done in vim's handler of the Tab action.
 4985                        self.change_selections(
 4986                            Some(Autoscroll::newest()),
 4987                            window,
 4988                            cx,
 4989                            |selections| {
 4990                                selections.select_anchor_ranges([target..target]);
 4991                            },
 4992                        );
 4993                        self.clear_row_highlights::<EditPredictionPreview>();
 4994
 4995                        self.edit_prediction_preview = EditPredictionPreview::Active {
 4996                            previous_scroll_position: None,
 4997                        };
 4998                    } else {
 4999                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5000                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5001                        };
 5002                        self.highlight_rows::<EditPredictionPreview>(
 5003                            target..target,
 5004                            cx.theme().colors().editor_highlighted_line_background,
 5005                            true,
 5006                            cx,
 5007                        );
 5008                        self.request_autoscroll(Autoscroll::fit(), cx);
 5009                    }
 5010                }
 5011            }
 5012            InlineCompletion::Edit { edits, .. } => {
 5013                if let Some(provider) = self.edit_prediction_provider() {
 5014                    provider.accept(cx);
 5015                }
 5016
 5017                let snapshot = self.buffer.read(cx).snapshot(cx);
 5018                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5019
 5020                self.buffer.update(cx, |buffer, cx| {
 5021                    buffer.edit(edits.iter().cloned(), None, cx)
 5022                });
 5023
 5024                self.change_selections(None, window, cx, |s| {
 5025                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5026                });
 5027
 5028                self.update_visible_inline_completion(window, cx);
 5029                if self.active_inline_completion.is_none() {
 5030                    self.refresh_inline_completion(true, true, window, cx);
 5031                }
 5032
 5033                cx.notify();
 5034            }
 5035        }
 5036
 5037        self.edit_prediction_requires_modifier_in_leading_space = false;
 5038    }
 5039
 5040    pub fn accept_partial_inline_completion(
 5041        &mut self,
 5042        _: &AcceptPartialEditPrediction,
 5043        window: &mut Window,
 5044        cx: &mut Context<Self>,
 5045    ) {
 5046        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5047            return;
 5048        };
 5049        if self.selections.count() != 1 {
 5050            return;
 5051        }
 5052
 5053        self.report_inline_completion_event(
 5054            active_inline_completion.completion_id.clone(),
 5055            true,
 5056            cx,
 5057        );
 5058
 5059        match &active_inline_completion.completion {
 5060            InlineCompletion::Move { target, .. } => {
 5061                let target = *target;
 5062                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5063                    selections.select_anchor_ranges([target..target]);
 5064                });
 5065            }
 5066            InlineCompletion::Edit { edits, .. } => {
 5067                // Find an insertion that starts at the cursor position.
 5068                let snapshot = self.buffer.read(cx).snapshot(cx);
 5069                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5070                let insertion = edits.iter().find_map(|(range, text)| {
 5071                    let range = range.to_offset(&snapshot);
 5072                    if range.is_empty() && range.start == cursor_offset {
 5073                        Some(text)
 5074                    } else {
 5075                        None
 5076                    }
 5077                });
 5078
 5079                if let Some(text) = insertion {
 5080                    let mut partial_completion = text
 5081                        .chars()
 5082                        .by_ref()
 5083                        .take_while(|c| c.is_alphabetic())
 5084                        .collect::<String>();
 5085                    if partial_completion.is_empty() {
 5086                        partial_completion = text
 5087                            .chars()
 5088                            .by_ref()
 5089                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5090                            .collect::<String>();
 5091                    }
 5092
 5093                    cx.emit(EditorEvent::InputHandled {
 5094                        utf16_range_to_replace: None,
 5095                        text: partial_completion.clone().into(),
 5096                    });
 5097
 5098                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5099
 5100                    self.refresh_inline_completion(true, true, window, cx);
 5101                    cx.notify();
 5102                } else {
 5103                    self.accept_edit_prediction(&Default::default(), window, cx);
 5104                }
 5105            }
 5106        }
 5107    }
 5108
 5109    fn discard_inline_completion(
 5110        &mut self,
 5111        should_report_inline_completion_event: bool,
 5112        cx: &mut Context<Self>,
 5113    ) -> bool {
 5114        if should_report_inline_completion_event {
 5115            let completion_id = self
 5116                .active_inline_completion
 5117                .as_ref()
 5118                .and_then(|active_completion| active_completion.completion_id.clone());
 5119
 5120            self.report_inline_completion_event(completion_id, false, cx);
 5121        }
 5122
 5123        if let Some(provider) = self.edit_prediction_provider() {
 5124            provider.discard(cx);
 5125        }
 5126
 5127        self.take_active_inline_completion(cx)
 5128    }
 5129
 5130    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5131        let Some(provider) = self.edit_prediction_provider() else {
 5132            return;
 5133        };
 5134
 5135        let Some((_, buffer, _)) = self
 5136            .buffer
 5137            .read(cx)
 5138            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5139        else {
 5140            return;
 5141        };
 5142
 5143        let extension = buffer
 5144            .read(cx)
 5145            .file()
 5146            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5147
 5148        let event_type = match accepted {
 5149            true => "Edit Prediction Accepted",
 5150            false => "Edit Prediction Discarded",
 5151        };
 5152        telemetry::event!(
 5153            event_type,
 5154            provider = provider.name(),
 5155            prediction_id = id,
 5156            suggestion_accepted = accepted,
 5157            file_extension = extension,
 5158        );
 5159    }
 5160
 5161    pub fn has_active_inline_completion(&self) -> bool {
 5162        self.active_inline_completion.is_some()
 5163    }
 5164
 5165    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5166        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5167            return false;
 5168        };
 5169
 5170        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5171        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5172        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5173        true
 5174    }
 5175
 5176    /// Returns true when we're displaying the edit prediction popover below the cursor
 5177    /// like we are not previewing and the LSP autocomplete menu is visible
 5178    /// or we are in `when_holding_modifier` mode.
 5179    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5180        if self.edit_prediction_preview_is_active()
 5181            || !self.show_edit_predictions_in_menu()
 5182            || !self.edit_predictions_enabled()
 5183        {
 5184            return false;
 5185        }
 5186
 5187        if self.has_visible_completions_menu() {
 5188            return true;
 5189        }
 5190
 5191        has_completion && self.edit_prediction_requires_modifier()
 5192    }
 5193
 5194    fn handle_modifiers_changed(
 5195        &mut self,
 5196        modifiers: Modifiers,
 5197        position_map: &PositionMap,
 5198        window: &mut Window,
 5199        cx: &mut Context<Self>,
 5200    ) {
 5201        if self.show_edit_predictions_in_menu() {
 5202            self.update_edit_prediction_preview(&modifiers, window, cx);
 5203        }
 5204
 5205        let mouse_position = window.mouse_position();
 5206        if !position_map.text_hitbox.is_hovered(window) {
 5207            return;
 5208        }
 5209
 5210        self.update_hovered_link(
 5211            position_map.point_for_position(mouse_position),
 5212            &position_map.snapshot,
 5213            modifiers,
 5214            window,
 5215            cx,
 5216        )
 5217    }
 5218
 5219    fn update_edit_prediction_preview(
 5220        &mut self,
 5221        modifiers: &Modifiers,
 5222        window: &mut Window,
 5223        cx: &mut Context<Self>,
 5224    ) {
 5225        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5226        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5227            return;
 5228        };
 5229
 5230        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5231            if matches!(
 5232                self.edit_prediction_preview,
 5233                EditPredictionPreview::Inactive
 5234            ) {
 5235                self.edit_prediction_preview = EditPredictionPreview::Active {
 5236                    previous_scroll_position: None,
 5237                };
 5238
 5239                self.update_visible_inline_completion(window, cx);
 5240                cx.notify();
 5241            }
 5242        } else if let EditPredictionPreview::Active {
 5243            previous_scroll_position,
 5244        } = self.edit_prediction_preview
 5245        {
 5246            if let (Some(previous_scroll_position), Some(position_map)) =
 5247                (previous_scroll_position, self.last_position_map.as_ref())
 5248            {
 5249                self.set_scroll_position(
 5250                    previous_scroll_position
 5251                        .scroll_position(&position_map.snapshot.display_snapshot),
 5252                    window,
 5253                    cx,
 5254                );
 5255            }
 5256
 5257            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5258            self.clear_row_highlights::<EditPredictionPreview>();
 5259            self.update_visible_inline_completion(window, cx);
 5260            cx.notify();
 5261        }
 5262    }
 5263
 5264    fn update_visible_inline_completion(
 5265        &mut self,
 5266        _window: &mut Window,
 5267        cx: &mut Context<Self>,
 5268    ) -> Option<()> {
 5269        let selection = self.selections.newest_anchor();
 5270        let cursor = selection.head();
 5271        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5272        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5273        let excerpt_id = cursor.excerpt_id;
 5274
 5275        let show_in_menu = self.show_edit_predictions_in_menu();
 5276        let completions_menu_has_precedence = !show_in_menu
 5277            && (self.context_menu.borrow().is_some()
 5278                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5279
 5280        if completions_menu_has_precedence
 5281            || !offset_selection.is_empty()
 5282            || self
 5283                .active_inline_completion
 5284                .as_ref()
 5285                .map_or(false, |completion| {
 5286                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5287                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5288                    !invalidation_range.contains(&offset_selection.head())
 5289                })
 5290        {
 5291            self.discard_inline_completion(false, cx);
 5292            return None;
 5293        }
 5294
 5295        self.take_active_inline_completion(cx);
 5296        let Some(provider) = self.edit_prediction_provider() else {
 5297            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5298            return None;
 5299        };
 5300
 5301        let (buffer, cursor_buffer_position) =
 5302            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5303
 5304        self.edit_prediction_settings =
 5305            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5306
 5307        if !self.edit_prediction_settings.is_enabled() {
 5308            self.discard_inline_completion(false, cx);
 5309            return None;
 5310        }
 5311
 5312        self.edit_prediction_cursor_on_leading_whitespace =
 5313            multibuffer.is_line_whitespace_upto(cursor);
 5314
 5315        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5316        let edits = inline_completion
 5317            .edits
 5318            .into_iter()
 5319            .flat_map(|(range, new_text)| {
 5320                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5321                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5322                Some((start..end, new_text))
 5323            })
 5324            .collect::<Vec<_>>();
 5325        if edits.is_empty() {
 5326            return None;
 5327        }
 5328
 5329        let first_edit_start = edits.first().unwrap().0.start;
 5330        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5331        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5332
 5333        let last_edit_end = edits.last().unwrap().0.end;
 5334        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5335        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5336
 5337        let cursor_row = cursor.to_point(&multibuffer).row;
 5338
 5339        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5340
 5341        let mut inlay_ids = Vec::new();
 5342        let invalidation_row_range;
 5343        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5344            Some(cursor_row..edit_end_row)
 5345        } else if cursor_row > edit_end_row {
 5346            Some(edit_start_row..cursor_row)
 5347        } else {
 5348            None
 5349        };
 5350        let is_move =
 5351            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5352        let completion = if is_move {
 5353            invalidation_row_range =
 5354                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5355            let target = first_edit_start;
 5356            InlineCompletion::Move { target, snapshot }
 5357        } else {
 5358            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5359                && !self.inline_completions_hidden_for_vim_mode;
 5360
 5361            if show_completions_in_buffer {
 5362                if edits
 5363                    .iter()
 5364                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5365                {
 5366                    let mut inlays = Vec::new();
 5367                    for (range, new_text) in &edits {
 5368                        let inlay = Inlay::inline_completion(
 5369                            post_inc(&mut self.next_inlay_id),
 5370                            range.start,
 5371                            new_text.as_str(),
 5372                        );
 5373                        inlay_ids.push(inlay.id);
 5374                        inlays.push(inlay);
 5375                    }
 5376
 5377                    self.splice_inlays(&[], inlays, cx);
 5378                } else {
 5379                    let background_color = cx.theme().status().deleted_background;
 5380                    self.highlight_text::<InlineCompletionHighlight>(
 5381                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5382                        HighlightStyle {
 5383                            background_color: Some(background_color),
 5384                            ..Default::default()
 5385                        },
 5386                        cx,
 5387                    );
 5388                }
 5389            }
 5390
 5391            invalidation_row_range = edit_start_row..edit_end_row;
 5392
 5393            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5394                if provider.show_tab_accept_marker() {
 5395                    EditDisplayMode::TabAccept
 5396                } else {
 5397                    EditDisplayMode::Inline
 5398                }
 5399            } else {
 5400                EditDisplayMode::DiffPopover
 5401            };
 5402
 5403            InlineCompletion::Edit {
 5404                edits,
 5405                edit_preview: inline_completion.edit_preview,
 5406                display_mode,
 5407                snapshot,
 5408            }
 5409        };
 5410
 5411        let invalidation_range = multibuffer
 5412            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5413            ..multibuffer.anchor_after(Point::new(
 5414                invalidation_row_range.end,
 5415                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5416            ));
 5417
 5418        self.stale_inline_completion_in_menu = None;
 5419        self.active_inline_completion = Some(InlineCompletionState {
 5420            inlay_ids,
 5421            completion,
 5422            completion_id: inline_completion.id,
 5423            invalidation_range,
 5424        });
 5425
 5426        cx.notify();
 5427
 5428        Some(())
 5429    }
 5430
 5431    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5432        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5433    }
 5434
 5435    fn render_code_actions_indicator(
 5436        &self,
 5437        _style: &EditorStyle,
 5438        row: DisplayRow,
 5439        is_active: bool,
 5440        cx: &mut Context<Self>,
 5441    ) -> Option<IconButton> {
 5442        if self.available_code_actions.is_some() {
 5443            Some(
 5444                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5445                    .shape(ui::IconButtonShape::Square)
 5446                    .icon_size(IconSize::XSmall)
 5447                    .icon_color(Color::Muted)
 5448                    .toggle_state(is_active)
 5449                    .tooltip({
 5450                        let focus_handle = self.focus_handle.clone();
 5451                        move |window, cx| {
 5452                            Tooltip::for_action_in(
 5453                                "Toggle Code Actions",
 5454                                &ToggleCodeActions {
 5455                                    deployed_from_indicator: None,
 5456                                },
 5457                                &focus_handle,
 5458                                window,
 5459                                cx,
 5460                            )
 5461                        }
 5462                    })
 5463                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5464                        window.focus(&editor.focus_handle(cx));
 5465                        editor.toggle_code_actions(
 5466                            &ToggleCodeActions {
 5467                                deployed_from_indicator: Some(row),
 5468                            },
 5469                            window,
 5470                            cx,
 5471                        );
 5472                    })),
 5473            )
 5474        } else {
 5475            None
 5476        }
 5477    }
 5478
 5479    fn clear_tasks(&mut self) {
 5480        self.tasks.clear()
 5481    }
 5482
 5483    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5484        if self.tasks.insert(key, value).is_some() {
 5485            // This case should hopefully be rare, but just in case...
 5486            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5487        }
 5488    }
 5489
 5490    fn build_tasks_context(
 5491        project: &Entity<Project>,
 5492        buffer: &Entity<Buffer>,
 5493        buffer_row: u32,
 5494        tasks: &Arc<RunnableTasks>,
 5495        cx: &mut Context<Self>,
 5496    ) -> Task<Option<task::TaskContext>> {
 5497        let position = Point::new(buffer_row, tasks.column);
 5498        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5499        let location = Location {
 5500            buffer: buffer.clone(),
 5501            range: range_start..range_start,
 5502        };
 5503        // Fill in the environmental variables from the tree-sitter captures
 5504        let mut captured_task_variables = TaskVariables::default();
 5505        for (capture_name, value) in tasks.extra_variables.clone() {
 5506            captured_task_variables.insert(
 5507                task::VariableName::Custom(capture_name.into()),
 5508                value.clone(),
 5509            );
 5510        }
 5511        project.update(cx, |project, cx| {
 5512            project.task_store().update(cx, |task_store, cx| {
 5513                task_store.task_context_for_location(captured_task_variables, location, cx)
 5514            })
 5515        })
 5516    }
 5517
 5518    pub fn spawn_nearest_task(
 5519        &mut self,
 5520        action: &SpawnNearestTask,
 5521        window: &mut Window,
 5522        cx: &mut Context<Self>,
 5523    ) {
 5524        let Some((workspace, _)) = self.workspace.clone() else {
 5525            return;
 5526        };
 5527        let Some(project) = self.project.clone() else {
 5528            return;
 5529        };
 5530
 5531        // Try to find a closest, enclosing node using tree-sitter that has a
 5532        // task
 5533        let Some((buffer, buffer_row, tasks)) = self
 5534            .find_enclosing_node_task(cx)
 5535            // Or find the task that's closest in row-distance.
 5536            .or_else(|| self.find_closest_task(cx))
 5537        else {
 5538            return;
 5539        };
 5540
 5541        let reveal_strategy = action.reveal;
 5542        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5543        cx.spawn_in(window, |_, mut cx| async move {
 5544            let context = task_context.await?;
 5545            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5546
 5547            let resolved = resolved_task.resolved.as_mut()?;
 5548            resolved.reveal = reveal_strategy;
 5549
 5550            workspace
 5551                .update(&mut cx, |workspace, cx| {
 5552                    workspace::tasks::schedule_resolved_task(
 5553                        workspace,
 5554                        task_source_kind,
 5555                        resolved_task,
 5556                        false,
 5557                        cx,
 5558                    );
 5559                })
 5560                .ok()
 5561        })
 5562        .detach();
 5563    }
 5564
 5565    fn find_closest_task(
 5566        &mut self,
 5567        cx: &mut Context<Self>,
 5568    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5569        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5570
 5571        let ((buffer_id, row), tasks) = self
 5572            .tasks
 5573            .iter()
 5574            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5575
 5576        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5577        let tasks = Arc::new(tasks.to_owned());
 5578        Some((buffer, *row, tasks))
 5579    }
 5580
 5581    fn find_enclosing_node_task(
 5582        &mut self,
 5583        cx: &mut Context<Self>,
 5584    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5585        let snapshot = self.buffer.read(cx).snapshot(cx);
 5586        let offset = self.selections.newest::<usize>(cx).head();
 5587        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5588        let buffer_id = excerpt.buffer().remote_id();
 5589
 5590        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5591        let mut cursor = layer.node().walk();
 5592
 5593        while cursor.goto_first_child_for_byte(offset).is_some() {
 5594            if cursor.node().end_byte() == offset {
 5595                cursor.goto_next_sibling();
 5596            }
 5597        }
 5598
 5599        // Ascend to the smallest ancestor that contains the range and has a task.
 5600        loop {
 5601            let node = cursor.node();
 5602            let node_range = node.byte_range();
 5603            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5604
 5605            // Check if this node contains our offset
 5606            if node_range.start <= offset && node_range.end >= offset {
 5607                // If it contains offset, check for task
 5608                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5609                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5610                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5611                }
 5612            }
 5613
 5614            if !cursor.goto_parent() {
 5615                break;
 5616            }
 5617        }
 5618        None
 5619    }
 5620
 5621    fn render_run_indicator(
 5622        &self,
 5623        _style: &EditorStyle,
 5624        is_active: bool,
 5625        row: DisplayRow,
 5626        cx: &mut Context<Self>,
 5627    ) -> IconButton {
 5628        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5629            .shape(ui::IconButtonShape::Square)
 5630            .icon_size(IconSize::XSmall)
 5631            .icon_color(Color::Muted)
 5632            .toggle_state(is_active)
 5633            .on_click(cx.listener(move |editor, _e, window, cx| {
 5634                window.focus(&editor.focus_handle(cx));
 5635                editor.toggle_code_actions(
 5636                    &ToggleCodeActions {
 5637                        deployed_from_indicator: Some(row),
 5638                    },
 5639                    window,
 5640                    cx,
 5641                );
 5642            }))
 5643    }
 5644
 5645    pub fn context_menu_visible(&self) -> bool {
 5646        !self.edit_prediction_preview_is_active()
 5647            && self
 5648                .context_menu
 5649                .borrow()
 5650                .as_ref()
 5651                .map_or(false, |menu| menu.visible())
 5652    }
 5653
 5654    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5655        self.context_menu
 5656            .borrow()
 5657            .as_ref()
 5658            .map(|menu| menu.origin())
 5659    }
 5660
 5661    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5662        px(30.)
 5663    }
 5664
 5665    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5666        if self.read_only(cx) {
 5667            cx.theme().players().read_only()
 5668        } else {
 5669            self.style.as_ref().unwrap().local_player
 5670        }
 5671    }
 5672
 5673    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5674        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5675        let accept_keystroke = accept_binding.keystroke()?;
 5676
 5677        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5678
 5679        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5680            Color::Accent
 5681        } else {
 5682            Color::Muted
 5683        };
 5684
 5685        h_flex()
 5686            .px_0p5()
 5687            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5688            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5689            .text_size(TextSize::XSmall.rems(cx))
 5690            .child(h_flex().children(ui::render_modifiers(
 5691                &accept_keystroke.modifiers,
 5692                PlatformStyle::platform(),
 5693                Some(modifiers_color),
 5694                Some(IconSize::XSmall.rems().into()),
 5695                true,
 5696            )))
 5697            .when(is_platform_style_mac, |parent| {
 5698                parent.child(accept_keystroke.key.clone())
 5699            })
 5700            .when(!is_platform_style_mac, |parent| {
 5701                parent.child(
 5702                    Key::new(
 5703                        util::capitalize(&accept_keystroke.key),
 5704                        Some(Color::Default),
 5705                    )
 5706                    .size(Some(IconSize::XSmall.rems().into())),
 5707                )
 5708            })
 5709            .into()
 5710    }
 5711
 5712    fn render_edit_prediction_line_popover(
 5713        &self,
 5714        label: impl Into<SharedString>,
 5715        icon: Option<IconName>,
 5716        window: &mut Window,
 5717        cx: &App,
 5718    ) -> Option<Div> {
 5719        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5720
 5721        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5722
 5723        let result = h_flex()
 5724            .gap_1()
 5725            .border_1()
 5726            .rounded_lg()
 5727            .shadow_sm()
 5728            .bg(bg_color)
 5729            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5730            .py_0p5()
 5731            .pl_1()
 5732            .pr(padding_right)
 5733            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5734            .child(Label::new(label).size(LabelSize::Small))
 5735            .when_some(icon, |element, icon| {
 5736                element.child(
 5737                    div()
 5738                        .mt(px(1.5))
 5739                        .child(Icon::new(icon).size(IconSize::Small)),
 5740                )
 5741            });
 5742
 5743        Some(result)
 5744    }
 5745
 5746    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5747        let accent_color = cx.theme().colors().text_accent;
 5748        let editor_bg_color = cx.theme().colors().editor_background;
 5749        editor_bg_color.blend(accent_color.opacity(0.1))
 5750    }
 5751
 5752    #[allow(clippy::too_many_arguments)]
 5753    fn render_edit_prediction_cursor_popover(
 5754        &self,
 5755        min_width: Pixels,
 5756        max_width: Pixels,
 5757        cursor_point: Point,
 5758        style: &EditorStyle,
 5759        accept_keystroke: &gpui::Keystroke,
 5760        _window: &Window,
 5761        cx: &mut Context<Editor>,
 5762    ) -> Option<AnyElement> {
 5763        let provider = self.edit_prediction_provider.as_ref()?;
 5764
 5765        if provider.provider.needs_terms_acceptance(cx) {
 5766            return Some(
 5767                h_flex()
 5768                    .min_w(min_width)
 5769                    .flex_1()
 5770                    .px_2()
 5771                    .py_1()
 5772                    .gap_3()
 5773                    .elevation_2(cx)
 5774                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5775                    .id("accept-terms")
 5776                    .cursor_pointer()
 5777                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5778                    .on_click(cx.listener(|this, _event, window, cx| {
 5779                        cx.stop_propagation();
 5780                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5781                        window.dispatch_action(
 5782                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5783                            cx,
 5784                        );
 5785                    }))
 5786                    .child(
 5787                        h_flex()
 5788                            .flex_1()
 5789                            .gap_2()
 5790                            .child(Icon::new(IconName::ZedPredict))
 5791                            .child(Label::new("Accept Terms of Service"))
 5792                            .child(div().w_full())
 5793                            .child(
 5794                                Icon::new(IconName::ArrowUpRight)
 5795                                    .color(Color::Muted)
 5796                                    .size(IconSize::Small),
 5797                            )
 5798                            .into_any_element(),
 5799                    )
 5800                    .into_any(),
 5801            );
 5802        }
 5803
 5804        let is_refreshing = provider.provider.is_refreshing(cx);
 5805
 5806        fn pending_completion_container() -> Div {
 5807            h_flex()
 5808                .h_full()
 5809                .flex_1()
 5810                .gap_2()
 5811                .child(Icon::new(IconName::ZedPredict))
 5812        }
 5813
 5814        let completion = match &self.active_inline_completion {
 5815            Some(completion) => match &completion.completion {
 5816                InlineCompletion::Move {
 5817                    target, snapshot, ..
 5818                } if !self.has_visible_completions_menu() => {
 5819                    use text::ToPoint as _;
 5820
 5821                    return Some(
 5822                        h_flex()
 5823                            .px_2()
 5824                            .py_1()
 5825                            .elevation_2(cx)
 5826                            .border_color(cx.theme().colors().border)
 5827                            .rounded_tl(px(0.))
 5828                            .gap_2()
 5829                            .child(
 5830                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5831                                    Icon::new(IconName::ZedPredictDown)
 5832                                } else {
 5833                                    Icon::new(IconName::ZedPredictUp)
 5834                                },
 5835                            )
 5836                            .child(Label::new("Hold").size(LabelSize::Small))
 5837                            .child(h_flex().children(ui::render_modifiers(
 5838                                &accept_keystroke.modifiers,
 5839                                PlatformStyle::platform(),
 5840                                Some(Color::Default),
 5841                                Some(IconSize::Small.rems().into()),
 5842                                false,
 5843                            )))
 5844                            .into_any(),
 5845                    );
 5846                }
 5847                _ => self.render_edit_prediction_cursor_popover_preview(
 5848                    completion,
 5849                    cursor_point,
 5850                    style,
 5851                    cx,
 5852                )?,
 5853            },
 5854
 5855            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5856                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5857                    stale_completion,
 5858                    cursor_point,
 5859                    style,
 5860                    cx,
 5861                )?,
 5862
 5863                None => {
 5864                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5865                }
 5866            },
 5867
 5868            None => pending_completion_container().child(Label::new("No Prediction")),
 5869        };
 5870
 5871        let completion = if is_refreshing {
 5872            completion
 5873                .with_animation(
 5874                    "loading-completion",
 5875                    Animation::new(Duration::from_secs(2))
 5876                        .repeat()
 5877                        .with_easing(pulsating_between(0.4, 0.8)),
 5878                    |label, delta| label.opacity(delta),
 5879                )
 5880                .into_any_element()
 5881        } else {
 5882            completion.into_any_element()
 5883        };
 5884
 5885        let has_completion = self.active_inline_completion.is_some();
 5886
 5887        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5888        Some(
 5889            h_flex()
 5890                .min_w(min_width)
 5891                .max_w(max_width)
 5892                .flex_1()
 5893                .elevation_2(cx)
 5894                .border_color(cx.theme().colors().border)
 5895                .child(
 5896                    div()
 5897                        .flex_1()
 5898                        .py_1()
 5899                        .px_2()
 5900                        .overflow_hidden()
 5901                        .child(completion),
 5902                )
 5903                .child(
 5904                    h_flex()
 5905                        .h_full()
 5906                        .border_l_1()
 5907                        .rounded_r_lg()
 5908                        .border_color(cx.theme().colors().border)
 5909                        .bg(Self::edit_prediction_line_popover_bg_color(cx))
 5910                        .gap_1()
 5911                        .py_1()
 5912                        .px_2()
 5913                        .child(
 5914                            h_flex()
 5915                                .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5916                                .when(is_platform_style_mac, |parent| parent.gap_1())
 5917                                .child(h_flex().children(ui::render_modifiers(
 5918                                    &accept_keystroke.modifiers,
 5919                                    PlatformStyle::platform(),
 5920                                    Some(if !has_completion {
 5921                                        Color::Muted
 5922                                    } else {
 5923                                        Color::Default
 5924                                    }),
 5925                                    None,
 5926                                    false,
 5927                                ))),
 5928                        )
 5929                        .child(Label::new("Preview").into_any_element())
 5930                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5931                )
 5932                .into_any(),
 5933        )
 5934    }
 5935
 5936    fn render_edit_prediction_cursor_popover_preview(
 5937        &self,
 5938        completion: &InlineCompletionState,
 5939        cursor_point: Point,
 5940        style: &EditorStyle,
 5941        cx: &mut Context<Editor>,
 5942    ) -> Option<Div> {
 5943        use text::ToPoint as _;
 5944
 5945        fn render_relative_row_jump(
 5946            prefix: impl Into<String>,
 5947            current_row: u32,
 5948            target_row: u32,
 5949        ) -> Div {
 5950            let (row_diff, arrow) = if target_row < current_row {
 5951                (current_row - target_row, IconName::ArrowUp)
 5952            } else {
 5953                (target_row - current_row, IconName::ArrowDown)
 5954            };
 5955
 5956            h_flex()
 5957                .child(
 5958                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5959                        .color(Color::Muted)
 5960                        .size(LabelSize::Small),
 5961                )
 5962                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5963        }
 5964
 5965        match &completion.completion {
 5966            InlineCompletion::Move {
 5967                target, snapshot, ..
 5968            } => Some(
 5969                h_flex()
 5970                    .px_2()
 5971                    .gap_2()
 5972                    .flex_1()
 5973                    .child(
 5974                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 5975                            Icon::new(IconName::ZedPredictDown)
 5976                        } else {
 5977                            Icon::new(IconName::ZedPredictUp)
 5978                        },
 5979                    )
 5980                    .child(Label::new("Jump to Edit")),
 5981            ),
 5982
 5983            InlineCompletion::Edit {
 5984                edits,
 5985                edit_preview,
 5986                snapshot,
 5987                display_mode: _,
 5988            } => {
 5989                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5990
 5991                let highlighted_edits = crate::inline_completion_edit_text(
 5992                    &snapshot,
 5993                    &edits,
 5994                    edit_preview.as_ref()?,
 5995                    true,
 5996                    cx,
 5997                );
 5998
 5999                let len_total = highlighted_edits.text.len();
 6000                let first_line = &highlighted_edits.text
 6001                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 6002                let first_line_len = first_line.len();
 6003
 6004                let first_highlight_start = highlighted_edits
 6005                    .highlights
 6006                    .first()
 6007                    .map_or(0, |(range, _)| range.start);
 6008                let drop_prefix_len = first_line
 6009                    .char_indices()
 6010                    .find(|(_, c)| !c.is_whitespace())
 6011                    .map_or(first_highlight_start, |(ix, _)| {
 6012                        ix.min(first_highlight_start)
 6013                    });
 6014
 6015                let preview_text = &first_line[drop_prefix_len..];
 6016                let preview_len = preview_text.len();
 6017                let highlights = highlighted_edits
 6018                    .highlights
 6019                    .into_iter()
 6020                    .take_until(|(range, _)| range.start > first_line_len)
 6021                    .map(|(range, style)| {
 6022                        (
 6023                            range.start - drop_prefix_len
 6024                                ..(range.end - drop_prefix_len).min(preview_len),
 6025                            style,
 6026                        )
 6027                    });
 6028
 6029                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 6030                    .with_highlights(&style.text, highlights);
 6031
 6032                let preview = h_flex()
 6033                    .gap_1()
 6034                    .min_w_16()
 6035                    .child(styled_text)
 6036                    .when(len_total > first_line_len, |parent| parent.child(""));
 6037
 6038                let left = if first_edit_row != cursor_point.row {
 6039                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6040                        .into_any_element()
 6041                } else {
 6042                    Icon::new(IconName::ZedPredict).into_any_element()
 6043                };
 6044
 6045                Some(
 6046                    h_flex()
 6047                        .h_full()
 6048                        .flex_1()
 6049                        .gap_2()
 6050                        .pr_1()
 6051                        .overflow_x_hidden()
 6052                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6053                        .child(left)
 6054                        .child(preview),
 6055                )
 6056            }
 6057        }
 6058    }
 6059
 6060    fn render_context_menu(
 6061        &self,
 6062        style: &EditorStyle,
 6063        max_height_in_lines: u32,
 6064        y_flipped: bool,
 6065        window: &mut Window,
 6066        cx: &mut Context<Editor>,
 6067    ) -> Option<AnyElement> {
 6068        let menu = self.context_menu.borrow();
 6069        let menu = menu.as_ref()?;
 6070        if !menu.visible() {
 6071            return None;
 6072        };
 6073        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6074    }
 6075
 6076    fn render_context_menu_aside(
 6077        &self,
 6078        style: &EditorStyle,
 6079        max_size: Size<Pixels>,
 6080        cx: &mut Context<Editor>,
 6081    ) -> Option<AnyElement> {
 6082        self.context_menu.borrow().as_ref().and_then(|menu| {
 6083            if menu.visible() {
 6084                menu.render_aside(
 6085                    style,
 6086                    max_size,
 6087                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6088                    cx,
 6089                )
 6090            } else {
 6091                None
 6092            }
 6093        })
 6094    }
 6095
 6096    fn hide_context_menu(
 6097        &mut self,
 6098        window: &mut Window,
 6099        cx: &mut Context<Self>,
 6100    ) -> Option<CodeContextMenu> {
 6101        cx.notify();
 6102        self.completion_tasks.clear();
 6103        let context_menu = self.context_menu.borrow_mut().take();
 6104        self.stale_inline_completion_in_menu.take();
 6105        self.update_visible_inline_completion(window, cx);
 6106        context_menu
 6107    }
 6108
 6109    fn show_snippet_choices(
 6110        &mut self,
 6111        choices: &Vec<String>,
 6112        selection: Range<Anchor>,
 6113        cx: &mut Context<Self>,
 6114    ) {
 6115        if selection.start.buffer_id.is_none() {
 6116            return;
 6117        }
 6118        let buffer_id = selection.start.buffer_id.unwrap();
 6119        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6120        let id = post_inc(&mut self.next_completion_id);
 6121
 6122        if let Some(buffer) = buffer {
 6123            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6124                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6125            ));
 6126        }
 6127    }
 6128
 6129    pub fn insert_snippet(
 6130        &mut self,
 6131        insertion_ranges: &[Range<usize>],
 6132        snippet: Snippet,
 6133        window: &mut Window,
 6134        cx: &mut Context<Self>,
 6135    ) -> Result<()> {
 6136        struct Tabstop<T> {
 6137            is_end_tabstop: bool,
 6138            ranges: Vec<Range<T>>,
 6139            choices: Option<Vec<String>>,
 6140        }
 6141
 6142        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6143            let snippet_text: Arc<str> = snippet.text.clone().into();
 6144            buffer.edit(
 6145                insertion_ranges
 6146                    .iter()
 6147                    .cloned()
 6148                    .map(|range| (range, snippet_text.clone())),
 6149                Some(AutoindentMode::EachLine),
 6150                cx,
 6151            );
 6152
 6153            let snapshot = &*buffer.read(cx);
 6154            let snippet = &snippet;
 6155            snippet
 6156                .tabstops
 6157                .iter()
 6158                .map(|tabstop| {
 6159                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6160                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6161                    });
 6162                    let mut tabstop_ranges = tabstop
 6163                        .ranges
 6164                        .iter()
 6165                        .flat_map(|tabstop_range| {
 6166                            let mut delta = 0_isize;
 6167                            insertion_ranges.iter().map(move |insertion_range| {
 6168                                let insertion_start = insertion_range.start as isize + delta;
 6169                                delta +=
 6170                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6171
 6172                                let start = ((insertion_start + tabstop_range.start) as usize)
 6173                                    .min(snapshot.len());
 6174                                let end = ((insertion_start + tabstop_range.end) as usize)
 6175                                    .min(snapshot.len());
 6176                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6177                            })
 6178                        })
 6179                        .collect::<Vec<_>>();
 6180                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6181
 6182                    Tabstop {
 6183                        is_end_tabstop,
 6184                        ranges: tabstop_ranges,
 6185                        choices: tabstop.choices.clone(),
 6186                    }
 6187                })
 6188                .collect::<Vec<_>>()
 6189        });
 6190        if let Some(tabstop) = tabstops.first() {
 6191            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6192                s.select_ranges(tabstop.ranges.iter().cloned());
 6193            });
 6194
 6195            if let Some(choices) = &tabstop.choices {
 6196                if let Some(selection) = tabstop.ranges.first() {
 6197                    self.show_snippet_choices(choices, selection.clone(), cx)
 6198                }
 6199            }
 6200
 6201            // If we're already at the last tabstop and it's at the end of the snippet,
 6202            // we're done, we don't need to keep the state around.
 6203            if !tabstop.is_end_tabstop {
 6204                let choices = tabstops
 6205                    .iter()
 6206                    .map(|tabstop| tabstop.choices.clone())
 6207                    .collect();
 6208
 6209                let ranges = tabstops
 6210                    .into_iter()
 6211                    .map(|tabstop| tabstop.ranges)
 6212                    .collect::<Vec<_>>();
 6213
 6214                self.snippet_stack.push(SnippetState {
 6215                    active_index: 0,
 6216                    ranges,
 6217                    choices,
 6218                });
 6219            }
 6220
 6221            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6222            if self.autoclose_regions.is_empty() {
 6223                let snapshot = self.buffer.read(cx).snapshot(cx);
 6224                for selection in &mut self.selections.all::<Point>(cx) {
 6225                    let selection_head = selection.head();
 6226                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6227                        continue;
 6228                    };
 6229
 6230                    let mut bracket_pair = None;
 6231                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6232                    let prev_chars = snapshot
 6233                        .reversed_chars_at(selection_head)
 6234                        .collect::<String>();
 6235                    for (pair, enabled) in scope.brackets() {
 6236                        if enabled
 6237                            && pair.close
 6238                            && prev_chars.starts_with(pair.start.as_str())
 6239                            && next_chars.starts_with(pair.end.as_str())
 6240                        {
 6241                            bracket_pair = Some(pair.clone());
 6242                            break;
 6243                        }
 6244                    }
 6245                    if let Some(pair) = bracket_pair {
 6246                        let start = snapshot.anchor_after(selection_head);
 6247                        let end = snapshot.anchor_after(selection_head);
 6248                        self.autoclose_regions.push(AutocloseRegion {
 6249                            selection_id: selection.id,
 6250                            range: start..end,
 6251                            pair,
 6252                        });
 6253                    }
 6254                }
 6255            }
 6256        }
 6257        Ok(())
 6258    }
 6259
 6260    pub fn move_to_next_snippet_tabstop(
 6261        &mut self,
 6262        window: &mut Window,
 6263        cx: &mut Context<Self>,
 6264    ) -> bool {
 6265        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6266    }
 6267
 6268    pub fn move_to_prev_snippet_tabstop(
 6269        &mut self,
 6270        window: &mut Window,
 6271        cx: &mut Context<Self>,
 6272    ) -> bool {
 6273        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6274    }
 6275
 6276    pub fn move_to_snippet_tabstop(
 6277        &mut self,
 6278        bias: Bias,
 6279        window: &mut Window,
 6280        cx: &mut Context<Self>,
 6281    ) -> bool {
 6282        if let Some(mut snippet) = self.snippet_stack.pop() {
 6283            match bias {
 6284                Bias::Left => {
 6285                    if snippet.active_index > 0 {
 6286                        snippet.active_index -= 1;
 6287                    } else {
 6288                        self.snippet_stack.push(snippet);
 6289                        return false;
 6290                    }
 6291                }
 6292                Bias::Right => {
 6293                    if snippet.active_index + 1 < snippet.ranges.len() {
 6294                        snippet.active_index += 1;
 6295                    } else {
 6296                        self.snippet_stack.push(snippet);
 6297                        return false;
 6298                    }
 6299                }
 6300            }
 6301            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6302                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6303                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6304                });
 6305
 6306                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6307                    if let Some(selection) = current_ranges.first() {
 6308                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6309                    }
 6310                }
 6311
 6312                // If snippet state is not at the last tabstop, push it back on the stack
 6313                if snippet.active_index + 1 < snippet.ranges.len() {
 6314                    self.snippet_stack.push(snippet);
 6315                }
 6316                return true;
 6317            }
 6318        }
 6319
 6320        false
 6321    }
 6322
 6323    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6324        self.transact(window, cx, |this, window, cx| {
 6325            this.select_all(&SelectAll, window, cx);
 6326            this.insert("", window, cx);
 6327        });
 6328    }
 6329
 6330    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6331        self.transact(window, cx, |this, window, cx| {
 6332            this.select_autoclose_pair(window, cx);
 6333            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6334            if !this.linked_edit_ranges.is_empty() {
 6335                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6336                let snapshot = this.buffer.read(cx).snapshot(cx);
 6337
 6338                for selection in selections.iter() {
 6339                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6340                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6341                    if selection_start.buffer_id != selection_end.buffer_id {
 6342                        continue;
 6343                    }
 6344                    if let Some(ranges) =
 6345                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6346                    {
 6347                        for (buffer, entries) in ranges {
 6348                            linked_ranges.entry(buffer).or_default().extend(entries);
 6349                        }
 6350                    }
 6351                }
 6352            }
 6353
 6354            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6355            if !this.selections.line_mode {
 6356                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6357                for selection in &mut selections {
 6358                    if selection.is_empty() {
 6359                        let old_head = selection.head();
 6360                        let mut new_head =
 6361                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6362                                .to_point(&display_map);
 6363                        if let Some((buffer, line_buffer_range)) = display_map
 6364                            .buffer_snapshot
 6365                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6366                        {
 6367                            let indent_size =
 6368                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6369                            let indent_len = match indent_size.kind {
 6370                                IndentKind::Space => {
 6371                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6372                                }
 6373                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6374                            };
 6375                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6376                                let indent_len = indent_len.get();
 6377                                new_head = cmp::min(
 6378                                    new_head,
 6379                                    MultiBufferPoint::new(
 6380                                        old_head.row,
 6381                                        ((old_head.column - 1) / indent_len) * indent_len,
 6382                                    ),
 6383                                );
 6384                            }
 6385                        }
 6386
 6387                        selection.set_head(new_head, SelectionGoal::None);
 6388                    }
 6389                }
 6390            }
 6391
 6392            this.signature_help_state.set_backspace_pressed(true);
 6393            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6394                s.select(selections)
 6395            });
 6396            this.insert("", window, cx);
 6397            let empty_str: Arc<str> = Arc::from("");
 6398            for (buffer, edits) in linked_ranges {
 6399                let snapshot = buffer.read(cx).snapshot();
 6400                use text::ToPoint as TP;
 6401
 6402                let edits = edits
 6403                    .into_iter()
 6404                    .map(|range| {
 6405                        let end_point = TP::to_point(&range.end, &snapshot);
 6406                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6407
 6408                        if end_point == start_point {
 6409                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6410                                .saturating_sub(1);
 6411                            start_point =
 6412                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6413                        };
 6414
 6415                        (start_point..end_point, empty_str.clone())
 6416                    })
 6417                    .sorted_by_key(|(range, _)| range.start)
 6418                    .collect::<Vec<_>>();
 6419                buffer.update(cx, |this, cx| {
 6420                    this.edit(edits, None, cx);
 6421                })
 6422            }
 6423            this.refresh_inline_completion(true, false, window, cx);
 6424            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6425        });
 6426    }
 6427
 6428    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6429        self.transact(window, cx, |this, window, cx| {
 6430            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6431                let line_mode = s.line_mode;
 6432                s.move_with(|map, selection| {
 6433                    if selection.is_empty() && !line_mode {
 6434                        let cursor = movement::right(map, selection.head());
 6435                        selection.end = cursor;
 6436                        selection.reversed = true;
 6437                        selection.goal = SelectionGoal::None;
 6438                    }
 6439                })
 6440            });
 6441            this.insert("", window, cx);
 6442            this.refresh_inline_completion(true, false, window, cx);
 6443        });
 6444    }
 6445
 6446    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6447        if self.move_to_prev_snippet_tabstop(window, cx) {
 6448            return;
 6449        }
 6450
 6451        self.outdent(&Outdent, window, cx);
 6452    }
 6453
 6454    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6455        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6456            return;
 6457        }
 6458
 6459        let mut selections = self.selections.all_adjusted(cx);
 6460        let buffer = self.buffer.read(cx);
 6461        let snapshot = buffer.snapshot(cx);
 6462        let rows_iter = selections.iter().map(|s| s.head().row);
 6463        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6464
 6465        let mut edits = Vec::new();
 6466        let mut prev_edited_row = 0;
 6467        let mut row_delta = 0;
 6468        for selection in &mut selections {
 6469            if selection.start.row != prev_edited_row {
 6470                row_delta = 0;
 6471            }
 6472            prev_edited_row = selection.end.row;
 6473
 6474            // If the selection is non-empty, then increase the indentation of the selected lines.
 6475            if !selection.is_empty() {
 6476                row_delta =
 6477                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6478                continue;
 6479            }
 6480
 6481            // If the selection is empty and the cursor is in the leading whitespace before the
 6482            // suggested indentation, then auto-indent the line.
 6483            let cursor = selection.head();
 6484            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6485            if let Some(suggested_indent) =
 6486                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6487            {
 6488                if cursor.column < suggested_indent.len
 6489                    && cursor.column <= current_indent.len
 6490                    && current_indent.len <= suggested_indent.len
 6491                {
 6492                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6493                    selection.end = selection.start;
 6494                    if row_delta == 0 {
 6495                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6496                            cursor.row,
 6497                            current_indent,
 6498                            suggested_indent,
 6499                        ));
 6500                        row_delta = suggested_indent.len - current_indent.len;
 6501                    }
 6502                    continue;
 6503                }
 6504            }
 6505
 6506            // Otherwise, insert a hard or soft tab.
 6507            let settings = buffer.settings_at(cursor, cx);
 6508            let tab_size = if settings.hard_tabs {
 6509                IndentSize::tab()
 6510            } else {
 6511                let tab_size = settings.tab_size.get();
 6512                let char_column = snapshot
 6513                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6514                    .flat_map(str::chars)
 6515                    .count()
 6516                    + row_delta as usize;
 6517                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6518                IndentSize::spaces(chars_to_next_tab_stop)
 6519            };
 6520            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6521            selection.end = selection.start;
 6522            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6523            row_delta += tab_size.len;
 6524        }
 6525
 6526        self.transact(window, cx, |this, window, cx| {
 6527            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6528            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6529                s.select(selections)
 6530            });
 6531            this.refresh_inline_completion(true, false, window, cx);
 6532        });
 6533    }
 6534
 6535    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6536        if self.read_only(cx) {
 6537            return;
 6538        }
 6539        let mut selections = self.selections.all::<Point>(cx);
 6540        let mut prev_edited_row = 0;
 6541        let mut row_delta = 0;
 6542        let mut edits = Vec::new();
 6543        let buffer = self.buffer.read(cx);
 6544        let snapshot = buffer.snapshot(cx);
 6545        for selection in &mut selections {
 6546            if selection.start.row != prev_edited_row {
 6547                row_delta = 0;
 6548            }
 6549            prev_edited_row = selection.end.row;
 6550
 6551            row_delta =
 6552                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6553        }
 6554
 6555        self.transact(window, cx, |this, window, cx| {
 6556            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6557            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6558                s.select(selections)
 6559            });
 6560        });
 6561    }
 6562
 6563    fn indent_selection(
 6564        buffer: &MultiBuffer,
 6565        snapshot: &MultiBufferSnapshot,
 6566        selection: &mut Selection<Point>,
 6567        edits: &mut Vec<(Range<Point>, String)>,
 6568        delta_for_start_row: u32,
 6569        cx: &App,
 6570    ) -> u32 {
 6571        let settings = buffer.settings_at(selection.start, cx);
 6572        let tab_size = settings.tab_size.get();
 6573        let indent_kind = if settings.hard_tabs {
 6574            IndentKind::Tab
 6575        } else {
 6576            IndentKind::Space
 6577        };
 6578        let mut start_row = selection.start.row;
 6579        let mut end_row = selection.end.row + 1;
 6580
 6581        // If a selection ends at the beginning of a line, don't indent
 6582        // that last line.
 6583        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6584            end_row -= 1;
 6585        }
 6586
 6587        // Avoid re-indenting a row that has already been indented by a
 6588        // previous selection, but still update this selection's column
 6589        // to reflect that indentation.
 6590        if delta_for_start_row > 0 {
 6591            start_row += 1;
 6592            selection.start.column += delta_for_start_row;
 6593            if selection.end.row == selection.start.row {
 6594                selection.end.column += delta_for_start_row;
 6595            }
 6596        }
 6597
 6598        let mut delta_for_end_row = 0;
 6599        let has_multiple_rows = start_row + 1 != end_row;
 6600        for row in start_row..end_row {
 6601            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6602            let indent_delta = match (current_indent.kind, indent_kind) {
 6603                (IndentKind::Space, IndentKind::Space) => {
 6604                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6605                    IndentSize::spaces(columns_to_next_tab_stop)
 6606                }
 6607                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6608                (_, IndentKind::Tab) => IndentSize::tab(),
 6609            };
 6610
 6611            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6612                0
 6613            } else {
 6614                selection.start.column
 6615            };
 6616            let row_start = Point::new(row, start);
 6617            edits.push((
 6618                row_start..row_start,
 6619                indent_delta.chars().collect::<String>(),
 6620            ));
 6621
 6622            // Update this selection's endpoints to reflect the indentation.
 6623            if row == selection.start.row {
 6624                selection.start.column += indent_delta.len;
 6625            }
 6626            if row == selection.end.row {
 6627                selection.end.column += indent_delta.len;
 6628                delta_for_end_row = indent_delta.len;
 6629            }
 6630        }
 6631
 6632        if selection.start.row == selection.end.row {
 6633            delta_for_start_row + delta_for_end_row
 6634        } else {
 6635            delta_for_end_row
 6636        }
 6637    }
 6638
 6639    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6640        if self.read_only(cx) {
 6641            return;
 6642        }
 6643        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6644        let selections = self.selections.all::<Point>(cx);
 6645        let mut deletion_ranges = Vec::new();
 6646        let mut last_outdent = None;
 6647        {
 6648            let buffer = self.buffer.read(cx);
 6649            let snapshot = buffer.snapshot(cx);
 6650            for selection in &selections {
 6651                let settings = buffer.settings_at(selection.start, cx);
 6652                let tab_size = settings.tab_size.get();
 6653                let mut rows = selection.spanned_rows(false, &display_map);
 6654
 6655                // Avoid re-outdenting a row that has already been outdented by a
 6656                // previous selection.
 6657                if let Some(last_row) = last_outdent {
 6658                    if last_row == rows.start {
 6659                        rows.start = rows.start.next_row();
 6660                    }
 6661                }
 6662                let has_multiple_rows = rows.len() > 1;
 6663                for row in rows.iter_rows() {
 6664                    let indent_size = snapshot.indent_size_for_line(row);
 6665                    if indent_size.len > 0 {
 6666                        let deletion_len = match indent_size.kind {
 6667                            IndentKind::Space => {
 6668                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6669                                if columns_to_prev_tab_stop == 0 {
 6670                                    tab_size
 6671                                } else {
 6672                                    columns_to_prev_tab_stop
 6673                                }
 6674                            }
 6675                            IndentKind::Tab => 1,
 6676                        };
 6677                        let start = if has_multiple_rows
 6678                            || deletion_len > selection.start.column
 6679                            || indent_size.len < selection.start.column
 6680                        {
 6681                            0
 6682                        } else {
 6683                            selection.start.column - deletion_len
 6684                        };
 6685                        deletion_ranges.push(
 6686                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6687                        );
 6688                        last_outdent = Some(row);
 6689                    }
 6690                }
 6691            }
 6692        }
 6693
 6694        self.transact(window, cx, |this, window, cx| {
 6695            this.buffer.update(cx, |buffer, cx| {
 6696                let empty_str: Arc<str> = Arc::default();
 6697                buffer.edit(
 6698                    deletion_ranges
 6699                        .into_iter()
 6700                        .map(|range| (range, empty_str.clone())),
 6701                    None,
 6702                    cx,
 6703                );
 6704            });
 6705            let selections = this.selections.all::<usize>(cx);
 6706            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6707                s.select(selections)
 6708            });
 6709        });
 6710    }
 6711
 6712    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6713        if self.read_only(cx) {
 6714            return;
 6715        }
 6716        let selections = self
 6717            .selections
 6718            .all::<usize>(cx)
 6719            .into_iter()
 6720            .map(|s| s.range());
 6721
 6722        self.transact(window, cx, |this, window, cx| {
 6723            this.buffer.update(cx, |buffer, cx| {
 6724                buffer.autoindent_ranges(selections, cx);
 6725            });
 6726            let selections = this.selections.all::<usize>(cx);
 6727            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6728                s.select(selections)
 6729            });
 6730        });
 6731    }
 6732
 6733    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6734        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6735        let selections = self.selections.all::<Point>(cx);
 6736
 6737        let mut new_cursors = Vec::new();
 6738        let mut edit_ranges = Vec::new();
 6739        let mut selections = selections.iter().peekable();
 6740        while let Some(selection) = selections.next() {
 6741            let mut rows = selection.spanned_rows(false, &display_map);
 6742            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6743
 6744            // Accumulate contiguous regions of rows that we want to delete.
 6745            while let Some(next_selection) = selections.peek() {
 6746                let next_rows = next_selection.spanned_rows(false, &display_map);
 6747                if next_rows.start <= rows.end {
 6748                    rows.end = next_rows.end;
 6749                    selections.next().unwrap();
 6750                } else {
 6751                    break;
 6752                }
 6753            }
 6754
 6755            let buffer = &display_map.buffer_snapshot;
 6756            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6757            let edit_end;
 6758            let cursor_buffer_row;
 6759            if buffer.max_point().row >= rows.end.0 {
 6760                // If there's a line after the range, delete the \n from the end of the row range
 6761                // and position the cursor on the next line.
 6762                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6763                cursor_buffer_row = rows.end;
 6764            } else {
 6765                // If there isn't a line after the range, delete the \n from the line before the
 6766                // start of the row range and position the cursor there.
 6767                edit_start = edit_start.saturating_sub(1);
 6768                edit_end = buffer.len();
 6769                cursor_buffer_row = rows.start.previous_row();
 6770            }
 6771
 6772            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6773            *cursor.column_mut() =
 6774                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6775
 6776            new_cursors.push((
 6777                selection.id,
 6778                buffer.anchor_after(cursor.to_point(&display_map)),
 6779            ));
 6780            edit_ranges.push(edit_start..edit_end);
 6781        }
 6782
 6783        self.transact(window, cx, |this, window, cx| {
 6784            let buffer = this.buffer.update(cx, |buffer, cx| {
 6785                let empty_str: Arc<str> = Arc::default();
 6786                buffer.edit(
 6787                    edit_ranges
 6788                        .into_iter()
 6789                        .map(|range| (range, empty_str.clone())),
 6790                    None,
 6791                    cx,
 6792                );
 6793                buffer.snapshot(cx)
 6794            });
 6795            let new_selections = new_cursors
 6796                .into_iter()
 6797                .map(|(id, cursor)| {
 6798                    let cursor = cursor.to_point(&buffer);
 6799                    Selection {
 6800                        id,
 6801                        start: cursor,
 6802                        end: cursor,
 6803                        reversed: false,
 6804                        goal: SelectionGoal::None,
 6805                    }
 6806                })
 6807                .collect();
 6808
 6809            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6810                s.select(new_selections);
 6811            });
 6812        });
 6813    }
 6814
 6815    pub fn join_lines_impl(
 6816        &mut self,
 6817        insert_whitespace: bool,
 6818        window: &mut Window,
 6819        cx: &mut Context<Self>,
 6820    ) {
 6821        if self.read_only(cx) {
 6822            return;
 6823        }
 6824        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6825        for selection in self.selections.all::<Point>(cx) {
 6826            let start = MultiBufferRow(selection.start.row);
 6827            // Treat single line selections as if they include the next line. Otherwise this action
 6828            // would do nothing for single line selections individual cursors.
 6829            let end = if selection.start.row == selection.end.row {
 6830                MultiBufferRow(selection.start.row + 1)
 6831            } else {
 6832                MultiBufferRow(selection.end.row)
 6833            };
 6834
 6835            if let Some(last_row_range) = row_ranges.last_mut() {
 6836                if start <= last_row_range.end {
 6837                    last_row_range.end = end;
 6838                    continue;
 6839                }
 6840            }
 6841            row_ranges.push(start..end);
 6842        }
 6843
 6844        let snapshot = self.buffer.read(cx).snapshot(cx);
 6845        let mut cursor_positions = Vec::new();
 6846        for row_range in &row_ranges {
 6847            let anchor = snapshot.anchor_before(Point::new(
 6848                row_range.end.previous_row().0,
 6849                snapshot.line_len(row_range.end.previous_row()),
 6850            ));
 6851            cursor_positions.push(anchor..anchor);
 6852        }
 6853
 6854        self.transact(window, cx, |this, window, cx| {
 6855            for row_range in row_ranges.into_iter().rev() {
 6856                for row in row_range.iter_rows().rev() {
 6857                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6858                    let next_line_row = row.next_row();
 6859                    let indent = snapshot.indent_size_for_line(next_line_row);
 6860                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6861
 6862                    let replace =
 6863                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6864                            " "
 6865                        } else {
 6866                            ""
 6867                        };
 6868
 6869                    this.buffer.update(cx, |buffer, cx| {
 6870                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6871                    });
 6872                }
 6873            }
 6874
 6875            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6876                s.select_anchor_ranges(cursor_positions)
 6877            });
 6878        });
 6879    }
 6880
 6881    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6882        self.join_lines_impl(true, window, cx);
 6883    }
 6884
 6885    pub fn sort_lines_case_sensitive(
 6886        &mut self,
 6887        _: &SortLinesCaseSensitive,
 6888        window: &mut Window,
 6889        cx: &mut Context<Self>,
 6890    ) {
 6891        self.manipulate_lines(window, cx, |lines| lines.sort())
 6892    }
 6893
 6894    pub fn sort_lines_case_insensitive(
 6895        &mut self,
 6896        _: &SortLinesCaseInsensitive,
 6897        window: &mut Window,
 6898        cx: &mut Context<Self>,
 6899    ) {
 6900        self.manipulate_lines(window, cx, |lines| {
 6901            lines.sort_by_key(|line| line.to_lowercase())
 6902        })
 6903    }
 6904
 6905    pub fn unique_lines_case_insensitive(
 6906        &mut self,
 6907        _: &UniqueLinesCaseInsensitive,
 6908        window: &mut Window,
 6909        cx: &mut Context<Self>,
 6910    ) {
 6911        self.manipulate_lines(window, cx, |lines| {
 6912            let mut seen = HashSet::default();
 6913            lines.retain(|line| seen.insert(line.to_lowercase()));
 6914        })
 6915    }
 6916
 6917    pub fn unique_lines_case_sensitive(
 6918        &mut self,
 6919        _: &UniqueLinesCaseSensitive,
 6920        window: &mut Window,
 6921        cx: &mut Context<Self>,
 6922    ) {
 6923        self.manipulate_lines(window, cx, |lines| {
 6924            let mut seen = HashSet::default();
 6925            lines.retain(|line| seen.insert(*line));
 6926        })
 6927    }
 6928
 6929    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6930        let mut revert_changes = HashMap::default();
 6931        let snapshot = self.snapshot(window, cx);
 6932        for hunk in snapshot
 6933            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6934        {
 6935            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6936        }
 6937        if !revert_changes.is_empty() {
 6938            self.transact(window, cx, |editor, window, cx| {
 6939                editor.revert(revert_changes, window, cx);
 6940            });
 6941        }
 6942    }
 6943
 6944    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6945        let Some(project) = self.project.clone() else {
 6946            return;
 6947        };
 6948        self.reload(project, window, cx)
 6949            .detach_and_notify_err(window, cx);
 6950    }
 6951
 6952    pub fn revert_selected_hunks(
 6953        &mut self,
 6954        _: &RevertSelectedHunks,
 6955        window: &mut Window,
 6956        cx: &mut Context<Self>,
 6957    ) {
 6958        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6959        self.revert_hunks_in_ranges(selections, window, cx);
 6960    }
 6961
 6962    fn revert_hunks_in_ranges(
 6963        &mut self,
 6964        ranges: impl Iterator<Item = Range<Point>>,
 6965        window: &mut Window,
 6966        cx: &mut Context<Editor>,
 6967    ) {
 6968        let mut revert_changes = HashMap::default();
 6969        let snapshot = self.snapshot(window, cx);
 6970        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6971            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6972        }
 6973        if !revert_changes.is_empty() {
 6974            self.transact(window, cx, |editor, window, cx| {
 6975                editor.revert(revert_changes, window, cx);
 6976            });
 6977        }
 6978    }
 6979
 6980    pub fn open_active_item_in_terminal(
 6981        &mut self,
 6982        _: &OpenInTerminal,
 6983        window: &mut Window,
 6984        cx: &mut Context<Self>,
 6985    ) {
 6986        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6987            let project_path = buffer.read(cx).project_path(cx)?;
 6988            let project = self.project.as_ref()?.read(cx);
 6989            let entry = project.entry_for_path(&project_path, cx)?;
 6990            let parent = match &entry.canonical_path {
 6991                Some(canonical_path) => canonical_path.to_path_buf(),
 6992                None => project.absolute_path(&project_path, cx)?,
 6993            }
 6994            .parent()?
 6995            .to_path_buf();
 6996            Some(parent)
 6997        }) {
 6998            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6999        }
 7000    }
 7001
 7002    pub fn prepare_revert_change(
 7003        &self,
 7004        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7005        hunk: &MultiBufferDiffHunk,
 7006        cx: &mut App,
 7007    ) -> Option<()> {
 7008        let buffer = self.buffer.read(cx);
 7009        let diff = buffer.diff_for(hunk.buffer_id)?;
 7010        let buffer = buffer.buffer(hunk.buffer_id)?;
 7011        let buffer = buffer.read(cx);
 7012        let original_text = diff
 7013            .read(cx)
 7014            .base_text()
 7015            .as_ref()?
 7016            .as_rope()
 7017            .slice(hunk.diff_base_byte_range.clone());
 7018        let buffer_snapshot = buffer.snapshot();
 7019        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7020        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7021            probe
 7022                .0
 7023                .start
 7024                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7025                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7026        }) {
 7027            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7028            Some(())
 7029        } else {
 7030            None
 7031        }
 7032    }
 7033
 7034    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7035        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7036    }
 7037
 7038    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7039        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7040    }
 7041
 7042    fn manipulate_lines<Fn>(
 7043        &mut self,
 7044        window: &mut Window,
 7045        cx: &mut Context<Self>,
 7046        mut callback: Fn,
 7047    ) where
 7048        Fn: FnMut(&mut Vec<&str>),
 7049    {
 7050        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7051        let buffer = self.buffer.read(cx).snapshot(cx);
 7052
 7053        let mut edits = Vec::new();
 7054
 7055        let selections = self.selections.all::<Point>(cx);
 7056        let mut selections = selections.iter().peekable();
 7057        let mut contiguous_row_selections = Vec::new();
 7058        let mut new_selections = Vec::new();
 7059        let mut added_lines = 0;
 7060        let mut removed_lines = 0;
 7061
 7062        while let Some(selection) = selections.next() {
 7063            let (start_row, end_row) = consume_contiguous_rows(
 7064                &mut contiguous_row_selections,
 7065                selection,
 7066                &display_map,
 7067                &mut selections,
 7068            );
 7069
 7070            let start_point = Point::new(start_row.0, 0);
 7071            let end_point = Point::new(
 7072                end_row.previous_row().0,
 7073                buffer.line_len(end_row.previous_row()),
 7074            );
 7075            let text = buffer
 7076                .text_for_range(start_point..end_point)
 7077                .collect::<String>();
 7078
 7079            let mut lines = text.split('\n').collect_vec();
 7080
 7081            let lines_before = lines.len();
 7082            callback(&mut lines);
 7083            let lines_after = lines.len();
 7084
 7085            edits.push((start_point..end_point, lines.join("\n")));
 7086
 7087            // Selections must change based on added and removed line count
 7088            let start_row =
 7089                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7090            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7091            new_selections.push(Selection {
 7092                id: selection.id,
 7093                start: start_row,
 7094                end: end_row,
 7095                goal: SelectionGoal::None,
 7096                reversed: selection.reversed,
 7097            });
 7098
 7099            if lines_after > lines_before {
 7100                added_lines += lines_after - lines_before;
 7101            } else if lines_before > lines_after {
 7102                removed_lines += lines_before - lines_after;
 7103            }
 7104        }
 7105
 7106        self.transact(window, cx, |this, window, cx| {
 7107            let buffer = this.buffer.update(cx, |buffer, cx| {
 7108                buffer.edit(edits, None, cx);
 7109                buffer.snapshot(cx)
 7110            });
 7111
 7112            // Recalculate offsets on newly edited buffer
 7113            let new_selections = new_selections
 7114                .iter()
 7115                .map(|s| {
 7116                    let start_point = Point::new(s.start.0, 0);
 7117                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7118                    Selection {
 7119                        id: s.id,
 7120                        start: buffer.point_to_offset(start_point),
 7121                        end: buffer.point_to_offset(end_point),
 7122                        goal: s.goal,
 7123                        reversed: s.reversed,
 7124                    }
 7125                })
 7126                .collect();
 7127
 7128            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7129                s.select(new_selections);
 7130            });
 7131
 7132            this.request_autoscroll(Autoscroll::fit(), cx);
 7133        });
 7134    }
 7135
 7136    pub fn convert_to_upper_case(
 7137        &mut self,
 7138        _: &ConvertToUpperCase,
 7139        window: &mut Window,
 7140        cx: &mut Context<Self>,
 7141    ) {
 7142        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7143    }
 7144
 7145    pub fn convert_to_lower_case(
 7146        &mut self,
 7147        _: &ConvertToLowerCase,
 7148        window: &mut Window,
 7149        cx: &mut Context<Self>,
 7150    ) {
 7151        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7152    }
 7153
 7154    pub fn convert_to_title_case(
 7155        &mut self,
 7156        _: &ConvertToTitleCase,
 7157        window: &mut Window,
 7158        cx: &mut Context<Self>,
 7159    ) {
 7160        self.manipulate_text(window, cx, |text| {
 7161            text.split('\n')
 7162                .map(|line| line.to_case(Case::Title))
 7163                .join("\n")
 7164        })
 7165    }
 7166
 7167    pub fn convert_to_snake_case(
 7168        &mut self,
 7169        _: &ConvertToSnakeCase,
 7170        window: &mut Window,
 7171        cx: &mut Context<Self>,
 7172    ) {
 7173        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7174    }
 7175
 7176    pub fn convert_to_kebab_case(
 7177        &mut self,
 7178        _: &ConvertToKebabCase,
 7179        window: &mut Window,
 7180        cx: &mut Context<Self>,
 7181    ) {
 7182        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7183    }
 7184
 7185    pub fn convert_to_upper_camel_case(
 7186        &mut self,
 7187        _: &ConvertToUpperCamelCase,
 7188        window: &mut Window,
 7189        cx: &mut Context<Self>,
 7190    ) {
 7191        self.manipulate_text(window, cx, |text| {
 7192            text.split('\n')
 7193                .map(|line| line.to_case(Case::UpperCamel))
 7194                .join("\n")
 7195        })
 7196    }
 7197
 7198    pub fn convert_to_lower_camel_case(
 7199        &mut self,
 7200        _: &ConvertToLowerCamelCase,
 7201        window: &mut Window,
 7202        cx: &mut Context<Self>,
 7203    ) {
 7204        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7205    }
 7206
 7207    pub fn convert_to_opposite_case(
 7208        &mut self,
 7209        _: &ConvertToOppositeCase,
 7210        window: &mut Window,
 7211        cx: &mut Context<Self>,
 7212    ) {
 7213        self.manipulate_text(window, cx, |text| {
 7214            text.chars()
 7215                .fold(String::with_capacity(text.len()), |mut t, c| {
 7216                    if c.is_uppercase() {
 7217                        t.extend(c.to_lowercase());
 7218                    } else {
 7219                        t.extend(c.to_uppercase());
 7220                    }
 7221                    t
 7222                })
 7223        })
 7224    }
 7225
 7226    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7227    where
 7228        Fn: FnMut(&str) -> String,
 7229    {
 7230        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7231        let buffer = self.buffer.read(cx).snapshot(cx);
 7232
 7233        let mut new_selections = Vec::new();
 7234        let mut edits = Vec::new();
 7235        let mut selection_adjustment = 0i32;
 7236
 7237        for selection in self.selections.all::<usize>(cx) {
 7238            let selection_is_empty = selection.is_empty();
 7239
 7240            let (start, end) = if selection_is_empty {
 7241                let word_range = movement::surrounding_word(
 7242                    &display_map,
 7243                    selection.start.to_display_point(&display_map),
 7244                );
 7245                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7246                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7247                (start, end)
 7248            } else {
 7249                (selection.start, selection.end)
 7250            };
 7251
 7252            let text = buffer.text_for_range(start..end).collect::<String>();
 7253            let old_length = text.len() as i32;
 7254            let text = callback(&text);
 7255
 7256            new_selections.push(Selection {
 7257                start: (start as i32 - selection_adjustment) as usize,
 7258                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7259                goal: SelectionGoal::None,
 7260                ..selection
 7261            });
 7262
 7263            selection_adjustment += old_length - text.len() as i32;
 7264
 7265            edits.push((start..end, text));
 7266        }
 7267
 7268        self.transact(window, cx, |this, window, cx| {
 7269            this.buffer.update(cx, |buffer, cx| {
 7270                buffer.edit(edits, None, cx);
 7271            });
 7272
 7273            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7274                s.select(new_selections);
 7275            });
 7276
 7277            this.request_autoscroll(Autoscroll::fit(), cx);
 7278        });
 7279    }
 7280
 7281    pub fn duplicate(
 7282        &mut self,
 7283        upwards: bool,
 7284        whole_lines: bool,
 7285        window: &mut Window,
 7286        cx: &mut Context<Self>,
 7287    ) {
 7288        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7289        let buffer = &display_map.buffer_snapshot;
 7290        let selections = self.selections.all::<Point>(cx);
 7291
 7292        let mut edits = Vec::new();
 7293        let mut selections_iter = selections.iter().peekable();
 7294        while let Some(selection) = selections_iter.next() {
 7295            let mut rows = selection.spanned_rows(false, &display_map);
 7296            // duplicate line-wise
 7297            if whole_lines || selection.start == selection.end {
 7298                // Avoid duplicating the same lines twice.
 7299                while let Some(next_selection) = selections_iter.peek() {
 7300                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7301                    if next_rows.start < rows.end {
 7302                        rows.end = next_rows.end;
 7303                        selections_iter.next().unwrap();
 7304                    } else {
 7305                        break;
 7306                    }
 7307                }
 7308
 7309                // Copy the text from the selected row region and splice it either at the start
 7310                // or end of the region.
 7311                let start = Point::new(rows.start.0, 0);
 7312                let end = Point::new(
 7313                    rows.end.previous_row().0,
 7314                    buffer.line_len(rows.end.previous_row()),
 7315                );
 7316                let text = buffer
 7317                    .text_for_range(start..end)
 7318                    .chain(Some("\n"))
 7319                    .collect::<String>();
 7320                let insert_location = if upwards {
 7321                    Point::new(rows.end.0, 0)
 7322                } else {
 7323                    start
 7324                };
 7325                edits.push((insert_location..insert_location, text));
 7326            } else {
 7327                // duplicate character-wise
 7328                let start = selection.start;
 7329                let end = selection.end;
 7330                let text = buffer.text_for_range(start..end).collect::<String>();
 7331                edits.push((selection.end..selection.end, text));
 7332            }
 7333        }
 7334
 7335        self.transact(window, cx, |this, _, cx| {
 7336            this.buffer.update(cx, |buffer, cx| {
 7337                buffer.edit(edits, None, cx);
 7338            });
 7339
 7340            this.request_autoscroll(Autoscroll::fit(), cx);
 7341        });
 7342    }
 7343
 7344    pub fn duplicate_line_up(
 7345        &mut self,
 7346        _: &DuplicateLineUp,
 7347        window: &mut Window,
 7348        cx: &mut Context<Self>,
 7349    ) {
 7350        self.duplicate(true, true, window, cx);
 7351    }
 7352
 7353    pub fn duplicate_line_down(
 7354        &mut self,
 7355        _: &DuplicateLineDown,
 7356        window: &mut Window,
 7357        cx: &mut Context<Self>,
 7358    ) {
 7359        self.duplicate(false, true, window, cx);
 7360    }
 7361
 7362    pub fn duplicate_selection(
 7363        &mut self,
 7364        _: &DuplicateSelection,
 7365        window: &mut Window,
 7366        cx: &mut Context<Self>,
 7367    ) {
 7368        self.duplicate(false, false, window, cx);
 7369    }
 7370
 7371    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7372        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7373        let buffer = self.buffer.read(cx).snapshot(cx);
 7374
 7375        let mut edits = Vec::new();
 7376        let mut unfold_ranges = Vec::new();
 7377        let mut refold_creases = Vec::new();
 7378
 7379        let selections = self.selections.all::<Point>(cx);
 7380        let mut selections = selections.iter().peekable();
 7381        let mut contiguous_row_selections = Vec::new();
 7382        let mut new_selections = Vec::new();
 7383
 7384        while let Some(selection) = selections.next() {
 7385            // Find all the selections that span a contiguous row range
 7386            let (start_row, end_row) = consume_contiguous_rows(
 7387                &mut contiguous_row_selections,
 7388                selection,
 7389                &display_map,
 7390                &mut selections,
 7391            );
 7392
 7393            // Move the text spanned by the row range to be before the line preceding the row range
 7394            if start_row.0 > 0 {
 7395                let range_to_move = Point::new(
 7396                    start_row.previous_row().0,
 7397                    buffer.line_len(start_row.previous_row()),
 7398                )
 7399                    ..Point::new(
 7400                        end_row.previous_row().0,
 7401                        buffer.line_len(end_row.previous_row()),
 7402                    );
 7403                let insertion_point = display_map
 7404                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7405                    .0;
 7406
 7407                // Don't move lines across excerpts
 7408                if buffer
 7409                    .excerpt_containing(insertion_point..range_to_move.end)
 7410                    .is_some()
 7411                {
 7412                    let text = buffer
 7413                        .text_for_range(range_to_move.clone())
 7414                        .flat_map(|s| s.chars())
 7415                        .skip(1)
 7416                        .chain(['\n'])
 7417                        .collect::<String>();
 7418
 7419                    edits.push((
 7420                        buffer.anchor_after(range_to_move.start)
 7421                            ..buffer.anchor_before(range_to_move.end),
 7422                        String::new(),
 7423                    ));
 7424                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7425                    edits.push((insertion_anchor..insertion_anchor, text));
 7426
 7427                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7428
 7429                    // Move selections up
 7430                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7431                        |mut selection| {
 7432                            selection.start.row -= row_delta;
 7433                            selection.end.row -= row_delta;
 7434                            selection
 7435                        },
 7436                    ));
 7437
 7438                    // Move folds up
 7439                    unfold_ranges.push(range_to_move.clone());
 7440                    for fold in display_map.folds_in_range(
 7441                        buffer.anchor_before(range_to_move.start)
 7442                            ..buffer.anchor_after(range_to_move.end),
 7443                    ) {
 7444                        let mut start = fold.range.start.to_point(&buffer);
 7445                        let mut end = fold.range.end.to_point(&buffer);
 7446                        start.row -= row_delta;
 7447                        end.row -= row_delta;
 7448                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7449                    }
 7450                }
 7451            }
 7452
 7453            // If we didn't move line(s), preserve the existing selections
 7454            new_selections.append(&mut contiguous_row_selections);
 7455        }
 7456
 7457        self.transact(window, cx, |this, window, cx| {
 7458            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7459            this.buffer.update(cx, |buffer, cx| {
 7460                for (range, text) in edits {
 7461                    buffer.edit([(range, text)], None, cx);
 7462                }
 7463            });
 7464            this.fold_creases(refold_creases, true, window, cx);
 7465            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7466                s.select(new_selections);
 7467            })
 7468        });
 7469    }
 7470
 7471    pub fn move_line_down(
 7472        &mut self,
 7473        _: &MoveLineDown,
 7474        window: &mut Window,
 7475        cx: &mut Context<Self>,
 7476    ) {
 7477        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7478        let buffer = self.buffer.read(cx).snapshot(cx);
 7479
 7480        let mut edits = Vec::new();
 7481        let mut unfold_ranges = Vec::new();
 7482        let mut refold_creases = Vec::new();
 7483
 7484        let selections = self.selections.all::<Point>(cx);
 7485        let mut selections = selections.iter().peekable();
 7486        let mut contiguous_row_selections = Vec::new();
 7487        let mut new_selections = Vec::new();
 7488
 7489        while let Some(selection) = selections.next() {
 7490            // Find all the selections that span a contiguous row range
 7491            let (start_row, end_row) = consume_contiguous_rows(
 7492                &mut contiguous_row_selections,
 7493                selection,
 7494                &display_map,
 7495                &mut selections,
 7496            );
 7497
 7498            // Move the text spanned by the row range to be after the last line of the row range
 7499            if end_row.0 <= buffer.max_point().row {
 7500                let range_to_move =
 7501                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7502                let insertion_point = display_map
 7503                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7504                    .0;
 7505
 7506                // Don't move lines across excerpt boundaries
 7507                if buffer
 7508                    .excerpt_containing(range_to_move.start..insertion_point)
 7509                    .is_some()
 7510                {
 7511                    let mut text = String::from("\n");
 7512                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7513                    text.pop(); // Drop trailing newline
 7514                    edits.push((
 7515                        buffer.anchor_after(range_to_move.start)
 7516                            ..buffer.anchor_before(range_to_move.end),
 7517                        String::new(),
 7518                    ));
 7519                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7520                    edits.push((insertion_anchor..insertion_anchor, text));
 7521
 7522                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7523
 7524                    // Move selections down
 7525                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7526                        |mut selection| {
 7527                            selection.start.row += row_delta;
 7528                            selection.end.row += row_delta;
 7529                            selection
 7530                        },
 7531                    ));
 7532
 7533                    // Move folds down
 7534                    unfold_ranges.push(range_to_move.clone());
 7535                    for fold in display_map.folds_in_range(
 7536                        buffer.anchor_before(range_to_move.start)
 7537                            ..buffer.anchor_after(range_to_move.end),
 7538                    ) {
 7539                        let mut start = fold.range.start.to_point(&buffer);
 7540                        let mut end = fold.range.end.to_point(&buffer);
 7541                        start.row += row_delta;
 7542                        end.row += row_delta;
 7543                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7544                    }
 7545                }
 7546            }
 7547
 7548            // If we didn't move line(s), preserve the existing selections
 7549            new_selections.append(&mut contiguous_row_selections);
 7550        }
 7551
 7552        self.transact(window, cx, |this, window, cx| {
 7553            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7554            this.buffer.update(cx, |buffer, cx| {
 7555                for (range, text) in edits {
 7556                    buffer.edit([(range, text)], None, cx);
 7557                }
 7558            });
 7559            this.fold_creases(refold_creases, true, window, cx);
 7560            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7561                s.select(new_selections)
 7562            });
 7563        });
 7564    }
 7565
 7566    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7567        let text_layout_details = &self.text_layout_details(window);
 7568        self.transact(window, cx, |this, window, cx| {
 7569            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7570                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7571                let line_mode = s.line_mode;
 7572                s.move_with(|display_map, selection| {
 7573                    if !selection.is_empty() || line_mode {
 7574                        return;
 7575                    }
 7576
 7577                    let mut head = selection.head();
 7578                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7579                    if head.column() == display_map.line_len(head.row()) {
 7580                        transpose_offset = display_map
 7581                            .buffer_snapshot
 7582                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7583                    }
 7584
 7585                    if transpose_offset == 0 {
 7586                        return;
 7587                    }
 7588
 7589                    *head.column_mut() += 1;
 7590                    head = display_map.clip_point(head, Bias::Right);
 7591                    let goal = SelectionGoal::HorizontalPosition(
 7592                        display_map
 7593                            .x_for_display_point(head, text_layout_details)
 7594                            .into(),
 7595                    );
 7596                    selection.collapse_to(head, goal);
 7597
 7598                    let transpose_start = display_map
 7599                        .buffer_snapshot
 7600                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7601                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7602                        let transpose_end = display_map
 7603                            .buffer_snapshot
 7604                            .clip_offset(transpose_offset + 1, Bias::Right);
 7605                        if let Some(ch) =
 7606                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7607                        {
 7608                            edits.push((transpose_start..transpose_offset, String::new()));
 7609                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7610                        }
 7611                    }
 7612                });
 7613                edits
 7614            });
 7615            this.buffer
 7616                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7617            let selections = this.selections.all::<usize>(cx);
 7618            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7619                s.select(selections);
 7620            });
 7621        });
 7622    }
 7623
 7624    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7625        self.rewrap_impl(IsVimMode::No, cx)
 7626    }
 7627
 7628    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7629        let buffer = self.buffer.read(cx).snapshot(cx);
 7630        let selections = self.selections.all::<Point>(cx);
 7631        let mut selections = selections.iter().peekable();
 7632
 7633        let mut edits = Vec::new();
 7634        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7635
 7636        while let Some(selection) = selections.next() {
 7637            let mut start_row = selection.start.row;
 7638            let mut end_row = selection.end.row;
 7639
 7640            // Skip selections that overlap with a range that has already been rewrapped.
 7641            let selection_range = start_row..end_row;
 7642            if rewrapped_row_ranges
 7643                .iter()
 7644                .any(|range| range.overlaps(&selection_range))
 7645            {
 7646                continue;
 7647            }
 7648
 7649            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7650
 7651            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7652                match language_scope.language_name().as_ref() {
 7653                    "Markdown" | "Plain Text" => {
 7654                        should_rewrap = true;
 7655                    }
 7656                    _ => {}
 7657                }
 7658            }
 7659
 7660            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7661
 7662            // Since not all lines in the selection may be at the same indent
 7663            // level, choose the indent size that is the most common between all
 7664            // of the lines.
 7665            //
 7666            // If there is a tie, we use the deepest indent.
 7667            let (indent_size, indent_end) = {
 7668                let mut indent_size_occurrences = HashMap::default();
 7669                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7670
 7671                for row in start_row..=end_row {
 7672                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7673                    rows_by_indent_size.entry(indent).or_default().push(row);
 7674                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7675                }
 7676
 7677                let indent_size = indent_size_occurrences
 7678                    .into_iter()
 7679                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7680                    .map(|(indent, _)| indent)
 7681                    .unwrap_or_default();
 7682                let row = rows_by_indent_size[&indent_size][0];
 7683                let indent_end = Point::new(row, indent_size.len);
 7684
 7685                (indent_size, indent_end)
 7686            };
 7687
 7688            let mut line_prefix = indent_size.chars().collect::<String>();
 7689
 7690            if let Some(comment_prefix) =
 7691                buffer
 7692                    .language_scope_at(selection.head())
 7693                    .and_then(|language| {
 7694                        language
 7695                            .line_comment_prefixes()
 7696                            .iter()
 7697                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7698                            .cloned()
 7699                    })
 7700            {
 7701                line_prefix.push_str(&comment_prefix);
 7702                should_rewrap = true;
 7703            }
 7704
 7705            if !should_rewrap {
 7706                continue;
 7707            }
 7708
 7709            if selection.is_empty() {
 7710                'expand_upwards: while start_row > 0 {
 7711                    let prev_row = start_row - 1;
 7712                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7713                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7714                    {
 7715                        start_row = prev_row;
 7716                    } else {
 7717                        break 'expand_upwards;
 7718                    }
 7719                }
 7720
 7721                'expand_downwards: while end_row < buffer.max_point().row {
 7722                    let next_row = end_row + 1;
 7723                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7724                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7725                    {
 7726                        end_row = next_row;
 7727                    } else {
 7728                        break 'expand_downwards;
 7729                    }
 7730                }
 7731            }
 7732
 7733            let start = Point::new(start_row, 0);
 7734            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7735            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7736            let Some(lines_without_prefixes) = selection_text
 7737                .lines()
 7738                .map(|line| {
 7739                    line.strip_prefix(&line_prefix)
 7740                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7741                        .ok_or_else(|| {
 7742                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7743                        })
 7744                })
 7745                .collect::<Result<Vec<_>, _>>()
 7746                .log_err()
 7747            else {
 7748                continue;
 7749            };
 7750
 7751            let wrap_column = buffer
 7752                .settings_at(Point::new(start_row, 0), cx)
 7753                .preferred_line_length as usize;
 7754            let wrapped_text = wrap_with_prefix(
 7755                line_prefix,
 7756                lines_without_prefixes.join(" "),
 7757                wrap_column,
 7758                tab_size,
 7759            );
 7760
 7761            // TODO: should always use char-based diff while still supporting cursor behavior that
 7762            // matches vim.
 7763            let diff = match is_vim_mode {
 7764                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7765                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7766            };
 7767            let mut offset = start.to_offset(&buffer);
 7768            let mut moved_since_edit = true;
 7769
 7770            for change in diff.iter_all_changes() {
 7771                let value = change.value();
 7772                match change.tag() {
 7773                    ChangeTag::Equal => {
 7774                        offset += value.len();
 7775                        moved_since_edit = true;
 7776                    }
 7777                    ChangeTag::Delete => {
 7778                        let start = buffer.anchor_after(offset);
 7779                        let end = buffer.anchor_before(offset + value.len());
 7780
 7781                        if moved_since_edit {
 7782                            edits.push((start..end, String::new()));
 7783                        } else {
 7784                            edits.last_mut().unwrap().0.end = end;
 7785                        }
 7786
 7787                        offset += value.len();
 7788                        moved_since_edit = false;
 7789                    }
 7790                    ChangeTag::Insert => {
 7791                        if moved_since_edit {
 7792                            let anchor = buffer.anchor_after(offset);
 7793                            edits.push((anchor..anchor, value.to_string()));
 7794                        } else {
 7795                            edits.last_mut().unwrap().1.push_str(value);
 7796                        }
 7797
 7798                        moved_since_edit = false;
 7799                    }
 7800                }
 7801            }
 7802
 7803            rewrapped_row_ranges.push(start_row..=end_row);
 7804        }
 7805
 7806        self.buffer
 7807            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7808    }
 7809
 7810    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7811        let mut text = String::new();
 7812        let buffer = self.buffer.read(cx).snapshot(cx);
 7813        let mut selections = self.selections.all::<Point>(cx);
 7814        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7815        {
 7816            let max_point = buffer.max_point();
 7817            let mut is_first = true;
 7818            for selection in &mut selections {
 7819                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7820                if is_entire_line {
 7821                    selection.start = Point::new(selection.start.row, 0);
 7822                    if !selection.is_empty() && selection.end.column == 0 {
 7823                        selection.end = cmp::min(max_point, selection.end);
 7824                    } else {
 7825                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7826                    }
 7827                    selection.goal = SelectionGoal::None;
 7828                }
 7829                if is_first {
 7830                    is_first = false;
 7831                } else {
 7832                    text += "\n";
 7833                }
 7834                let mut len = 0;
 7835                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7836                    text.push_str(chunk);
 7837                    len += chunk.len();
 7838                }
 7839                clipboard_selections.push(ClipboardSelection {
 7840                    len,
 7841                    is_entire_line,
 7842                    first_line_indent: buffer
 7843                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7844                        .len,
 7845                });
 7846            }
 7847        }
 7848
 7849        self.transact(window, cx, |this, window, cx| {
 7850            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7851                s.select(selections);
 7852            });
 7853            this.insert("", window, cx);
 7854        });
 7855        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7856    }
 7857
 7858    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7859        let item = self.cut_common(window, cx);
 7860        cx.write_to_clipboard(item);
 7861    }
 7862
 7863    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7864        self.change_selections(None, window, cx, |s| {
 7865            s.move_with(|snapshot, sel| {
 7866                if sel.is_empty() {
 7867                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7868                }
 7869            });
 7870        });
 7871        let item = self.cut_common(window, cx);
 7872        cx.set_global(KillRing(item))
 7873    }
 7874
 7875    pub fn kill_ring_yank(
 7876        &mut self,
 7877        _: &KillRingYank,
 7878        window: &mut Window,
 7879        cx: &mut Context<Self>,
 7880    ) {
 7881        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7882            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7883                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7884            } else {
 7885                return;
 7886            }
 7887        } else {
 7888            return;
 7889        };
 7890        self.do_paste(&text, metadata, false, window, cx);
 7891    }
 7892
 7893    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7894        let selections = self.selections.all::<Point>(cx);
 7895        let buffer = self.buffer.read(cx).read(cx);
 7896        let mut text = String::new();
 7897
 7898        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7899        {
 7900            let max_point = buffer.max_point();
 7901            let mut is_first = true;
 7902            for selection in selections.iter() {
 7903                let mut start = selection.start;
 7904                let mut end = selection.end;
 7905                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7906                if is_entire_line {
 7907                    start = Point::new(start.row, 0);
 7908                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7909                }
 7910                if is_first {
 7911                    is_first = false;
 7912                } else {
 7913                    text += "\n";
 7914                }
 7915                let mut len = 0;
 7916                for chunk in buffer.text_for_range(start..end) {
 7917                    text.push_str(chunk);
 7918                    len += chunk.len();
 7919                }
 7920                clipboard_selections.push(ClipboardSelection {
 7921                    len,
 7922                    is_entire_line,
 7923                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7924                });
 7925            }
 7926        }
 7927
 7928        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7929            text,
 7930            clipboard_selections,
 7931        ));
 7932    }
 7933
 7934    pub fn do_paste(
 7935        &mut self,
 7936        text: &String,
 7937        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7938        handle_entire_lines: bool,
 7939        window: &mut Window,
 7940        cx: &mut Context<Self>,
 7941    ) {
 7942        if self.read_only(cx) {
 7943            return;
 7944        }
 7945
 7946        let clipboard_text = Cow::Borrowed(text);
 7947
 7948        self.transact(window, cx, |this, window, cx| {
 7949            if let Some(mut clipboard_selections) = clipboard_selections {
 7950                let old_selections = this.selections.all::<usize>(cx);
 7951                let all_selections_were_entire_line =
 7952                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7953                let first_selection_indent_column =
 7954                    clipboard_selections.first().map(|s| s.first_line_indent);
 7955                if clipboard_selections.len() != old_selections.len() {
 7956                    clipboard_selections.drain(..);
 7957                }
 7958                let cursor_offset = this.selections.last::<usize>(cx).head();
 7959                let mut auto_indent_on_paste = true;
 7960
 7961                this.buffer.update(cx, |buffer, cx| {
 7962                    let snapshot = buffer.read(cx);
 7963                    auto_indent_on_paste =
 7964                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7965
 7966                    let mut start_offset = 0;
 7967                    let mut edits = Vec::new();
 7968                    let mut original_indent_columns = Vec::new();
 7969                    for (ix, selection) in old_selections.iter().enumerate() {
 7970                        let to_insert;
 7971                        let entire_line;
 7972                        let original_indent_column;
 7973                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7974                            let end_offset = start_offset + clipboard_selection.len;
 7975                            to_insert = &clipboard_text[start_offset..end_offset];
 7976                            entire_line = clipboard_selection.is_entire_line;
 7977                            start_offset = end_offset + 1;
 7978                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7979                        } else {
 7980                            to_insert = clipboard_text.as_str();
 7981                            entire_line = all_selections_were_entire_line;
 7982                            original_indent_column = first_selection_indent_column
 7983                        }
 7984
 7985                        // If the corresponding selection was empty when this slice of the
 7986                        // clipboard text was written, then the entire line containing the
 7987                        // selection was copied. If this selection is also currently empty,
 7988                        // then paste the line before the current line of the buffer.
 7989                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7990                            let column = selection.start.to_point(&snapshot).column as usize;
 7991                            let line_start = selection.start - column;
 7992                            line_start..line_start
 7993                        } else {
 7994                            selection.range()
 7995                        };
 7996
 7997                        edits.push((range, to_insert));
 7998                        original_indent_columns.extend(original_indent_column);
 7999                    }
 8000                    drop(snapshot);
 8001
 8002                    buffer.edit(
 8003                        edits,
 8004                        if auto_indent_on_paste {
 8005                            Some(AutoindentMode::Block {
 8006                                original_indent_columns,
 8007                            })
 8008                        } else {
 8009                            None
 8010                        },
 8011                        cx,
 8012                    );
 8013                });
 8014
 8015                let selections = this.selections.all::<usize>(cx);
 8016                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8017                    s.select(selections)
 8018                });
 8019            } else {
 8020                this.insert(&clipboard_text, window, cx);
 8021            }
 8022        });
 8023    }
 8024
 8025    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8026        if let Some(item) = cx.read_from_clipboard() {
 8027            let entries = item.entries();
 8028
 8029            match entries.first() {
 8030                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8031                // of all the pasted entries.
 8032                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8033                    .do_paste(
 8034                        clipboard_string.text(),
 8035                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8036                        true,
 8037                        window,
 8038                        cx,
 8039                    ),
 8040                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8041            }
 8042        }
 8043    }
 8044
 8045    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8046        if self.read_only(cx) {
 8047            return;
 8048        }
 8049
 8050        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8051            if let Some((selections, _)) =
 8052                self.selection_history.transaction(transaction_id).cloned()
 8053            {
 8054                self.change_selections(None, window, cx, |s| {
 8055                    s.select_anchors(selections.to_vec());
 8056                });
 8057            }
 8058            self.request_autoscroll(Autoscroll::fit(), cx);
 8059            self.unmark_text(window, cx);
 8060            self.refresh_inline_completion(true, false, window, cx);
 8061            cx.emit(EditorEvent::Edited { transaction_id });
 8062            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8063        }
 8064    }
 8065
 8066    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8067        if self.read_only(cx) {
 8068            return;
 8069        }
 8070
 8071        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8072            if let Some((_, Some(selections))) =
 8073                self.selection_history.transaction(transaction_id).cloned()
 8074            {
 8075                self.change_selections(None, window, cx, |s| {
 8076                    s.select_anchors(selections.to_vec());
 8077                });
 8078            }
 8079            self.request_autoscroll(Autoscroll::fit(), cx);
 8080            self.unmark_text(window, cx);
 8081            self.refresh_inline_completion(true, false, window, cx);
 8082            cx.emit(EditorEvent::Edited { transaction_id });
 8083        }
 8084    }
 8085
 8086    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8087        self.buffer
 8088            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8089    }
 8090
 8091    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8092        self.buffer
 8093            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8094    }
 8095
 8096    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8097        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8098            let line_mode = s.line_mode;
 8099            s.move_with(|map, selection| {
 8100                let cursor = if selection.is_empty() && !line_mode {
 8101                    movement::left(map, selection.start)
 8102                } else {
 8103                    selection.start
 8104                };
 8105                selection.collapse_to(cursor, SelectionGoal::None);
 8106            });
 8107        })
 8108    }
 8109
 8110    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8111        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8112            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8113        })
 8114    }
 8115
 8116    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8117        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8118            let line_mode = s.line_mode;
 8119            s.move_with(|map, selection| {
 8120                let cursor = if selection.is_empty() && !line_mode {
 8121                    movement::right(map, selection.end)
 8122                } else {
 8123                    selection.end
 8124                };
 8125                selection.collapse_to(cursor, SelectionGoal::None)
 8126            });
 8127        })
 8128    }
 8129
 8130    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8131        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8132            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8133        })
 8134    }
 8135
 8136    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8137        if self.take_rename(true, window, cx).is_some() {
 8138            return;
 8139        }
 8140
 8141        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8142            cx.propagate();
 8143            return;
 8144        }
 8145
 8146        let text_layout_details = &self.text_layout_details(window);
 8147        let selection_count = self.selections.count();
 8148        let first_selection = self.selections.first_anchor();
 8149
 8150        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8151            let line_mode = s.line_mode;
 8152            s.move_with(|map, selection| {
 8153                if !selection.is_empty() && !line_mode {
 8154                    selection.goal = SelectionGoal::None;
 8155                }
 8156                let (cursor, goal) = movement::up(
 8157                    map,
 8158                    selection.start,
 8159                    selection.goal,
 8160                    false,
 8161                    text_layout_details,
 8162                );
 8163                selection.collapse_to(cursor, goal);
 8164            });
 8165        });
 8166
 8167        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8168        {
 8169            cx.propagate();
 8170        }
 8171    }
 8172
 8173    pub fn move_up_by_lines(
 8174        &mut self,
 8175        action: &MoveUpByLines,
 8176        window: &mut Window,
 8177        cx: &mut Context<Self>,
 8178    ) {
 8179        if self.take_rename(true, window, cx).is_some() {
 8180            return;
 8181        }
 8182
 8183        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8184            cx.propagate();
 8185            return;
 8186        }
 8187
 8188        let text_layout_details = &self.text_layout_details(window);
 8189
 8190        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8191            let line_mode = s.line_mode;
 8192            s.move_with(|map, selection| {
 8193                if !selection.is_empty() && !line_mode {
 8194                    selection.goal = SelectionGoal::None;
 8195                }
 8196                let (cursor, goal) = movement::up_by_rows(
 8197                    map,
 8198                    selection.start,
 8199                    action.lines,
 8200                    selection.goal,
 8201                    false,
 8202                    text_layout_details,
 8203                );
 8204                selection.collapse_to(cursor, goal);
 8205            });
 8206        })
 8207    }
 8208
 8209    pub fn move_down_by_lines(
 8210        &mut self,
 8211        action: &MoveDownByLines,
 8212        window: &mut Window,
 8213        cx: &mut Context<Self>,
 8214    ) {
 8215        if self.take_rename(true, window, cx).is_some() {
 8216            return;
 8217        }
 8218
 8219        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8220            cx.propagate();
 8221            return;
 8222        }
 8223
 8224        let text_layout_details = &self.text_layout_details(window);
 8225
 8226        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8227            let line_mode = s.line_mode;
 8228            s.move_with(|map, selection| {
 8229                if !selection.is_empty() && !line_mode {
 8230                    selection.goal = SelectionGoal::None;
 8231                }
 8232                let (cursor, goal) = movement::down_by_rows(
 8233                    map,
 8234                    selection.start,
 8235                    action.lines,
 8236                    selection.goal,
 8237                    false,
 8238                    text_layout_details,
 8239                );
 8240                selection.collapse_to(cursor, goal);
 8241            });
 8242        })
 8243    }
 8244
 8245    pub fn select_down_by_lines(
 8246        &mut self,
 8247        action: &SelectDownByLines,
 8248        window: &mut Window,
 8249        cx: &mut Context<Self>,
 8250    ) {
 8251        let text_layout_details = &self.text_layout_details(window);
 8252        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8253            s.move_heads_with(|map, head, goal| {
 8254                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8255            })
 8256        })
 8257    }
 8258
 8259    pub fn select_up_by_lines(
 8260        &mut self,
 8261        action: &SelectUpByLines,
 8262        window: &mut Window,
 8263        cx: &mut Context<Self>,
 8264    ) {
 8265        let text_layout_details = &self.text_layout_details(window);
 8266        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8267            s.move_heads_with(|map, head, goal| {
 8268                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8269            })
 8270        })
 8271    }
 8272
 8273    pub fn select_page_up(
 8274        &mut self,
 8275        _: &SelectPageUp,
 8276        window: &mut Window,
 8277        cx: &mut Context<Self>,
 8278    ) {
 8279        let Some(row_count) = self.visible_row_count() else {
 8280            return;
 8281        };
 8282
 8283        let text_layout_details = &self.text_layout_details(window);
 8284
 8285        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8286            s.move_heads_with(|map, head, goal| {
 8287                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8288            })
 8289        })
 8290    }
 8291
 8292    pub fn move_page_up(
 8293        &mut self,
 8294        action: &MovePageUp,
 8295        window: &mut Window,
 8296        cx: &mut Context<Self>,
 8297    ) {
 8298        if self.take_rename(true, window, cx).is_some() {
 8299            return;
 8300        }
 8301
 8302        if self
 8303            .context_menu
 8304            .borrow_mut()
 8305            .as_mut()
 8306            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8307            .unwrap_or(false)
 8308        {
 8309            return;
 8310        }
 8311
 8312        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8313            cx.propagate();
 8314            return;
 8315        }
 8316
 8317        let Some(row_count) = self.visible_row_count() else {
 8318            return;
 8319        };
 8320
 8321        let autoscroll = if action.center_cursor {
 8322            Autoscroll::center()
 8323        } else {
 8324            Autoscroll::fit()
 8325        };
 8326
 8327        let text_layout_details = &self.text_layout_details(window);
 8328
 8329        self.change_selections(Some(autoscroll), window, cx, |s| {
 8330            let line_mode = s.line_mode;
 8331            s.move_with(|map, selection| {
 8332                if !selection.is_empty() && !line_mode {
 8333                    selection.goal = SelectionGoal::None;
 8334                }
 8335                let (cursor, goal) = movement::up_by_rows(
 8336                    map,
 8337                    selection.end,
 8338                    row_count,
 8339                    selection.goal,
 8340                    false,
 8341                    text_layout_details,
 8342                );
 8343                selection.collapse_to(cursor, goal);
 8344            });
 8345        });
 8346    }
 8347
 8348    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8349        let text_layout_details = &self.text_layout_details(window);
 8350        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8351            s.move_heads_with(|map, head, goal| {
 8352                movement::up(map, head, goal, false, text_layout_details)
 8353            })
 8354        })
 8355    }
 8356
 8357    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8358        self.take_rename(true, window, cx);
 8359
 8360        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8361            cx.propagate();
 8362            return;
 8363        }
 8364
 8365        let text_layout_details = &self.text_layout_details(window);
 8366        let selection_count = self.selections.count();
 8367        let first_selection = self.selections.first_anchor();
 8368
 8369        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8370            let line_mode = s.line_mode;
 8371            s.move_with(|map, selection| {
 8372                if !selection.is_empty() && !line_mode {
 8373                    selection.goal = SelectionGoal::None;
 8374                }
 8375                let (cursor, goal) = movement::down(
 8376                    map,
 8377                    selection.end,
 8378                    selection.goal,
 8379                    false,
 8380                    text_layout_details,
 8381                );
 8382                selection.collapse_to(cursor, goal);
 8383            });
 8384        });
 8385
 8386        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8387        {
 8388            cx.propagate();
 8389        }
 8390    }
 8391
 8392    pub fn select_page_down(
 8393        &mut self,
 8394        _: &SelectPageDown,
 8395        window: &mut Window,
 8396        cx: &mut Context<Self>,
 8397    ) {
 8398        let Some(row_count) = self.visible_row_count() else {
 8399            return;
 8400        };
 8401
 8402        let text_layout_details = &self.text_layout_details(window);
 8403
 8404        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8405            s.move_heads_with(|map, head, goal| {
 8406                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8407            })
 8408        })
 8409    }
 8410
 8411    pub fn move_page_down(
 8412        &mut self,
 8413        action: &MovePageDown,
 8414        window: &mut Window,
 8415        cx: &mut Context<Self>,
 8416    ) {
 8417        if self.take_rename(true, window, cx).is_some() {
 8418            return;
 8419        }
 8420
 8421        if self
 8422            .context_menu
 8423            .borrow_mut()
 8424            .as_mut()
 8425            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8426            .unwrap_or(false)
 8427        {
 8428            return;
 8429        }
 8430
 8431        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8432            cx.propagate();
 8433            return;
 8434        }
 8435
 8436        let Some(row_count) = self.visible_row_count() else {
 8437            return;
 8438        };
 8439
 8440        let autoscroll = if action.center_cursor {
 8441            Autoscroll::center()
 8442        } else {
 8443            Autoscroll::fit()
 8444        };
 8445
 8446        let text_layout_details = &self.text_layout_details(window);
 8447        self.change_selections(Some(autoscroll), window, cx, |s| {
 8448            let line_mode = s.line_mode;
 8449            s.move_with(|map, selection| {
 8450                if !selection.is_empty() && !line_mode {
 8451                    selection.goal = SelectionGoal::None;
 8452                }
 8453                let (cursor, goal) = movement::down_by_rows(
 8454                    map,
 8455                    selection.end,
 8456                    row_count,
 8457                    selection.goal,
 8458                    false,
 8459                    text_layout_details,
 8460                );
 8461                selection.collapse_to(cursor, goal);
 8462            });
 8463        });
 8464    }
 8465
 8466    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8467        let text_layout_details = &self.text_layout_details(window);
 8468        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8469            s.move_heads_with(|map, head, goal| {
 8470                movement::down(map, head, goal, false, text_layout_details)
 8471            })
 8472        });
 8473    }
 8474
 8475    pub fn context_menu_first(
 8476        &mut self,
 8477        _: &ContextMenuFirst,
 8478        _window: &mut Window,
 8479        cx: &mut Context<Self>,
 8480    ) {
 8481        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8482            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8483        }
 8484    }
 8485
 8486    pub fn context_menu_prev(
 8487        &mut self,
 8488        _: &ContextMenuPrev,
 8489        _window: &mut Window,
 8490        cx: &mut Context<Self>,
 8491    ) {
 8492        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8493            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8494        }
 8495    }
 8496
 8497    pub fn context_menu_next(
 8498        &mut self,
 8499        _: &ContextMenuNext,
 8500        _window: &mut Window,
 8501        cx: &mut Context<Self>,
 8502    ) {
 8503        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8504            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8505        }
 8506    }
 8507
 8508    pub fn context_menu_last(
 8509        &mut self,
 8510        _: &ContextMenuLast,
 8511        _window: &mut Window,
 8512        cx: &mut Context<Self>,
 8513    ) {
 8514        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8515            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8516        }
 8517    }
 8518
 8519    pub fn move_to_previous_word_start(
 8520        &mut self,
 8521        _: &MoveToPreviousWordStart,
 8522        window: &mut Window,
 8523        cx: &mut Context<Self>,
 8524    ) {
 8525        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8526            s.move_cursors_with(|map, head, _| {
 8527                (
 8528                    movement::previous_word_start(map, head),
 8529                    SelectionGoal::None,
 8530                )
 8531            });
 8532        })
 8533    }
 8534
 8535    pub fn move_to_previous_subword_start(
 8536        &mut self,
 8537        _: &MoveToPreviousSubwordStart,
 8538        window: &mut Window,
 8539        cx: &mut Context<Self>,
 8540    ) {
 8541        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8542            s.move_cursors_with(|map, head, _| {
 8543                (
 8544                    movement::previous_subword_start(map, head),
 8545                    SelectionGoal::None,
 8546                )
 8547            });
 8548        })
 8549    }
 8550
 8551    pub fn select_to_previous_word_start(
 8552        &mut self,
 8553        _: &SelectToPreviousWordStart,
 8554        window: &mut Window,
 8555        cx: &mut Context<Self>,
 8556    ) {
 8557        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8558            s.move_heads_with(|map, head, _| {
 8559                (
 8560                    movement::previous_word_start(map, head),
 8561                    SelectionGoal::None,
 8562                )
 8563            });
 8564        })
 8565    }
 8566
 8567    pub fn select_to_previous_subword_start(
 8568        &mut self,
 8569        _: &SelectToPreviousSubwordStart,
 8570        window: &mut Window,
 8571        cx: &mut Context<Self>,
 8572    ) {
 8573        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8574            s.move_heads_with(|map, head, _| {
 8575                (
 8576                    movement::previous_subword_start(map, head),
 8577                    SelectionGoal::None,
 8578                )
 8579            });
 8580        })
 8581    }
 8582
 8583    pub fn delete_to_previous_word_start(
 8584        &mut self,
 8585        action: &DeleteToPreviousWordStart,
 8586        window: &mut Window,
 8587        cx: &mut Context<Self>,
 8588    ) {
 8589        self.transact(window, cx, |this, window, cx| {
 8590            this.select_autoclose_pair(window, cx);
 8591            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8592                let line_mode = s.line_mode;
 8593                s.move_with(|map, selection| {
 8594                    if selection.is_empty() && !line_mode {
 8595                        let cursor = if action.ignore_newlines {
 8596                            movement::previous_word_start(map, selection.head())
 8597                        } else {
 8598                            movement::previous_word_start_or_newline(map, selection.head())
 8599                        };
 8600                        selection.set_head(cursor, SelectionGoal::None);
 8601                    }
 8602                });
 8603            });
 8604            this.insert("", window, cx);
 8605        });
 8606    }
 8607
 8608    pub fn delete_to_previous_subword_start(
 8609        &mut self,
 8610        _: &DeleteToPreviousSubwordStart,
 8611        window: &mut Window,
 8612        cx: &mut Context<Self>,
 8613    ) {
 8614        self.transact(window, cx, |this, window, cx| {
 8615            this.select_autoclose_pair(window, cx);
 8616            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8617                let line_mode = s.line_mode;
 8618                s.move_with(|map, selection| {
 8619                    if selection.is_empty() && !line_mode {
 8620                        let cursor = movement::previous_subword_start(map, selection.head());
 8621                        selection.set_head(cursor, SelectionGoal::None);
 8622                    }
 8623                });
 8624            });
 8625            this.insert("", window, cx);
 8626        });
 8627    }
 8628
 8629    pub fn move_to_next_word_end(
 8630        &mut self,
 8631        _: &MoveToNextWordEnd,
 8632        window: &mut Window,
 8633        cx: &mut Context<Self>,
 8634    ) {
 8635        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8636            s.move_cursors_with(|map, head, _| {
 8637                (movement::next_word_end(map, head), SelectionGoal::None)
 8638            });
 8639        })
 8640    }
 8641
 8642    pub fn move_to_next_subword_end(
 8643        &mut self,
 8644        _: &MoveToNextSubwordEnd,
 8645        window: &mut Window,
 8646        cx: &mut Context<Self>,
 8647    ) {
 8648        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8649            s.move_cursors_with(|map, head, _| {
 8650                (movement::next_subword_end(map, head), SelectionGoal::None)
 8651            });
 8652        })
 8653    }
 8654
 8655    pub fn select_to_next_word_end(
 8656        &mut self,
 8657        _: &SelectToNextWordEnd,
 8658        window: &mut Window,
 8659        cx: &mut Context<Self>,
 8660    ) {
 8661        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8662            s.move_heads_with(|map, head, _| {
 8663                (movement::next_word_end(map, head), SelectionGoal::None)
 8664            });
 8665        })
 8666    }
 8667
 8668    pub fn select_to_next_subword_end(
 8669        &mut self,
 8670        _: &SelectToNextSubwordEnd,
 8671        window: &mut Window,
 8672        cx: &mut Context<Self>,
 8673    ) {
 8674        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8675            s.move_heads_with(|map, head, _| {
 8676                (movement::next_subword_end(map, head), SelectionGoal::None)
 8677            });
 8678        })
 8679    }
 8680
 8681    pub fn delete_to_next_word_end(
 8682        &mut self,
 8683        action: &DeleteToNextWordEnd,
 8684        window: &mut Window,
 8685        cx: &mut Context<Self>,
 8686    ) {
 8687        self.transact(window, cx, |this, window, cx| {
 8688            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8689                let line_mode = s.line_mode;
 8690                s.move_with(|map, selection| {
 8691                    if selection.is_empty() && !line_mode {
 8692                        let cursor = if action.ignore_newlines {
 8693                            movement::next_word_end(map, selection.head())
 8694                        } else {
 8695                            movement::next_word_end_or_newline(map, selection.head())
 8696                        };
 8697                        selection.set_head(cursor, SelectionGoal::None);
 8698                    }
 8699                });
 8700            });
 8701            this.insert("", window, cx);
 8702        });
 8703    }
 8704
 8705    pub fn delete_to_next_subword_end(
 8706        &mut self,
 8707        _: &DeleteToNextSubwordEnd,
 8708        window: &mut Window,
 8709        cx: &mut Context<Self>,
 8710    ) {
 8711        self.transact(window, cx, |this, window, cx| {
 8712            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8713                s.move_with(|map, selection| {
 8714                    if selection.is_empty() {
 8715                        let cursor = movement::next_subword_end(map, selection.head());
 8716                        selection.set_head(cursor, SelectionGoal::None);
 8717                    }
 8718                });
 8719            });
 8720            this.insert("", window, cx);
 8721        });
 8722    }
 8723
 8724    pub fn move_to_beginning_of_line(
 8725        &mut self,
 8726        action: &MoveToBeginningOfLine,
 8727        window: &mut Window,
 8728        cx: &mut Context<Self>,
 8729    ) {
 8730        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8731            s.move_cursors_with(|map, head, _| {
 8732                (
 8733                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8734                    SelectionGoal::None,
 8735                )
 8736            });
 8737        })
 8738    }
 8739
 8740    pub fn select_to_beginning_of_line(
 8741        &mut self,
 8742        action: &SelectToBeginningOfLine,
 8743        window: &mut Window,
 8744        cx: &mut Context<Self>,
 8745    ) {
 8746        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8747            s.move_heads_with(|map, head, _| {
 8748                (
 8749                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8750                    SelectionGoal::None,
 8751                )
 8752            });
 8753        });
 8754    }
 8755
 8756    pub fn delete_to_beginning_of_line(
 8757        &mut self,
 8758        _: &DeleteToBeginningOfLine,
 8759        window: &mut Window,
 8760        cx: &mut Context<Self>,
 8761    ) {
 8762        self.transact(window, cx, |this, window, cx| {
 8763            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8764                s.move_with(|_, selection| {
 8765                    selection.reversed = true;
 8766                });
 8767            });
 8768
 8769            this.select_to_beginning_of_line(
 8770                &SelectToBeginningOfLine {
 8771                    stop_at_soft_wraps: false,
 8772                },
 8773                window,
 8774                cx,
 8775            );
 8776            this.backspace(&Backspace, window, cx);
 8777        });
 8778    }
 8779
 8780    pub fn move_to_end_of_line(
 8781        &mut self,
 8782        action: &MoveToEndOfLine,
 8783        window: &mut Window,
 8784        cx: &mut Context<Self>,
 8785    ) {
 8786        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8787            s.move_cursors_with(|map, head, _| {
 8788                (
 8789                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8790                    SelectionGoal::None,
 8791                )
 8792            });
 8793        })
 8794    }
 8795
 8796    pub fn select_to_end_of_line(
 8797        &mut self,
 8798        action: &SelectToEndOfLine,
 8799        window: &mut Window,
 8800        cx: &mut Context<Self>,
 8801    ) {
 8802        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8803            s.move_heads_with(|map, head, _| {
 8804                (
 8805                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8806                    SelectionGoal::None,
 8807                )
 8808            });
 8809        })
 8810    }
 8811
 8812    pub fn delete_to_end_of_line(
 8813        &mut self,
 8814        _: &DeleteToEndOfLine,
 8815        window: &mut Window,
 8816        cx: &mut Context<Self>,
 8817    ) {
 8818        self.transact(window, cx, |this, window, cx| {
 8819            this.select_to_end_of_line(
 8820                &SelectToEndOfLine {
 8821                    stop_at_soft_wraps: false,
 8822                },
 8823                window,
 8824                cx,
 8825            );
 8826            this.delete(&Delete, window, cx);
 8827        });
 8828    }
 8829
 8830    pub fn cut_to_end_of_line(
 8831        &mut self,
 8832        _: &CutToEndOfLine,
 8833        window: &mut Window,
 8834        cx: &mut Context<Self>,
 8835    ) {
 8836        self.transact(window, cx, |this, window, cx| {
 8837            this.select_to_end_of_line(
 8838                &SelectToEndOfLine {
 8839                    stop_at_soft_wraps: false,
 8840                },
 8841                window,
 8842                cx,
 8843            );
 8844            this.cut(&Cut, window, cx);
 8845        });
 8846    }
 8847
 8848    pub fn move_to_start_of_paragraph(
 8849        &mut self,
 8850        _: &MoveToStartOfParagraph,
 8851        window: &mut Window,
 8852        cx: &mut Context<Self>,
 8853    ) {
 8854        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8855            cx.propagate();
 8856            return;
 8857        }
 8858
 8859        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8860            s.move_with(|map, selection| {
 8861                selection.collapse_to(
 8862                    movement::start_of_paragraph(map, selection.head(), 1),
 8863                    SelectionGoal::None,
 8864                )
 8865            });
 8866        })
 8867    }
 8868
 8869    pub fn move_to_end_of_paragraph(
 8870        &mut self,
 8871        _: &MoveToEndOfParagraph,
 8872        window: &mut Window,
 8873        cx: &mut Context<Self>,
 8874    ) {
 8875        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8876            cx.propagate();
 8877            return;
 8878        }
 8879
 8880        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8881            s.move_with(|map, selection| {
 8882                selection.collapse_to(
 8883                    movement::end_of_paragraph(map, selection.head(), 1),
 8884                    SelectionGoal::None,
 8885                )
 8886            });
 8887        })
 8888    }
 8889
 8890    pub fn select_to_start_of_paragraph(
 8891        &mut self,
 8892        _: &SelectToStartOfParagraph,
 8893        window: &mut Window,
 8894        cx: &mut Context<Self>,
 8895    ) {
 8896        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8897            cx.propagate();
 8898            return;
 8899        }
 8900
 8901        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8902            s.move_heads_with(|map, head, _| {
 8903                (
 8904                    movement::start_of_paragraph(map, head, 1),
 8905                    SelectionGoal::None,
 8906                )
 8907            });
 8908        })
 8909    }
 8910
 8911    pub fn select_to_end_of_paragraph(
 8912        &mut self,
 8913        _: &SelectToEndOfParagraph,
 8914        window: &mut Window,
 8915        cx: &mut Context<Self>,
 8916    ) {
 8917        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8918            cx.propagate();
 8919            return;
 8920        }
 8921
 8922        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8923            s.move_heads_with(|map, head, _| {
 8924                (
 8925                    movement::end_of_paragraph(map, head, 1),
 8926                    SelectionGoal::None,
 8927                )
 8928            });
 8929        })
 8930    }
 8931
 8932    pub fn move_to_beginning(
 8933        &mut self,
 8934        _: &MoveToBeginning,
 8935        window: &mut Window,
 8936        cx: &mut Context<Self>,
 8937    ) {
 8938        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8939            cx.propagate();
 8940            return;
 8941        }
 8942
 8943        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8944            s.select_ranges(vec![0..0]);
 8945        });
 8946    }
 8947
 8948    pub fn select_to_beginning(
 8949        &mut self,
 8950        _: &SelectToBeginning,
 8951        window: &mut Window,
 8952        cx: &mut Context<Self>,
 8953    ) {
 8954        let mut selection = self.selections.last::<Point>(cx);
 8955        selection.set_head(Point::zero(), SelectionGoal::None);
 8956
 8957        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8958            s.select(vec![selection]);
 8959        });
 8960    }
 8961
 8962    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8963        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8964            cx.propagate();
 8965            return;
 8966        }
 8967
 8968        let cursor = self.buffer.read(cx).read(cx).len();
 8969        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8970            s.select_ranges(vec![cursor..cursor])
 8971        });
 8972    }
 8973
 8974    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8975        self.nav_history = nav_history;
 8976    }
 8977
 8978    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8979        self.nav_history.as_ref()
 8980    }
 8981
 8982    fn push_to_nav_history(
 8983        &mut self,
 8984        cursor_anchor: Anchor,
 8985        new_position: Option<Point>,
 8986        cx: &mut Context<Self>,
 8987    ) {
 8988        if let Some(nav_history) = self.nav_history.as_mut() {
 8989            let buffer = self.buffer.read(cx).read(cx);
 8990            let cursor_position = cursor_anchor.to_point(&buffer);
 8991            let scroll_state = self.scroll_manager.anchor();
 8992            let scroll_top_row = scroll_state.top_row(&buffer);
 8993            drop(buffer);
 8994
 8995            if let Some(new_position) = new_position {
 8996                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8997                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8998                    return;
 8999                }
 9000            }
 9001
 9002            nav_history.push(
 9003                Some(NavigationData {
 9004                    cursor_anchor,
 9005                    cursor_position,
 9006                    scroll_anchor: scroll_state,
 9007                    scroll_top_row,
 9008                }),
 9009                cx,
 9010            );
 9011        }
 9012    }
 9013
 9014    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9015        let buffer = self.buffer.read(cx).snapshot(cx);
 9016        let mut selection = self.selections.first::<usize>(cx);
 9017        selection.set_head(buffer.len(), SelectionGoal::None);
 9018        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9019            s.select(vec![selection]);
 9020        });
 9021    }
 9022
 9023    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9024        let end = self.buffer.read(cx).read(cx).len();
 9025        self.change_selections(None, window, cx, |s| {
 9026            s.select_ranges(vec![0..end]);
 9027        });
 9028    }
 9029
 9030    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9031        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9032        let mut selections = self.selections.all::<Point>(cx);
 9033        let max_point = display_map.buffer_snapshot.max_point();
 9034        for selection in &mut selections {
 9035            let rows = selection.spanned_rows(true, &display_map);
 9036            selection.start = Point::new(rows.start.0, 0);
 9037            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9038            selection.reversed = false;
 9039        }
 9040        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9041            s.select(selections);
 9042        });
 9043    }
 9044
 9045    pub fn split_selection_into_lines(
 9046        &mut self,
 9047        _: &SplitSelectionIntoLines,
 9048        window: &mut Window,
 9049        cx: &mut Context<Self>,
 9050    ) {
 9051        let mut to_unfold = Vec::new();
 9052        let mut new_selection_ranges = Vec::new();
 9053        {
 9054            let selections = self.selections.all::<Point>(cx);
 9055            let buffer = self.buffer.read(cx).read(cx);
 9056            for selection in selections {
 9057                for row in selection.start.row..selection.end.row {
 9058                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9059                    new_selection_ranges.push(cursor..cursor);
 9060                }
 9061                new_selection_ranges.push(selection.end..selection.end);
 9062                to_unfold.push(selection.start..selection.end);
 9063            }
 9064        }
 9065        self.unfold_ranges(&to_unfold, true, true, cx);
 9066        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9067            s.select_ranges(new_selection_ranges);
 9068        });
 9069    }
 9070
 9071    pub fn add_selection_above(
 9072        &mut self,
 9073        _: &AddSelectionAbove,
 9074        window: &mut Window,
 9075        cx: &mut Context<Self>,
 9076    ) {
 9077        self.add_selection(true, window, cx);
 9078    }
 9079
 9080    pub fn add_selection_below(
 9081        &mut self,
 9082        _: &AddSelectionBelow,
 9083        window: &mut Window,
 9084        cx: &mut Context<Self>,
 9085    ) {
 9086        self.add_selection(false, window, cx);
 9087    }
 9088
 9089    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9090        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9091        let mut selections = self.selections.all::<Point>(cx);
 9092        let text_layout_details = self.text_layout_details(window);
 9093        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9094            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9095            let range = oldest_selection.display_range(&display_map).sorted();
 9096
 9097            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9098            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9099            let positions = start_x.min(end_x)..start_x.max(end_x);
 9100
 9101            selections.clear();
 9102            let mut stack = Vec::new();
 9103            for row in range.start.row().0..=range.end.row().0 {
 9104                if let Some(selection) = self.selections.build_columnar_selection(
 9105                    &display_map,
 9106                    DisplayRow(row),
 9107                    &positions,
 9108                    oldest_selection.reversed,
 9109                    &text_layout_details,
 9110                ) {
 9111                    stack.push(selection.id);
 9112                    selections.push(selection);
 9113                }
 9114            }
 9115
 9116            if above {
 9117                stack.reverse();
 9118            }
 9119
 9120            AddSelectionsState { above, stack }
 9121        });
 9122
 9123        let last_added_selection = *state.stack.last().unwrap();
 9124        let mut new_selections = Vec::new();
 9125        if above == state.above {
 9126            let end_row = if above {
 9127                DisplayRow(0)
 9128            } else {
 9129                display_map.max_point().row()
 9130            };
 9131
 9132            'outer: for selection in selections {
 9133                if selection.id == last_added_selection {
 9134                    let range = selection.display_range(&display_map).sorted();
 9135                    debug_assert_eq!(range.start.row(), range.end.row());
 9136                    let mut row = range.start.row();
 9137                    let positions =
 9138                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9139                            px(start)..px(end)
 9140                        } else {
 9141                            let start_x =
 9142                                display_map.x_for_display_point(range.start, &text_layout_details);
 9143                            let end_x =
 9144                                display_map.x_for_display_point(range.end, &text_layout_details);
 9145                            start_x.min(end_x)..start_x.max(end_x)
 9146                        };
 9147
 9148                    while row != end_row {
 9149                        if above {
 9150                            row.0 -= 1;
 9151                        } else {
 9152                            row.0 += 1;
 9153                        }
 9154
 9155                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9156                            &display_map,
 9157                            row,
 9158                            &positions,
 9159                            selection.reversed,
 9160                            &text_layout_details,
 9161                        ) {
 9162                            state.stack.push(new_selection.id);
 9163                            if above {
 9164                                new_selections.push(new_selection);
 9165                                new_selections.push(selection);
 9166                            } else {
 9167                                new_selections.push(selection);
 9168                                new_selections.push(new_selection);
 9169                            }
 9170
 9171                            continue 'outer;
 9172                        }
 9173                    }
 9174                }
 9175
 9176                new_selections.push(selection);
 9177            }
 9178        } else {
 9179            new_selections = selections;
 9180            new_selections.retain(|s| s.id != last_added_selection);
 9181            state.stack.pop();
 9182        }
 9183
 9184        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9185            s.select(new_selections);
 9186        });
 9187        if state.stack.len() > 1 {
 9188            self.add_selections_state = Some(state);
 9189        }
 9190    }
 9191
 9192    pub fn select_next_match_internal(
 9193        &mut self,
 9194        display_map: &DisplaySnapshot,
 9195        replace_newest: bool,
 9196        autoscroll: Option<Autoscroll>,
 9197        window: &mut Window,
 9198        cx: &mut Context<Self>,
 9199    ) -> Result<()> {
 9200        fn select_next_match_ranges(
 9201            this: &mut Editor,
 9202            range: Range<usize>,
 9203            replace_newest: bool,
 9204            auto_scroll: Option<Autoscroll>,
 9205            window: &mut Window,
 9206            cx: &mut Context<Editor>,
 9207        ) {
 9208            this.unfold_ranges(&[range.clone()], false, true, cx);
 9209            this.change_selections(auto_scroll, window, cx, |s| {
 9210                if replace_newest {
 9211                    s.delete(s.newest_anchor().id);
 9212                }
 9213                s.insert_range(range.clone());
 9214            });
 9215        }
 9216
 9217        let buffer = &display_map.buffer_snapshot;
 9218        let mut selections = self.selections.all::<usize>(cx);
 9219        if let Some(mut select_next_state) = self.select_next_state.take() {
 9220            let query = &select_next_state.query;
 9221            if !select_next_state.done {
 9222                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9223                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9224                let mut next_selected_range = None;
 9225
 9226                let bytes_after_last_selection =
 9227                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9228                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9229                let query_matches = query
 9230                    .stream_find_iter(bytes_after_last_selection)
 9231                    .map(|result| (last_selection.end, result))
 9232                    .chain(
 9233                        query
 9234                            .stream_find_iter(bytes_before_first_selection)
 9235                            .map(|result| (0, result)),
 9236                    );
 9237
 9238                for (start_offset, query_match) in query_matches {
 9239                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9240                    let offset_range =
 9241                        start_offset + query_match.start()..start_offset + query_match.end();
 9242                    let display_range = offset_range.start.to_display_point(display_map)
 9243                        ..offset_range.end.to_display_point(display_map);
 9244
 9245                    if !select_next_state.wordwise
 9246                        || (!movement::is_inside_word(display_map, display_range.start)
 9247                            && !movement::is_inside_word(display_map, display_range.end))
 9248                    {
 9249                        // TODO: This is n^2, because we might check all the selections
 9250                        if !selections
 9251                            .iter()
 9252                            .any(|selection| selection.range().overlaps(&offset_range))
 9253                        {
 9254                            next_selected_range = Some(offset_range);
 9255                            break;
 9256                        }
 9257                    }
 9258                }
 9259
 9260                if let Some(next_selected_range) = next_selected_range {
 9261                    select_next_match_ranges(
 9262                        self,
 9263                        next_selected_range,
 9264                        replace_newest,
 9265                        autoscroll,
 9266                        window,
 9267                        cx,
 9268                    );
 9269                } else {
 9270                    select_next_state.done = true;
 9271                }
 9272            }
 9273
 9274            self.select_next_state = Some(select_next_state);
 9275        } else {
 9276            let mut only_carets = true;
 9277            let mut same_text_selected = true;
 9278            let mut selected_text = None;
 9279
 9280            let mut selections_iter = selections.iter().peekable();
 9281            while let Some(selection) = selections_iter.next() {
 9282                if selection.start != selection.end {
 9283                    only_carets = false;
 9284                }
 9285
 9286                if same_text_selected {
 9287                    if selected_text.is_none() {
 9288                        selected_text =
 9289                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9290                    }
 9291
 9292                    if let Some(next_selection) = selections_iter.peek() {
 9293                        if next_selection.range().len() == selection.range().len() {
 9294                            let next_selected_text = buffer
 9295                                .text_for_range(next_selection.range())
 9296                                .collect::<String>();
 9297                            if Some(next_selected_text) != selected_text {
 9298                                same_text_selected = false;
 9299                                selected_text = None;
 9300                            }
 9301                        } else {
 9302                            same_text_selected = false;
 9303                            selected_text = None;
 9304                        }
 9305                    }
 9306                }
 9307            }
 9308
 9309            if only_carets {
 9310                for selection in &mut selections {
 9311                    let word_range = movement::surrounding_word(
 9312                        display_map,
 9313                        selection.start.to_display_point(display_map),
 9314                    );
 9315                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9316                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9317                    selection.goal = SelectionGoal::None;
 9318                    selection.reversed = false;
 9319                    select_next_match_ranges(
 9320                        self,
 9321                        selection.start..selection.end,
 9322                        replace_newest,
 9323                        autoscroll,
 9324                        window,
 9325                        cx,
 9326                    );
 9327                }
 9328
 9329                if selections.len() == 1 {
 9330                    let selection = selections
 9331                        .last()
 9332                        .expect("ensured that there's only one selection");
 9333                    let query = buffer
 9334                        .text_for_range(selection.start..selection.end)
 9335                        .collect::<String>();
 9336                    let is_empty = query.is_empty();
 9337                    let select_state = SelectNextState {
 9338                        query: AhoCorasick::new(&[query])?,
 9339                        wordwise: true,
 9340                        done: is_empty,
 9341                    };
 9342                    self.select_next_state = Some(select_state);
 9343                } else {
 9344                    self.select_next_state = None;
 9345                }
 9346            } else if let Some(selected_text) = selected_text {
 9347                self.select_next_state = Some(SelectNextState {
 9348                    query: AhoCorasick::new(&[selected_text])?,
 9349                    wordwise: false,
 9350                    done: false,
 9351                });
 9352                self.select_next_match_internal(
 9353                    display_map,
 9354                    replace_newest,
 9355                    autoscroll,
 9356                    window,
 9357                    cx,
 9358                )?;
 9359            }
 9360        }
 9361        Ok(())
 9362    }
 9363
 9364    pub fn select_all_matches(
 9365        &mut self,
 9366        _action: &SelectAllMatches,
 9367        window: &mut Window,
 9368        cx: &mut Context<Self>,
 9369    ) -> Result<()> {
 9370        self.push_to_selection_history();
 9371        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9372
 9373        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9374        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9375            return Ok(());
 9376        };
 9377        if select_next_state.done {
 9378            return Ok(());
 9379        }
 9380
 9381        let mut new_selections = self.selections.all::<usize>(cx);
 9382
 9383        let buffer = &display_map.buffer_snapshot;
 9384        let query_matches = select_next_state
 9385            .query
 9386            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9387
 9388        for query_match in query_matches {
 9389            let query_match = query_match.unwrap(); // can only fail due to I/O
 9390            let offset_range = query_match.start()..query_match.end();
 9391            let display_range = offset_range.start.to_display_point(&display_map)
 9392                ..offset_range.end.to_display_point(&display_map);
 9393
 9394            if !select_next_state.wordwise
 9395                || (!movement::is_inside_word(&display_map, display_range.start)
 9396                    && !movement::is_inside_word(&display_map, display_range.end))
 9397            {
 9398                self.selections.change_with(cx, |selections| {
 9399                    new_selections.push(Selection {
 9400                        id: selections.new_selection_id(),
 9401                        start: offset_range.start,
 9402                        end: offset_range.end,
 9403                        reversed: false,
 9404                        goal: SelectionGoal::None,
 9405                    });
 9406                });
 9407            }
 9408        }
 9409
 9410        new_selections.sort_by_key(|selection| selection.start);
 9411        let mut ix = 0;
 9412        while ix + 1 < new_selections.len() {
 9413            let current_selection = &new_selections[ix];
 9414            let next_selection = &new_selections[ix + 1];
 9415            if current_selection.range().overlaps(&next_selection.range()) {
 9416                if current_selection.id < next_selection.id {
 9417                    new_selections.remove(ix + 1);
 9418                } else {
 9419                    new_selections.remove(ix);
 9420                }
 9421            } else {
 9422                ix += 1;
 9423            }
 9424        }
 9425
 9426        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9427
 9428        for selection in new_selections.iter_mut() {
 9429            selection.reversed = reversed;
 9430        }
 9431
 9432        select_next_state.done = true;
 9433        self.unfold_ranges(
 9434            &new_selections
 9435                .iter()
 9436                .map(|selection| selection.range())
 9437                .collect::<Vec<_>>(),
 9438            false,
 9439            false,
 9440            cx,
 9441        );
 9442        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9443            selections.select(new_selections)
 9444        });
 9445
 9446        Ok(())
 9447    }
 9448
 9449    pub fn select_next(
 9450        &mut self,
 9451        action: &SelectNext,
 9452        window: &mut Window,
 9453        cx: &mut Context<Self>,
 9454    ) -> Result<()> {
 9455        self.push_to_selection_history();
 9456        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9457        self.select_next_match_internal(
 9458            &display_map,
 9459            action.replace_newest,
 9460            Some(Autoscroll::newest()),
 9461            window,
 9462            cx,
 9463        )?;
 9464        Ok(())
 9465    }
 9466
 9467    pub fn select_previous(
 9468        &mut self,
 9469        action: &SelectPrevious,
 9470        window: &mut Window,
 9471        cx: &mut Context<Self>,
 9472    ) -> Result<()> {
 9473        self.push_to_selection_history();
 9474        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9475        let buffer = &display_map.buffer_snapshot;
 9476        let mut selections = self.selections.all::<usize>(cx);
 9477        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9478            let query = &select_prev_state.query;
 9479            if !select_prev_state.done {
 9480                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9481                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9482                let mut next_selected_range = None;
 9483                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9484                let bytes_before_last_selection =
 9485                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9486                let bytes_after_first_selection =
 9487                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9488                let query_matches = query
 9489                    .stream_find_iter(bytes_before_last_selection)
 9490                    .map(|result| (last_selection.start, result))
 9491                    .chain(
 9492                        query
 9493                            .stream_find_iter(bytes_after_first_selection)
 9494                            .map(|result| (buffer.len(), result)),
 9495                    );
 9496                for (end_offset, query_match) in query_matches {
 9497                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9498                    let offset_range =
 9499                        end_offset - query_match.end()..end_offset - query_match.start();
 9500                    let display_range = offset_range.start.to_display_point(&display_map)
 9501                        ..offset_range.end.to_display_point(&display_map);
 9502
 9503                    if !select_prev_state.wordwise
 9504                        || (!movement::is_inside_word(&display_map, display_range.start)
 9505                            && !movement::is_inside_word(&display_map, display_range.end))
 9506                    {
 9507                        next_selected_range = Some(offset_range);
 9508                        break;
 9509                    }
 9510                }
 9511
 9512                if let Some(next_selected_range) = next_selected_range {
 9513                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9514                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9515                        if action.replace_newest {
 9516                            s.delete(s.newest_anchor().id);
 9517                        }
 9518                        s.insert_range(next_selected_range);
 9519                    });
 9520                } else {
 9521                    select_prev_state.done = true;
 9522                }
 9523            }
 9524
 9525            self.select_prev_state = Some(select_prev_state);
 9526        } else {
 9527            let mut only_carets = true;
 9528            let mut same_text_selected = true;
 9529            let mut selected_text = None;
 9530
 9531            let mut selections_iter = selections.iter().peekable();
 9532            while let Some(selection) = selections_iter.next() {
 9533                if selection.start != selection.end {
 9534                    only_carets = false;
 9535                }
 9536
 9537                if same_text_selected {
 9538                    if selected_text.is_none() {
 9539                        selected_text =
 9540                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9541                    }
 9542
 9543                    if let Some(next_selection) = selections_iter.peek() {
 9544                        if next_selection.range().len() == selection.range().len() {
 9545                            let next_selected_text = buffer
 9546                                .text_for_range(next_selection.range())
 9547                                .collect::<String>();
 9548                            if Some(next_selected_text) != selected_text {
 9549                                same_text_selected = false;
 9550                                selected_text = None;
 9551                            }
 9552                        } else {
 9553                            same_text_selected = false;
 9554                            selected_text = None;
 9555                        }
 9556                    }
 9557                }
 9558            }
 9559
 9560            if only_carets {
 9561                for selection in &mut selections {
 9562                    let word_range = movement::surrounding_word(
 9563                        &display_map,
 9564                        selection.start.to_display_point(&display_map),
 9565                    );
 9566                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9567                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9568                    selection.goal = SelectionGoal::None;
 9569                    selection.reversed = false;
 9570                }
 9571                if selections.len() == 1 {
 9572                    let selection = selections
 9573                        .last()
 9574                        .expect("ensured that there's only one selection");
 9575                    let query = buffer
 9576                        .text_for_range(selection.start..selection.end)
 9577                        .collect::<String>();
 9578                    let is_empty = query.is_empty();
 9579                    let select_state = SelectNextState {
 9580                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9581                        wordwise: true,
 9582                        done: is_empty,
 9583                    };
 9584                    self.select_prev_state = Some(select_state);
 9585                } else {
 9586                    self.select_prev_state = None;
 9587                }
 9588
 9589                self.unfold_ranges(
 9590                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9591                    false,
 9592                    true,
 9593                    cx,
 9594                );
 9595                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9596                    s.select(selections);
 9597                });
 9598            } else if let Some(selected_text) = selected_text {
 9599                self.select_prev_state = Some(SelectNextState {
 9600                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9601                    wordwise: false,
 9602                    done: false,
 9603                });
 9604                self.select_previous(action, window, cx)?;
 9605            }
 9606        }
 9607        Ok(())
 9608    }
 9609
 9610    pub fn toggle_comments(
 9611        &mut self,
 9612        action: &ToggleComments,
 9613        window: &mut Window,
 9614        cx: &mut Context<Self>,
 9615    ) {
 9616        if self.read_only(cx) {
 9617            return;
 9618        }
 9619        let text_layout_details = &self.text_layout_details(window);
 9620        self.transact(window, cx, |this, window, cx| {
 9621            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9622            let mut edits = Vec::new();
 9623            let mut selection_edit_ranges = Vec::new();
 9624            let mut last_toggled_row = None;
 9625            let snapshot = this.buffer.read(cx).read(cx);
 9626            let empty_str: Arc<str> = Arc::default();
 9627            let mut suffixes_inserted = Vec::new();
 9628            let ignore_indent = action.ignore_indent;
 9629
 9630            fn comment_prefix_range(
 9631                snapshot: &MultiBufferSnapshot,
 9632                row: MultiBufferRow,
 9633                comment_prefix: &str,
 9634                comment_prefix_whitespace: &str,
 9635                ignore_indent: bool,
 9636            ) -> Range<Point> {
 9637                let indent_size = if ignore_indent {
 9638                    0
 9639                } else {
 9640                    snapshot.indent_size_for_line(row).len
 9641                };
 9642
 9643                let start = Point::new(row.0, indent_size);
 9644
 9645                let mut line_bytes = snapshot
 9646                    .bytes_in_range(start..snapshot.max_point())
 9647                    .flatten()
 9648                    .copied();
 9649
 9650                // If this line currently begins with the line comment prefix, then record
 9651                // the range containing the prefix.
 9652                if line_bytes
 9653                    .by_ref()
 9654                    .take(comment_prefix.len())
 9655                    .eq(comment_prefix.bytes())
 9656                {
 9657                    // Include any whitespace that matches the comment prefix.
 9658                    let matching_whitespace_len = line_bytes
 9659                        .zip(comment_prefix_whitespace.bytes())
 9660                        .take_while(|(a, b)| a == b)
 9661                        .count() as u32;
 9662                    let end = Point::new(
 9663                        start.row,
 9664                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9665                    );
 9666                    start..end
 9667                } else {
 9668                    start..start
 9669                }
 9670            }
 9671
 9672            fn comment_suffix_range(
 9673                snapshot: &MultiBufferSnapshot,
 9674                row: MultiBufferRow,
 9675                comment_suffix: &str,
 9676                comment_suffix_has_leading_space: bool,
 9677            ) -> Range<Point> {
 9678                let end = Point::new(row.0, snapshot.line_len(row));
 9679                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9680
 9681                let mut line_end_bytes = snapshot
 9682                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9683                    .flatten()
 9684                    .copied();
 9685
 9686                let leading_space_len = if suffix_start_column > 0
 9687                    && line_end_bytes.next() == Some(b' ')
 9688                    && comment_suffix_has_leading_space
 9689                {
 9690                    1
 9691                } else {
 9692                    0
 9693                };
 9694
 9695                // If this line currently begins with the line comment prefix, then record
 9696                // the range containing the prefix.
 9697                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9698                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9699                    start..end
 9700                } else {
 9701                    end..end
 9702                }
 9703            }
 9704
 9705            // TODO: Handle selections that cross excerpts
 9706            for selection in &mut selections {
 9707                let start_column = snapshot
 9708                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9709                    .len;
 9710                let language = if let Some(language) =
 9711                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9712                {
 9713                    language
 9714                } else {
 9715                    continue;
 9716                };
 9717
 9718                selection_edit_ranges.clear();
 9719
 9720                // If multiple selections contain a given row, avoid processing that
 9721                // row more than once.
 9722                let mut start_row = MultiBufferRow(selection.start.row);
 9723                if last_toggled_row == Some(start_row) {
 9724                    start_row = start_row.next_row();
 9725                }
 9726                let end_row =
 9727                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9728                        MultiBufferRow(selection.end.row - 1)
 9729                    } else {
 9730                        MultiBufferRow(selection.end.row)
 9731                    };
 9732                last_toggled_row = Some(end_row);
 9733
 9734                if start_row > end_row {
 9735                    continue;
 9736                }
 9737
 9738                // If the language has line comments, toggle those.
 9739                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9740
 9741                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9742                if ignore_indent {
 9743                    full_comment_prefixes = full_comment_prefixes
 9744                        .into_iter()
 9745                        .map(|s| Arc::from(s.trim_end()))
 9746                        .collect();
 9747                }
 9748
 9749                if !full_comment_prefixes.is_empty() {
 9750                    let first_prefix = full_comment_prefixes
 9751                        .first()
 9752                        .expect("prefixes is non-empty");
 9753                    let prefix_trimmed_lengths = full_comment_prefixes
 9754                        .iter()
 9755                        .map(|p| p.trim_end_matches(' ').len())
 9756                        .collect::<SmallVec<[usize; 4]>>();
 9757
 9758                    let mut all_selection_lines_are_comments = true;
 9759
 9760                    for row in start_row.0..=end_row.0 {
 9761                        let row = MultiBufferRow(row);
 9762                        if start_row < end_row && snapshot.is_line_blank(row) {
 9763                            continue;
 9764                        }
 9765
 9766                        let prefix_range = full_comment_prefixes
 9767                            .iter()
 9768                            .zip(prefix_trimmed_lengths.iter().copied())
 9769                            .map(|(prefix, trimmed_prefix_len)| {
 9770                                comment_prefix_range(
 9771                                    snapshot.deref(),
 9772                                    row,
 9773                                    &prefix[..trimmed_prefix_len],
 9774                                    &prefix[trimmed_prefix_len..],
 9775                                    ignore_indent,
 9776                                )
 9777                            })
 9778                            .max_by_key(|range| range.end.column - range.start.column)
 9779                            .expect("prefixes is non-empty");
 9780
 9781                        if prefix_range.is_empty() {
 9782                            all_selection_lines_are_comments = false;
 9783                        }
 9784
 9785                        selection_edit_ranges.push(prefix_range);
 9786                    }
 9787
 9788                    if all_selection_lines_are_comments {
 9789                        edits.extend(
 9790                            selection_edit_ranges
 9791                                .iter()
 9792                                .cloned()
 9793                                .map(|range| (range, empty_str.clone())),
 9794                        );
 9795                    } else {
 9796                        let min_column = selection_edit_ranges
 9797                            .iter()
 9798                            .map(|range| range.start.column)
 9799                            .min()
 9800                            .unwrap_or(0);
 9801                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9802                            let position = Point::new(range.start.row, min_column);
 9803                            (position..position, first_prefix.clone())
 9804                        }));
 9805                    }
 9806                } else if let Some((full_comment_prefix, comment_suffix)) =
 9807                    language.block_comment_delimiters()
 9808                {
 9809                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9810                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9811                    let prefix_range = comment_prefix_range(
 9812                        snapshot.deref(),
 9813                        start_row,
 9814                        comment_prefix,
 9815                        comment_prefix_whitespace,
 9816                        ignore_indent,
 9817                    );
 9818                    let suffix_range = comment_suffix_range(
 9819                        snapshot.deref(),
 9820                        end_row,
 9821                        comment_suffix.trim_start_matches(' '),
 9822                        comment_suffix.starts_with(' '),
 9823                    );
 9824
 9825                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9826                        edits.push((
 9827                            prefix_range.start..prefix_range.start,
 9828                            full_comment_prefix.clone(),
 9829                        ));
 9830                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9831                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9832                    } else {
 9833                        edits.push((prefix_range, empty_str.clone()));
 9834                        edits.push((suffix_range, empty_str.clone()));
 9835                    }
 9836                } else {
 9837                    continue;
 9838                }
 9839            }
 9840
 9841            drop(snapshot);
 9842            this.buffer.update(cx, |buffer, cx| {
 9843                buffer.edit(edits, None, cx);
 9844            });
 9845
 9846            // Adjust selections so that they end before any comment suffixes that
 9847            // were inserted.
 9848            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9849            let mut selections = this.selections.all::<Point>(cx);
 9850            let snapshot = this.buffer.read(cx).read(cx);
 9851            for selection in &mut selections {
 9852                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9853                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9854                        Ordering::Less => {
 9855                            suffixes_inserted.next();
 9856                            continue;
 9857                        }
 9858                        Ordering::Greater => break,
 9859                        Ordering::Equal => {
 9860                            if selection.end.column == snapshot.line_len(row) {
 9861                                if selection.is_empty() {
 9862                                    selection.start.column -= suffix_len as u32;
 9863                                }
 9864                                selection.end.column -= suffix_len as u32;
 9865                            }
 9866                            break;
 9867                        }
 9868                    }
 9869                }
 9870            }
 9871
 9872            drop(snapshot);
 9873            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9874                s.select(selections)
 9875            });
 9876
 9877            let selections = this.selections.all::<Point>(cx);
 9878            let selections_on_single_row = selections.windows(2).all(|selections| {
 9879                selections[0].start.row == selections[1].start.row
 9880                    && selections[0].end.row == selections[1].end.row
 9881                    && selections[0].start.row == selections[0].end.row
 9882            });
 9883            let selections_selecting = selections
 9884                .iter()
 9885                .any(|selection| selection.start != selection.end);
 9886            let advance_downwards = action.advance_downwards
 9887                && selections_on_single_row
 9888                && !selections_selecting
 9889                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9890
 9891            if advance_downwards {
 9892                let snapshot = this.buffer.read(cx).snapshot(cx);
 9893
 9894                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9895                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9896                        let mut point = display_point.to_point(display_snapshot);
 9897                        point.row += 1;
 9898                        point = snapshot.clip_point(point, Bias::Left);
 9899                        let display_point = point.to_display_point(display_snapshot);
 9900                        let goal = SelectionGoal::HorizontalPosition(
 9901                            display_snapshot
 9902                                .x_for_display_point(display_point, text_layout_details)
 9903                                .into(),
 9904                        );
 9905                        (display_point, goal)
 9906                    })
 9907                });
 9908            }
 9909        });
 9910    }
 9911
 9912    pub fn select_enclosing_symbol(
 9913        &mut self,
 9914        _: &SelectEnclosingSymbol,
 9915        window: &mut Window,
 9916        cx: &mut Context<Self>,
 9917    ) {
 9918        let buffer = self.buffer.read(cx).snapshot(cx);
 9919        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9920
 9921        fn update_selection(
 9922            selection: &Selection<usize>,
 9923            buffer_snap: &MultiBufferSnapshot,
 9924        ) -> Option<Selection<usize>> {
 9925            let cursor = selection.head();
 9926            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9927            for symbol in symbols.iter().rev() {
 9928                let start = symbol.range.start.to_offset(buffer_snap);
 9929                let end = symbol.range.end.to_offset(buffer_snap);
 9930                let new_range = start..end;
 9931                if start < selection.start || end > selection.end {
 9932                    return Some(Selection {
 9933                        id: selection.id,
 9934                        start: new_range.start,
 9935                        end: new_range.end,
 9936                        goal: SelectionGoal::None,
 9937                        reversed: selection.reversed,
 9938                    });
 9939                }
 9940            }
 9941            None
 9942        }
 9943
 9944        let mut selected_larger_symbol = false;
 9945        let new_selections = old_selections
 9946            .iter()
 9947            .map(|selection| match update_selection(selection, &buffer) {
 9948                Some(new_selection) => {
 9949                    if new_selection.range() != selection.range() {
 9950                        selected_larger_symbol = true;
 9951                    }
 9952                    new_selection
 9953                }
 9954                None => selection.clone(),
 9955            })
 9956            .collect::<Vec<_>>();
 9957
 9958        if selected_larger_symbol {
 9959            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9960                s.select(new_selections);
 9961            });
 9962        }
 9963    }
 9964
 9965    pub fn select_larger_syntax_node(
 9966        &mut self,
 9967        _: &SelectLargerSyntaxNode,
 9968        window: &mut Window,
 9969        cx: &mut Context<Self>,
 9970    ) {
 9971        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9972        let buffer = self.buffer.read(cx).snapshot(cx);
 9973        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9974
 9975        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9976        let mut selected_larger_node = false;
 9977        let new_selections = old_selections
 9978            .iter()
 9979            .map(|selection| {
 9980                let old_range = selection.start..selection.end;
 9981                let mut new_range = old_range.clone();
 9982                let mut new_node = None;
 9983                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9984                {
 9985                    new_node = Some(node);
 9986                    new_range = containing_range;
 9987                    if !display_map.intersects_fold(new_range.start)
 9988                        && !display_map.intersects_fold(new_range.end)
 9989                    {
 9990                        break;
 9991                    }
 9992                }
 9993
 9994                if let Some(node) = new_node {
 9995                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9996                    // nodes. Parent and grandparent are also logged because this operation will not
 9997                    // visit nodes that have the same range as their parent.
 9998                    log::info!("Node: {node:?}");
 9999                    let parent = node.parent();
10000                    log::info!("Parent: {parent:?}");
10001                    let grandparent = parent.and_then(|x| x.parent());
10002                    log::info!("Grandparent: {grandparent:?}");
10003                }
10004
10005                selected_larger_node |= new_range != old_range;
10006                Selection {
10007                    id: selection.id,
10008                    start: new_range.start,
10009                    end: new_range.end,
10010                    goal: SelectionGoal::None,
10011                    reversed: selection.reversed,
10012                }
10013            })
10014            .collect::<Vec<_>>();
10015
10016        if selected_larger_node {
10017            stack.push(old_selections);
10018            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10019                s.select(new_selections);
10020            });
10021        }
10022        self.select_larger_syntax_node_stack = stack;
10023    }
10024
10025    pub fn select_smaller_syntax_node(
10026        &mut self,
10027        _: &SelectSmallerSyntaxNode,
10028        window: &mut Window,
10029        cx: &mut Context<Self>,
10030    ) {
10031        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10032        if let Some(selections) = stack.pop() {
10033            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10034                s.select(selections.to_vec());
10035            });
10036        }
10037        self.select_larger_syntax_node_stack = stack;
10038    }
10039
10040    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10041        if !EditorSettings::get_global(cx).gutter.runnables {
10042            self.clear_tasks();
10043            return Task::ready(());
10044        }
10045        let project = self.project.as_ref().map(Entity::downgrade);
10046        cx.spawn_in(window, |this, mut cx| async move {
10047            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10048            let Some(project) = project.and_then(|p| p.upgrade()) else {
10049                return;
10050            };
10051            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10052                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10053            }) else {
10054                return;
10055            };
10056
10057            let hide_runnables = project
10058                .update(&mut cx, |project, cx| {
10059                    // Do not display any test indicators in non-dev server remote projects.
10060                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10061                })
10062                .unwrap_or(true);
10063            if hide_runnables {
10064                return;
10065            }
10066            let new_rows =
10067                cx.background_executor()
10068                    .spawn({
10069                        let snapshot = display_snapshot.clone();
10070                        async move {
10071                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10072                        }
10073                    })
10074                    .await;
10075
10076            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10077            this.update(&mut cx, |this, _| {
10078                this.clear_tasks();
10079                for (key, value) in rows {
10080                    this.insert_tasks(key, value);
10081                }
10082            })
10083            .ok();
10084        })
10085    }
10086    fn fetch_runnable_ranges(
10087        snapshot: &DisplaySnapshot,
10088        range: Range<Anchor>,
10089    ) -> Vec<language::RunnableRange> {
10090        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10091    }
10092
10093    fn runnable_rows(
10094        project: Entity<Project>,
10095        snapshot: DisplaySnapshot,
10096        runnable_ranges: Vec<RunnableRange>,
10097        mut cx: AsyncWindowContext,
10098    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10099        runnable_ranges
10100            .into_iter()
10101            .filter_map(|mut runnable| {
10102                let tasks = cx
10103                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10104                    .ok()?;
10105                if tasks.is_empty() {
10106                    return None;
10107                }
10108
10109                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10110
10111                let row = snapshot
10112                    .buffer_snapshot
10113                    .buffer_line_for_row(MultiBufferRow(point.row))?
10114                    .1
10115                    .start
10116                    .row;
10117
10118                let context_range =
10119                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10120                Some((
10121                    (runnable.buffer_id, row),
10122                    RunnableTasks {
10123                        templates: tasks,
10124                        offset: MultiBufferOffset(runnable.run_range.start),
10125                        context_range,
10126                        column: point.column,
10127                        extra_variables: runnable.extra_captures,
10128                    },
10129                ))
10130            })
10131            .collect()
10132    }
10133
10134    fn templates_with_tags(
10135        project: &Entity<Project>,
10136        runnable: &mut Runnable,
10137        cx: &mut App,
10138    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10139        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10140            let (worktree_id, file) = project
10141                .buffer_for_id(runnable.buffer, cx)
10142                .and_then(|buffer| buffer.read(cx).file())
10143                .map(|file| (file.worktree_id(cx), file.clone()))
10144                .unzip();
10145
10146            (
10147                project.task_store().read(cx).task_inventory().cloned(),
10148                worktree_id,
10149                file,
10150            )
10151        });
10152
10153        let tags = mem::take(&mut runnable.tags);
10154        let mut tags: Vec<_> = tags
10155            .into_iter()
10156            .flat_map(|tag| {
10157                let tag = tag.0.clone();
10158                inventory
10159                    .as_ref()
10160                    .into_iter()
10161                    .flat_map(|inventory| {
10162                        inventory.read(cx).list_tasks(
10163                            file.clone(),
10164                            Some(runnable.language.clone()),
10165                            worktree_id,
10166                            cx,
10167                        )
10168                    })
10169                    .filter(move |(_, template)| {
10170                        template.tags.iter().any(|source_tag| source_tag == &tag)
10171                    })
10172            })
10173            .sorted_by_key(|(kind, _)| kind.to_owned())
10174            .collect();
10175        if let Some((leading_tag_source, _)) = tags.first() {
10176            // Strongest source wins; if we have worktree tag binding, prefer that to
10177            // global and language bindings;
10178            // if we have a global binding, prefer that to language binding.
10179            let first_mismatch = tags
10180                .iter()
10181                .position(|(tag_source, _)| tag_source != leading_tag_source);
10182            if let Some(index) = first_mismatch {
10183                tags.truncate(index);
10184            }
10185        }
10186
10187        tags
10188    }
10189
10190    pub fn move_to_enclosing_bracket(
10191        &mut self,
10192        _: &MoveToEnclosingBracket,
10193        window: &mut Window,
10194        cx: &mut Context<Self>,
10195    ) {
10196        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10197            s.move_offsets_with(|snapshot, selection| {
10198                let Some(enclosing_bracket_ranges) =
10199                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10200                else {
10201                    return;
10202                };
10203
10204                let mut best_length = usize::MAX;
10205                let mut best_inside = false;
10206                let mut best_in_bracket_range = false;
10207                let mut best_destination = None;
10208                for (open, close) in enclosing_bracket_ranges {
10209                    let close = close.to_inclusive();
10210                    let length = close.end() - open.start;
10211                    let inside = selection.start >= open.end && selection.end <= *close.start();
10212                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10213                        || close.contains(&selection.head());
10214
10215                    // If best is next to a bracket and current isn't, skip
10216                    if !in_bracket_range && best_in_bracket_range {
10217                        continue;
10218                    }
10219
10220                    // Prefer smaller lengths unless best is inside and current isn't
10221                    if length > best_length && (best_inside || !inside) {
10222                        continue;
10223                    }
10224
10225                    best_length = length;
10226                    best_inside = inside;
10227                    best_in_bracket_range = in_bracket_range;
10228                    best_destination = Some(
10229                        if close.contains(&selection.start) && close.contains(&selection.end) {
10230                            if inside {
10231                                open.end
10232                            } else {
10233                                open.start
10234                            }
10235                        } else if inside {
10236                            *close.start()
10237                        } else {
10238                            *close.end()
10239                        },
10240                    );
10241                }
10242
10243                if let Some(destination) = best_destination {
10244                    selection.collapse_to(destination, SelectionGoal::None);
10245                }
10246            })
10247        });
10248    }
10249
10250    pub fn undo_selection(
10251        &mut self,
10252        _: &UndoSelection,
10253        window: &mut Window,
10254        cx: &mut Context<Self>,
10255    ) {
10256        self.end_selection(window, cx);
10257        self.selection_history.mode = SelectionHistoryMode::Undoing;
10258        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10259            self.change_selections(None, window, cx, |s| {
10260                s.select_anchors(entry.selections.to_vec())
10261            });
10262            self.select_next_state = entry.select_next_state;
10263            self.select_prev_state = entry.select_prev_state;
10264            self.add_selections_state = entry.add_selections_state;
10265            self.request_autoscroll(Autoscroll::newest(), cx);
10266        }
10267        self.selection_history.mode = SelectionHistoryMode::Normal;
10268    }
10269
10270    pub fn redo_selection(
10271        &mut self,
10272        _: &RedoSelection,
10273        window: &mut Window,
10274        cx: &mut Context<Self>,
10275    ) {
10276        self.end_selection(window, cx);
10277        self.selection_history.mode = SelectionHistoryMode::Redoing;
10278        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10279            self.change_selections(None, window, cx, |s| {
10280                s.select_anchors(entry.selections.to_vec())
10281            });
10282            self.select_next_state = entry.select_next_state;
10283            self.select_prev_state = entry.select_prev_state;
10284            self.add_selections_state = entry.add_selections_state;
10285            self.request_autoscroll(Autoscroll::newest(), cx);
10286        }
10287        self.selection_history.mode = SelectionHistoryMode::Normal;
10288    }
10289
10290    pub fn expand_excerpts(
10291        &mut self,
10292        action: &ExpandExcerpts,
10293        _: &mut Window,
10294        cx: &mut Context<Self>,
10295    ) {
10296        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10297    }
10298
10299    pub fn expand_excerpts_down(
10300        &mut self,
10301        action: &ExpandExcerptsDown,
10302        _: &mut Window,
10303        cx: &mut Context<Self>,
10304    ) {
10305        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10306    }
10307
10308    pub fn expand_excerpts_up(
10309        &mut self,
10310        action: &ExpandExcerptsUp,
10311        _: &mut Window,
10312        cx: &mut Context<Self>,
10313    ) {
10314        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10315    }
10316
10317    pub fn expand_excerpts_for_direction(
10318        &mut self,
10319        lines: u32,
10320        direction: ExpandExcerptDirection,
10321
10322        cx: &mut Context<Self>,
10323    ) {
10324        let selections = self.selections.disjoint_anchors();
10325
10326        let lines = if lines == 0 {
10327            EditorSettings::get_global(cx).expand_excerpt_lines
10328        } else {
10329            lines
10330        };
10331
10332        self.buffer.update(cx, |buffer, cx| {
10333            let snapshot = buffer.snapshot(cx);
10334            let mut excerpt_ids = selections
10335                .iter()
10336                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10337                .collect::<Vec<_>>();
10338            excerpt_ids.sort();
10339            excerpt_ids.dedup();
10340            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10341        })
10342    }
10343
10344    pub fn expand_excerpt(
10345        &mut self,
10346        excerpt: ExcerptId,
10347        direction: ExpandExcerptDirection,
10348        cx: &mut Context<Self>,
10349    ) {
10350        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10351        self.buffer.update(cx, |buffer, cx| {
10352            buffer.expand_excerpts([excerpt], lines, direction, cx)
10353        })
10354    }
10355
10356    pub fn go_to_singleton_buffer_point(
10357        &mut self,
10358        point: Point,
10359        window: &mut Window,
10360        cx: &mut Context<Self>,
10361    ) {
10362        self.go_to_singleton_buffer_range(point..point, window, cx);
10363    }
10364
10365    pub fn go_to_singleton_buffer_range(
10366        &mut self,
10367        range: Range<Point>,
10368        window: &mut Window,
10369        cx: &mut Context<Self>,
10370    ) {
10371        let multibuffer = self.buffer().read(cx);
10372        let Some(buffer) = multibuffer.as_singleton() else {
10373            return;
10374        };
10375        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10376            return;
10377        };
10378        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10379            return;
10380        };
10381        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10382            s.select_anchor_ranges([start..end])
10383        });
10384    }
10385
10386    fn go_to_diagnostic(
10387        &mut self,
10388        _: &GoToDiagnostic,
10389        window: &mut Window,
10390        cx: &mut Context<Self>,
10391    ) {
10392        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10393    }
10394
10395    fn go_to_prev_diagnostic(
10396        &mut self,
10397        _: &GoToPrevDiagnostic,
10398        window: &mut Window,
10399        cx: &mut Context<Self>,
10400    ) {
10401        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10402    }
10403
10404    pub fn go_to_diagnostic_impl(
10405        &mut self,
10406        direction: Direction,
10407        window: &mut Window,
10408        cx: &mut Context<Self>,
10409    ) {
10410        let buffer = self.buffer.read(cx).snapshot(cx);
10411        let selection = self.selections.newest::<usize>(cx);
10412
10413        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10414        if direction == Direction::Next {
10415            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10416                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10417                    return;
10418                };
10419                self.activate_diagnostics(
10420                    buffer_id,
10421                    popover.local_diagnostic.diagnostic.group_id,
10422                    window,
10423                    cx,
10424                );
10425                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10426                    let primary_range_start = active_diagnostics.primary_range.start;
10427                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10428                        let mut new_selection = s.newest_anchor().clone();
10429                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10430                        s.select_anchors(vec![new_selection.clone()]);
10431                    });
10432                    self.refresh_inline_completion(false, true, window, cx);
10433                }
10434                return;
10435            }
10436        }
10437
10438        let active_group_id = self
10439            .active_diagnostics
10440            .as_ref()
10441            .map(|active_group| active_group.group_id);
10442        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10443            active_diagnostics
10444                .primary_range
10445                .to_offset(&buffer)
10446                .to_inclusive()
10447        });
10448        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10449            if active_primary_range.contains(&selection.head()) {
10450                *active_primary_range.start()
10451            } else {
10452                selection.head()
10453            }
10454        } else {
10455            selection.head()
10456        };
10457
10458        let snapshot = self.snapshot(window, cx);
10459        let primary_diagnostics_before = buffer
10460            .diagnostics_in_range::<usize>(0..search_start)
10461            .filter(|entry| entry.diagnostic.is_primary)
10462            .filter(|entry| entry.range.start != entry.range.end)
10463            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10464            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10465            .collect::<Vec<_>>();
10466        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10467            primary_diagnostics_before
10468                .iter()
10469                .position(|entry| entry.diagnostic.group_id == active_group_id)
10470        });
10471
10472        let primary_diagnostics_after = buffer
10473            .diagnostics_in_range::<usize>(search_start..buffer.len())
10474            .filter(|entry| entry.diagnostic.is_primary)
10475            .filter(|entry| entry.range.start != entry.range.end)
10476            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10477            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10478            .collect::<Vec<_>>();
10479        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10480            primary_diagnostics_after
10481                .iter()
10482                .enumerate()
10483                .rev()
10484                .find_map(|(i, entry)| {
10485                    if entry.diagnostic.group_id == active_group_id {
10486                        Some(i)
10487                    } else {
10488                        None
10489                    }
10490                })
10491        });
10492
10493        let next_primary_diagnostic = match direction {
10494            Direction::Prev => primary_diagnostics_before
10495                .iter()
10496                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10497                .rev()
10498                .next(),
10499            Direction::Next => primary_diagnostics_after
10500                .iter()
10501                .skip(
10502                    last_same_group_diagnostic_after
10503                        .map(|index| index + 1)
10504                        .unwrap_or(0),
10505                )
10506                .next(),
10507        };
10508
10509        // Cycle around to the start of the buffer, potentially moving back to the start of
10510        // the currently active diagnostic.
10511        let cycle_around = || match direction {
10512            Direction::Prev => primary_diagnostics_after
10513                .iter()
10514                .rev()
10515                .chain(primary_diagnostics_before.iter().rev())
10516                .next(),
10517            Direction::Next => primary_diagnostics_before
10518                .iter()
10519                .chain(primary_diagnostics_after.iter())
10520                .next(),
10521        };
10522
10523        if let Some((primary_range, group_id)) = next_primary_diagnostic
10524            .or_else(cycle_around)
10525            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10526        {
10527            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10528                return;
10529            };
10530            self.activate_diagnostics(buffer_id, group_id, window, cx);
10531            if self.active_diagnostics.is_some() {
10532                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10533                    s.select(vec![Selection {
10534                        id: selection.id,
10535                        start: primary_range.start,
10536                        end: primary_range.start,
10537                        reversed: false,
10538                        goal: SelectionGoal::None,
10539                    }]);
10540                });
10541                self.refresh_inline_completion(false, true, window, cx);
10542            }
10543        }
10544    }
10545
10546    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10547        let snapshot = self.snapshot(window, cx);
10548        let selection = self.selections.newest::<Point>(cx);
10549        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10550    }
10551
10552    fn go_to_hunk_after_position(
10553        &mut self,
10554        snapshot: &EditorSnapshot,
10555        position: Point,
10556        window: &mut Window,
10557        cx: &mut Context<Editor>,
10558    ) -> Option<MultiBufferDiffHunk> {
10559        let mut hunk = snapshot
10560            .buffer_snapshot
10561            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10562            .find(|hunk| hunk.row_range.start.0 > position.row);
10563        if hunk.is_none() {
10564            hunk = snapshot
10565                .buffer_snapshot
10566                .diff_hunks_in_range(Point::zero()..position)
10567                .find(|hunk| hunk.row_range.end.0 < position.row)
10568        }
10569        if let Some(hunk) = &hunk {
10570            let destination = Point::new(hunk.row_range.start.0, 0);
10571            self.unfold_ranges(&[destination..destination], false, false, cx);
10572            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10573                s.select_ranges(vec![destination..destination]);
10574            });
10575        }
10576
10577        hunk
10578    }
10579
10580    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10581        let snapshot = self.snapshot(window, cx);
10582        let selection = self.selections.newest::<Point>(cx);
10583        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10584    }
10585
10586    fn go_to_hunk_before_position(
10587        &mut self,
10588        snapshot: &EditorSnapshot,
10589        position: Point,
10590        window: &mut Window,
10591        cx: &mut Context<Editor>,
10592    ) -> Option<MultiBufferDiffHunk> {
10593        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10594        if hunk.is_none() {
10595            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10596        }
10597        if let Some(hunk) = &hunk {
10598            let destination = Point::new(hunk.row_range.start.0, 0);
10599            self.unfold_ranges(&[destination..destination], false, false, cx);
10600            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10601                s.select_ranges(vec![destination..destination]);
10602            });
10603        }
10604
10605        hunk
10606    }
10607
10608    pub fn go_to_definition(
10609        &mut self,
10610        _: &GoToDefinition,
10611        window: &mut Window,
10612        cx: &mut Context<Self>,
10613    ) -> Task<Result<Navigated>> {
10614        let definition =
10615            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10616        cx.spawn_in(window, |editor, mut cx| async move {
10617            if definition.await? == Navigated::Yes {
10618                return Ok(Navigated::Yes);
10619            }
10620            match editor.update_in(&mut cx, |editor, window, cx| {
10621                editor.find_all_references(&FindAllReferences, window, cx)
10622            })? {
10623                Some(references) => references.await,
10624                None => Ok(Navigated::No),
10625            }
10626        })
10627    }
10628
10629    pub fn go_to_declaration(
10630        &mut self,
10631        _: &GoToDeclaration,
10632        window: &mut Window,
10633        cx: &mut Context<Self>,
10634    ) -> Task<Result<Navigated>> {
10635        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10636    }
10637
10638    pub fn go_to_declaration_split(
10639        &mut self,
10640        _: &GoToDeclaration,
10641        window: &mut Window,
10642        cx: &mut Context<Self>,
10643    ) -> Task<Result<Navigated>> {
10644        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10645    }
10646
10647    pub fn go_to_implementation(
10648        &mut self,
10649        _: &GoToImplementation,
10650        window: &mut Window,
10651        cx: &mut Context<Self>,
10652    ) -> Task<Result<Navigated>> {
10653        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10654    }
10655
10656    pub fn go_to_implementation_split(
10657        &mut self,
10658        _: &GoToImplementationSplit,
10659        window: &mut Window,
10660        cx: &mut Context<Self>,
10661    ) -> Task<Result<Navigated>> {
10662        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10663    }
10664
10665    pub fn go_to_type_definition(
10666        &mut self,
10667        _: &GoToTypeDefinition,
10668        window: &mut Window,
10669        cx: &mut Context<Self>,
10670    ) -> Task<Result<Navigated>> {
10671        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10672    }
10673
10674    pub fn go_to_definition_split(
10675        &mut self,
10676        _: &GoToDefinitionSplit,
10677        window: &mut Window,
10678        cx: &mut Context<Self>,
10679    ) -> Task<Result<Navigated>> {
10680        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10681    }
10682
10683    pub fn go_to_type_definition_split(
10684        &mut self,
10685        _: &GoToTypeDefinitionSplit,
10686        window: &mut Window,
10687        cx: &mut Context<Self>,
10688    ) -> Task<Result<Navigated>> {
10689        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10690    }
10691
10692    fn go_to_definition_of_kind(
10693        &mut self,
10694        kind: GotoDefinitionKind,
10695        split: bool,
10696        window: &mut Window,
10697        cx: &mut Context<Self>,
10698    ) -> Task<Result<Navigated>> {
10699        let Some(provider) = self.semantics_provider.clone() else {
10700            return Task::ready(Ok(Navigated::No));
10701        };
10702        let head = self.selections.newest::<usize>(cx).head();
10703        let buffer = self.buffer.read(cx);
10704        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10705            text_anchor
10706        } else {
10707            return Task::ready(Ok(Navigated::No));
10708        };
10709
10710        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10711            return Task::ready(Ok(Navigated::No));
10712        };
10713
10714        cx.spawn_in(window, |editor, mut cx| async move {
10715            let definitions = definitions.await?;
10716            let navigated = editor
10717                .update_in(&mut cx, |editor, window, cx| {
10718                    editor.navigate_to_hover_links(
10719                        Some(kind),
10720                        definitions
10721                            .into_iter()
10722                            .filter(|location| {
10723                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10724                            })
10725                            .map(HoverLink::Text)
10726                            .collect::<Vec<_>>(),
10727                        split,
10728                        window,
10729                        cx,
10730                    )
10731                })?
10732                .await?;
10733            anyhow::Ok(navigated)
10734        })
10735    }
10736
10737    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10738        let selection = self.selections.newest_anchor();
10739        let head = selection.head();
10740        let tail = selection.tail();
10741
10742        let Some((buffer, start_position)) =
10743            self.buffer.read(cx).text_anchor_for_position(head, cx)
10744        else {
10745            return;
10746        };
10747
10748        let end_position = if head != tail {
10749            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10750                return;
10751            };
10752            Some(pos)
10753        } else {
10754            None
10755        };
10756
10757        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10758            let url = if let Some(end_pos) = end_position {
10759                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10760            } else {
10761                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10762            };
10763
10764            if let Some(url) = url {
10765                editor.update(&mut cx, |_, cx| {
10766                    cx.open_url(&url);
10767                })
10768            } else {
10769                Ok(())
10770            }
10771        });
10772
10773        url_finder.detach();
10774    }
10775
10776    pub fn open_selected_filename(
10777        &mut self,
10778        _: &OpenSelectedFilename,
10779        window: &mut Window,
10780        cx: &mut Context<Self>,
10781    ) {
10782        let Some(workspace) = self.workspace() else {
10783            return;
10784        };
10785
10786        let position = self.selections.newest_anchor().head();
10787
10788        let Some((buffer, buffer_position)) =
10789            self.buffer.read(cx).text_anchor_for_position(position, cx)
10790        else {
10791            return;
10792        };
10793
10794        let project = self.project.clone();
10795
10796        cx.spawn_in(window, |_, mut cx| async move {
10797            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10798
10799            if let Some((_, path)) = result {
10800                workspace
10801                    .update_in(&mut cx, |workspace, window, cx| {
10802                        workspace.open_resolved_path(path, window, cx)
10803                    })?
10804                    .await?;
10805            }
10806            anyhow::Ok(())
10807        })
10808        .detach();
10809    }
10810
10811    pub(crate) fn navigate_to_hover_links(
10812        &mut self,
10813        kind: Option<GotoDefinitionKind>,
10814        mut definitions: Vec<HoverLink>,
10815        split: bool,
10816        window: &mut Window,
10817        cx: &mut Context<Editor>,
10818    ) -> Task<Result<Navigated>> {
10819        // If there is one definition, just open it directly
10820        if definitions.len() == 1 {
10821            let definition = definitions.pop().unwrap();
10822
10823            enum TargetTaskResult {
10824                Location(Option<Location>),
10825                AlreadyNavigated,
10826            }
10827
10828            let target_task = match definition {
10829                HoverLink::Text(link) => {
10830                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10831                }
10832                HoverLink::InlayHint(lsp_location, server_id) => {
10833                    let computation =
10834                        self.compute_target_location(lsp_location, server_id, window, cx);
10835                    cx.background_executor().spawn(async move {
10836                        let location = computation.await?;
10837                        Ok(TargetTaskResult::Location(location))
10838                    })
10839                }
10840                HoverLink::Url(url) => {
10841                    cx.open_url(&url);
10842                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10843                }
10844                HoverLink::File(path) => {
10845                    if let Some(workspace) = self.workspace() {
10846                        cx.spawn_in(window, |_, mut cx| async move {
10847                            workspace
10848                                .update_in(&mut cx, |workspace, window, cx| {
10849                                    workspace.open_resolved_path(path, window, cx)
10850                                })?
10851                                .await
10852                                .map(|_| TargetTaskResult::AlreadyNavigated)
10853                        })
10854                    } else {
10855                        Task::ready(Ok(TargetTaskResult::Location(None)))
10856                    }
10857                }
10858            };
10859            cx.spawn_in(window, |editor, mut cx| async move {
10860                let target = match target_task.await.context("target resolution task")? {
10861                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10862                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10863                    TargetTaskResult::Location(Some(target)) => target,
10864                };
10865
10866                editor.update_in(&mut cx, |editor, window, cx| {
10867                    let Some(workspace) = editor.workspace() else {
10868                        return Navigated::No;
10869                    };
10870                    let pane = workspace.read(cx).active_pane().clone();
10871
10872                    let range = target.range.to_point(target.buffer.read(cx));
10873                    let range = editor.range_for_match(&range);
10874                    let range = collapse_multiline_range(range);
10875
10876                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10877                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10878                    } else {
10879                        window.defer(cx, move |window, cx| {
10880                            let target_editor: Entity<Self> =
10881                                workspace.update(cx, |workspace, cx| {
10882                                    let pane = if split {
10883                                        workspace.adjacent_pane(window, cx)
10884                                    } else {
10885                                        workspace.active_pane().clone()
10886                                    };
10887
10888                                    workspace.open_project_item(
10889                                        pane,
10890                                        target.buffer.clone(),
10891                                        true,
10892                                        true,
10893                                        window,
10894                                        cx,
10895                                    )
10896                                });
10897                            target_editor.update(cx, |target_editor, cx| {
10898                                // When selecting a definition in a different buffer, disable the nav history
10899                                // to avoid creating a history entry at the previous cursor location.
10900                                pane.update(cx, |pane, _| pane.disable_history());
10901                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10902                                pane.update(cx, |pane, _| pane.enable_history());
10903                            });
10904                        });
10905                    }
10906                    Navigated::Yes
10907                })
10908            })
10909        } else if !definitions.is_empty() {
10910            cx.spawn_in(window, |editor, mut cx| async move {
10911                let (title, location_tasks, workspace) = editor
10912                    .update_in(&mut cx, |editor, window, cx| {
10913                        let tab_kind = match kind {
10914                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10915                            _ => "Definitions",
10916                        };
10917                        let title = definitions
10918                            .iter()
10919                            .find_map(|definition| match definition {
10920                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10921                                    let buffer = origin.buffer.read(cx);
10922                                    format!(
10923                                        "{} for {}",
10924                                        tab_kind,
10925                                        buffer
10926                                            .text_for_range(origin.range.clone())
10927                                            .collect::<String>()
10928                                    )
10929                                }),
10930                                HoverLink::InlayHint(_, _) => None,
10931                                HoverLink::Url(_) => None,
10932                                HoverLink::File(_) => None,
10933                            })
10934                            .unwrap_or(tab_kind.to_string());
10935                        let location_tasks = definitions
10936                            .into_iter()
10937                            .map(|definition| match definition {
10938                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10939                                HoverLink::InlayHint(lsp_location, server_id) => editor
10940                                    .compute_target_location(lsp_location, server_id, window, cx),
10941                                HoverLink::Url(_) => Task::ready(Ok(None)),
10942                                HoverLink::File(_) => Task::ready(Ok(None)),
10943                            })
10944                            .collect::<Vec<_>>();
10945                        (title, location_tasks, editor.workspace().clone())
10946                    })
10947                    .context("location tasks preparation")?;
10948
10949                let locations = future::join_all(location_tasks)
10950                    .await
10951                    .into_iter()
10952                    .filter_map(|location| location.transpose())
10953                    .collect::<Result<_>>()
10954                    .context("location tasks")?;
10955
10956                let Some(workspace) = workspace else {
10957                    return Ok(Navigated::No);
10958                };
10959                let opened = workspace
10960                    .update_in(&mut cx, |workspace, window, cx| {
10961                        Self::open_locations_in_multibuffer(
10962                            workspace,
10963                            locations,
10964                            title,
10965                            split,
10966                            MultibufferSelectionMode::First,
10967                            window,
10968                            cx,
10969                        )
10970                    })
10971                    .ok();
10972
10973                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10974            })
10975        } else {
10976            Task::ready(Ok(Navigated::No))
10977        }
10978    }
10979
10980    fn compute_target_location(
10981        &self,
10982        lsp_location: lsp::Location,
10983        server_id: LanguageServerId,
10984        window: &mut Window,
10985        cx: &mut Context<Self>,
10986    ) -> Task<anyhow::Result<Option<Location>>> {
10987        let Some(project) = self.project.clone() else {
10988            return Task::ready(Ok(None));
10989        };
10990
10991        cx.spawn_in(window, move |editor, mut cx| async move {
10992            let location_task = editor.update(&mut cx, |_, cx| {
10993                project.update(cx, |project, cx| {
10994                    let language_server_name = project
10995                        .language_server_statuses(cx)
10996                        .find(|(id, _)| server_id == *id)
10997                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10998                    language_server_name.map(|language_server_name| {
10999                        project.open_local_buffer_via_lsp(
11000                            lsp_location.uri.clone(),
11001                            server_id,
11002                            language_server_name,
11003                            cx,
11004                        )
11005                    })
11006                })
11007            })?;
11008            let location = match location_task {
11009                Some(task) => Some({
11010                    let target_buffer_handle = task.await.context("open local buffer")?;
11011                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11012                        let target_start = target_buffer
11013                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11014                        let target_end = target_buffer
11015                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11016                        target_buffer.anchor_after(target_start)
11017                            ..target_buffer.anchor_before(target_end)
11018                    })?;
11019                    Location {
11020                        buffer: target_buffer_handle,
11021                        range,
11022                    }
11023                }),
11024                None => None,
11025            };
11026            Ok(location)
11027        })
11028    }
11029
11030    pub fn find_all_references(
11031        &mut self,
11032        _: &FindAllReferences,
11033        window: &mut Window,
11034        cx: &mut Context<Self>,
11035    ) -> Option<Task<Result<Navigated>>> {
11036        let selection = self.selections.newest::<usize>(cx);
11037        let multi_buffer = self.buffer.read(cx);
11038        let head = selection.head();
11039
11040        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11041        let head_anchor = multi_buffer_snapshot.anchor_at(
11042            head,
11043            if head < selection.tail() {
11044                Bias::Right
11045            } else {
11046                Bias::Left
11047            },
11048        );
11049
11050        match self
11051            .find_all_references_task_sources
11052            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11053        {
11054            Ok(_) => {
11055                log::info!(
11056                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11057                );
11058                return None;
11059            }
11060            Err(i) => {
11061                self.find_all_references_task_sources.insert(i, head_anchor);
11062            }
11063        }
11064
11065        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11066        let workspace = self.workspace()?;
11067        let project = workspace.read(cx).project().clone();
11068        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11069        Some(cx.spawn_in(window, |editor, mut cx| async move {
11070            let _cleanup = defer({
11071                let mut cx = cx.clone();
11072                move || {
11073                    let _ = editor.update(&mut cx, |editor, _| {
11074                        if let Ok(i) =
11075                            editor
11076                                .find_all_references_task_sources
11077                                .binary_search_by(|anchor| {
11078                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11079                                })
11080                        {
11081                            editor.find_all_references_task_sources.remove(i);
11082                        }
11083                    });
11084                }
11085            });
11086
11087            let locations = references.await?;
11088            if locations.is_empty() {
11089                return anyhow::Ok(Navigated::No);
11090            }
11091
11092            workspace.update_in(&mut cx, |workspace, window, cx| {
11093                let title = locations
11094                    .first()
11095                    .as_ref()
11096                    .map(|location| {
11097                        let buffer = location.buffer.read(cx);
11098                        format!(
11099                            "References to `{}`",
11100                            buffer
11101                                .text_for_range(location.range.clone())
11102                                .collect::<String>()
11103                        )
11104                    })
11105                    .unwrap();
11106                Self::open_locations_in_multibuffer(
11107                    workspace,
11108                    locations,
11109                    title,
11110                    false,
11111                    MultibufferSelectionMode::First,
11112                    window,
11113                    cx,
11114                );
11115                Navigated::Yes
11116            })
11117        }))
11118    }
11119
11120    /// Opens a multibuffer with the given project locations in it
11121    pub fn open_locations_in_multibuffer(
11122        workspace: &mut Workspace,
11123        mut locations: Vec<Location>,
11124        title: String,
11125        split: bool,
11126        multibuffer_selection_mode: MultibufferSelectionMode,
11127        window: &mut Window,
11128        cx: &mut Context<Workspace>,
11129    ) {
11130        // If there are multiple definitions, open them in a multibuffer
11131        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11132        let mut locations = locations.into_iter().peekable();
11133        let mut ranges = Vec::new();
11134        let capability = workspace.project().read(cx).capability();
11135
11136        let excerpt_buffer = cx.new(|cx| {
11137            let mut multibuffer = MultiBuffer::new(capability);
11138            while let Some(location) = locations.next() {
11139                let buffer = location.buffer.read(cx);
11140                let mut ranges_for_buffer = Vec::new();
11141                let range = location.range.to_offset(buffer);
11142                ranges_for_buffer.push(range.clone());
11143
11144                while let Some(next_location) = locations.peek() {
11145                    if next_location.buffer == location.buffer {
11146                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11147                        locations.next();
11148                    } else {
11149                        break;
11150                    }
11151                }
11152
11153                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11154                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11155                    location.buffer.clone(),
11156                    ranges_for_buffer,
11157                    DEFAULT_MULTIBUFFER_CONTEXT,
11158                    cx,
11159                ))
11160            }
11161
11162            multibuffer.with_title(title)
11163        });
11164
11165        let editor = cx.new(|cx| {
11166            Editor::for_multibuffer(
11167                excerpt_buffer,
11168                Some(workspace.project().clone()),
11169                true,
11170                window,
11171                cx,
11172            )
11173        });
11174        editor.update(cx, |editor, cx| {
11175            match multibuffer_selection_mode {
11176                MultibufferSelectionMode::First => {
11177                    if let Some(first_range) = ranges.first() {
11178                        editor.change_selections(None, window, cx, |selections| {
11179                            selections.clear_disjoint();
11180                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11181                        });
11182                    }
11183                    editor.highlight_background::<Self>(
11184                        &ranges,
11185                        |theme| theme.editor_highlighted_line_background,
11186                        cx,
11187                    );
11188                }
11189                MultibufferSelectionMode::All => {
11190                    editor.change_selections(None, window, cx, |selections| {
11191                        selections.clear_disjoint();
11192                        selections.select_anchor_ranges(ranges);
11193                    });
11194                }
11195            }
11196            editor.register_buffers_with_language_servers(cx);
11197        });
11198
11199        let item = Box::new(editor);
11200        let item_id = item.item_id();
11201
11202        if split {
11203            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11204        } else {
11205            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11206                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11207                    pane.close_current_preview_item(window, cx)
11208                } else {
11209                    None
11210                }
11211            });
11212            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11213        }
11214        workspace.active_pane().update(cx, |pane, cx| {
11215            pane.set_preview_item_id(Some(item_id), cx);
11216        });
11217    }
11218
11219    pub fn rename(
11220        &mut self,
11221        _: &Rename,
11222        window: &mut Window,
11223        cx: &mut Context<Self>,
11224    ) -> Option<Task<Result<()>>> {
11225        use language::ToOffset as _;
11226
11227        let provider = self.semantics_provider.clone()?;
11228        let selection = self.selections.newest_anchor().clone();
11229        let (cursor_buffer, cursor_buffer_position) = self
11230            .buffer
11231            .read(cx)
11232            .text_anchor_for_position(selection.head(), cx)?;
11233        let (tail_buffer, cursor_buffer_position_end) = self
11234            .buffer
11235            .read(cx)
11236            .text_anchor_for_position(selection.tail(), cx)?;
11237        if tail_buffer != cursor_buffer {
11238            return None;
11239        }
11240
11241        let snapshot = cursor_buffer.read(cx).snapshot();
11242        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11243        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11244        let prepare_rename = provider
11245            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11246            .unwrap_or_else(|| Task::ready(Ok(None)));
11247        drop(snapshot);
11248
11249        Some(cx.spawn_in(window, |this, mut cx| async move {
11250            let rename_range = if let Some(range) = prepare_rename.await? {
11251                Some(range)
11252            } else {
11253                this.update(&mut cx, |this, cx| {
11254                    let buffer = this.buffer.read(cx).snapshot(cx);
11255                    let mut buffer_highlights = this
11256                        .document_highlights_for_position(selection.head(), &buffer)
11257                        .filter(|highlight| {
11258                            highlight.start.excerpt_id == selection.head().excerpt_id
11259                                && highlight.end.excerpt_id == selection.head().excerpt_id
11260                        });
11261                    buffer_highlights
11262                        .next()
11263                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11264                })?
11265            };
11266            if let Some(rename_range) = rename_range {
11267                this.update_in(&mut cx, |this, window, cx| {
11268                    let snapshot = cursor_buffer.read(cx).snapshot();
11269                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11270                    let cursor_offset_in_rename_range =
11271                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11272                    let cursor_offset_in_rename_range_end =
11273                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11274
11275                    this.take_rename(false, window, cx);
11276                    let buffer = this.buffer.read(cx).read(cx);
11277                    let cursor_offset = selection.head().to_offset(&buffer);
11278                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11279                    let rename_end = rename_start + rename_buffer_range.len();
11280                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11281                    let mut old_highlight_id = None;
11282                    let old_name: Arc<str> = buffer
11283                        .chunks(rename_start..rename_end, true)
11284                        .map(|chunk| {
11285                            if old_highlight_id.is_none() {
11286                                old_highlight_id = chunk.syntax_highlight_id;
11287                            }
11288                            chunk.text
11289                        })
11290                        .collect::<String>()
11291                        .into();
11292
11293                    drop(buffer);
11294
11295                    // Position the selection in the rename editor so that it matches the current selection.
11296                    this.show_local_selections = false;
11297                    let rename_editor = cx.new(|cx| {
11298                        let mut editor = Editor::single_line(window, cx);
11299                        editor.buffer.update(cx, |buffer, cx| {
11300                            buffer.edit([(0..0, old_name.clone())], None, cx)
11301                        });
11302                        let rename_selection_range = match cursor_offset_in_rename_range
11303                            .cmp(&cursor_offset_in_rename_range_end)
11304                        {
11305                            Ordering::Equal => {
11306                                editor.select_all(&SelectAll, window, cx);
11307                                return editor;
11308                            }
11309                            Ordering::Less => {
11310                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11311                            }
11312                            Ordering::Greater => {
11313                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11314                            }
11315                        };
11316                        if rename_selection_range.end > old_name.len() {
11317                            editor.select_all(&SelectAll, window, cx);
11318                        } else {
11319                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11320                                s.select_ranges([rename_selection_range]);
11321                            });
11322                        }
11323                        editor
11324                    });
11325                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11326                        if e == &EditorEvent::Focused {
11327                            cx.emit(EditorEvent::FocusedIn)
11328                        }
11329                    })
11330                    .detach();
11331
11332                    let write_highlights =
11333                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11334                    let read_highlights =
11335                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11336                    let ranges = write_highlights
11337                        .iter()
11338                        .flat_map(|(_, ranges)| ranges.iter())
11339                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11340                        .cloned()
11341                        .collect();
11342
11343                    this.highlight_text::<Rename>(
11344                        ranges,
11345                        HighlightStyle {
11346                            fade_out: Some(0.6),
11347                            ..Default::default()
11348                        },
11349                        cx,
11350                    );
11351                    let rename_focus_handle = rename_editor.focus_handle(cx);
11352                    window.focus(&rename_focus_handle);
11353                    let block_id = this.insert_blocks(
11354                        [BlockProperties {
11355                            style: BlockStyle::Flex,
11356                            placement: BlockPlacement::Below(range.start),
11357                            height: 1,
11358                            render: Arc::new({
11359                                let rename_editor = rename_editor.clone();
11360                                move |cx: &mut BlockContext| {
11361                                    let mut text_style = cx.editor_style.text.clone();
11362                                    if let Some(highlight_style) = old_highlight_id
11363                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11364                                    {
11365                                        text_style = text_style.highlight(highlight_style);
11366                                    }
11367                                    div()
11368                                        .block_mouse_down()
11369                                        .pl(cx.anchor_x)
11370                                        .child(EditorElement::new(
11371                                            &rename_editor,
11372                                            EditorStyle {
11373                                                background: cx.theme().system().transparent,
11374                                                local_player: cx.editor_style.local_player,
11375                                                text: text_style,
11376                                                scrollbar_width: cx.editor_style.scrollbar_width,
11377                                                syntax: cx.editor_style.syntax.clone(),
11378                                                status: cx.editor_style.status.clone(),
11379                                                inlay_hints_style: HighlightStyle {
11380                                                    font_weight: Some(FontWeight::BOLD),
11381                                                    ..make_inlay_hints_style(cx.app)
11382                                                },
11383                                                inline_completion_styles: make_suggestion_styles(
11384                                                    cx.app,
11385                                                ),
11386                                                ..EditorStyle::default()
11387                                            },
11388                                        ))
11389                                        .into_any_element()
11390                                }
11391                            }),
11392                            priority: 0,
11393                        }],
11394                        Some(Autoscroll::fit()),
11395                        cx,
11396                    )[0];
11397                    this.pending_rename = Some(RenameState {
11398                        range,
11399                        old_name,
11400                        editor: rename_editor,
11401                        block_id,
11402                    });
11403                })?;
11404            }
11405
11406            Ok(())
11407        }))
11408    }
11409
11410    pub fn confirm_rename(
11411        &mut self,
11412        _: &ConfirmRename,
11413        window: &mut Window,
11414        cx: &mut Context<Self>,
11415    ) -> Option<Task<Result<()>>> {
11416        let rename = self.take_rename(false, window, cx)?;
11417        let workspace = self.workspace()?.downgrade();
11418        let (buffer, start) = self
11419            .buffer
11420            .read(cx)
11421            .text_anchor_for_position(rename.range.start, cx)?;
11422        let (end_buffer, _) = self
11423            .buffer
11424            .read(cx)
11425            .text_anchor_for_position(rename.range.end, cx)?;
11426        if buffer != end_buffer {
11427            return None;
11428        }
11429
11430        let old_name = rename.old_name;
11431        let new_name = rename.editor.read(cx).text(cx);
11432
11433        let rename = self.semantics_provider.as_ref()?.perform_rename(
11434            &buffer,
11435            start,
11436            new_name.clone(),
11437            cx,
11438        )?;
11439
11440        Some(cx.spawn_in(window, |editor, mut cx| async move {
11441            let project_transaction = rename.await?;
11442            Self::open_project_transaction(
11443                &editor,
11444                workspace,
11445                project_transaction,
11446                format!("Rename: {}{}", old_name, new_name),
11447                cx.clone(),
11448            )
11449            .await?;
11450
11451            editor.update(&mut cx, |editor, cx| {
11452                editor.refresh_document_highlights(cx);
11453            })?;
11454            Ok(())
11455        }))
11456    }
11457
11458    fn take_rename(
11459        &mut self,
11460        moving_cursor: bool,
11461        window: &mut Window,
11462        cx: &mut Context<Self>,
11463    ) -> Option<RenameState> {
11464        let rename = self.pending_rename.take()?;
11465        if rename.editor.focus_handle(cx).is_focused(window) {
11466            window.focus(&self.focus_handle);
11467        }
11468
11469        self.remove_blocks(
11470            [rename.block_id].into_iter().collect(),
11471            Some(Autoscroll::fit()),
11472            cx,
11473        );
11474        self.clear_highlights::<Rename>(cx);
11475        self.show_local_selections = true;
11476
11477        if moving_cursor {
11478            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11479                editor.selections.newest::<usize>(cx).head()
11480            });
11481
11482            // Update the selection to match the position of the selection inside
11483            // the rename editor.
11484            let snapshot = self.buffer.read(cx).read(cx);
11485            let rename_range = rename.range.to_offset(&snapshot);
11486            let cursor_in_editor = snapshot
11487                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11488                .min(rename_range.end);
11489            drop(snapshot);
11490
11491            self.change_selections(None, window, cx, |s| {
11492                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11493            });
11494        } else {
11495            self.refresh_document_highlights(cx);
11496        }
11497
11498        Some(rename)
11499    }
11500
11501    pub fn pending_rename(&self) -> Option<&RenameState> {
11502        self.pending_rename.as_ref()
11503    }
11504
11505    fn format(
11506        &mut self,
11507        _: &Format,
11508        window: &mut Window,
11509        cx: &mut Context<Self>,
11510    ) -> Option<Task<Result<()>>> {
11511        let project = match &self.project {
11512            Some(project) => project.clone(),
11513            None => return None,
11514        };
11515
11516        Some(self.perform_format(
11517            project,
11518            FormatTrigger::Manual,
11519            FormatTarget::Buffers,
11520            window,
11521            cx,
11522        ))
11523    }
11524
11525    fn format_selections(
11526        &mut self,
11527        _: &FormatSelections,
11528        window: &mut Window,
11529        cx: &mut Context<Self>,
11530    ) -> Option<Task<Result<()>>> {
11531        let project = match &self.project {
11532            Some(project) => project.clone(),
11533            None => return None,
11534        };
11535
11536        let ranges = self
11537            .selections
11538            .all_adjusted(cx)
11539            .into_iter()
11540            .map(|selection| selection.range())
11541            .collect_vec();
11542
11543        Some(self.perform_format(
11544            project,
11545            FormatTrigger::Manual,
11546            FormatTarget::Ranges(ranges),
11547            window,
11548            cx,
11549        ))
11550    }
11551
11552    fn perform_format(
11553        &mut self,
11554        project: Entity<Project>,
11555        trigger: FormatTrigger,
11556        target: FormatTarget,
11557        window: &mut Window,
11558        cx: &mut Context<Self>,
11559    ) -> Task<Result<()>> {
11560        let buffer = self.buffer.clone();
11561        let (buffers, target) = match target {
11562            FormatTarget::Buffers => {
11563                let mut buffers = buffer.read(cx).all_buffers();
11564                if trigger == FormatTrigger::Save {
11565                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11566                }
11567                (buffers, LspFormatTarget::Buffers)
11568            }
11569            FormatTarget::Ranges(selection_ranges) => {
11570                let multi_buffer = buffer.read(cx);
11571                let snapshot = multi_buffer.read(cx);
11572                let mut buffers = HashSet::default();
11573                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11574                    BTreeMap::new();
11575                for selection_range in selection_ranges {
11576                    for (buffer, buffer_range, _) in
11577                        snapshot.range_to_buffer_ranges(selection_range)
11578                    {
11579                        let buffer_id = buffer.remote_id();
11580                        let start = buffer.anchor_before(buffer_range.start);
11581                        let end = buffer.anchor_after(buffer_range.end);
11582                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11583                        buffer_id_to_ranges
11584                            .entry(buffer_id)
11585                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11586                            .or_insert_with(|| vec![start..end]);
11587                    }
11588                }
11589                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11590            }
11591        };
11592
11593        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11594        let format = project.update(cx, |project, cx| {
11595            project.format(buffers, target, true, trigger, cx)
11596        });
11597
11598        cx.spawn_in(window, |_, mut cx| async move {
11599            let transaction = futures::select_biased! {
11600                () = timeout => {
11601                    log::warn!("timed out waiting for formatting");
11602                    None
11603                }
11604                transaction = format.log_err().fuse() => transaction,
11605            };
11606
11607            buffer
11608                .update(&mut cx, |buffer, cx| {
11609                    if let Some(transaction) = transaction {
11610                        if !buffer.is_singleton() {
11611                            buffer.push_transaction(&transaction.0, cx);
11612                        }
11613                    }
11614
11615                    cx.notify();
11616                })
11617                .ok();
11618
11619            Ok(())
11620        })
11621    }
11622
11623    fn restart_language_server(
11624        &mut self,
11625        _: &RestartLanguageServer,
11626        _: &mut Window,
11627        cx: &mut Context<Self>,
11628    ) {
11629        if let Some(project) = self.project.clone() {
11630            self.buffer.update(cx, |multi_buffer, cx| {
11631                project.update(cx, |project, cx| {
11632                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11633                });
11634            })
11635        }
11636    }
11637
11638    fn cancel_language_server_work(
11639        workspace: &mut Workspace,
11640        _: &actions::CancelLanguageServerWork,
11641        _: &mut Window,
11642        cx: &mut Context<Workspace>,
11643    ) {
11644        let project = workspace.project();
11645        let buffers = workspace
11646            .active_item(cx)
11647            .and_then(|item| item.act_as::<Editor>(cx))
11648            .map_or(HashSet::default(), |editor| {
11649                editor.read(cx).buffer.read(cx).all_buffers()
11650            });
11651        project.update(cx, |project, cx| {
11652            project.cancel_language_server_work_for_buffers(buffers, cx);
11653        });
11654    }
11655
11656    fn show_character_palette(
11657        &mut self,
11658        _: &ShowCharacterPalette,
11659        window: &mut Window,
11660        _: &mut Context<Self>,
11661    ) {
11662        window.show_character_palette();
11663    }
11664
11665    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11666        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11667            let buffer = self.buffer.read(cx).snapshot(cx);
11668            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11669            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11670            let is_valid = buffer
11671                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11672                .any(|entry| {
11673                    entry.diagnostic.is_primary
11674                        && !entry.range.is_empty()
11675                        && entry.range.start == primary_range_start
11676                        && entry.diagnostic.message == active_diagnostics.primary_message
11677                });
11678
11679            if is_valid != active_diagnostics.is_valid {
11680                active_diagnostics.is_valid = is_valid;
11681                let mut new_styles = HashMap::default();
11682                for (block_id, diagnostic) in &active_diagnostics.blocks {
11683                    new_styles.insert(
11684                        *block_id,
11685                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11686                    );
11687                }
11688                self.display_map.update(cx, |display_map, _cx| {
11689                    display_map.replace_blocks(new_styles)
11690                });
11691            }
11692        }
11693    }
11694
11695    fn activate_diagnostics(
11696        &mut self,
11697        buffer_id: BufferId,
11698        group_id: usize,
11699        window: &mut Window,
11700        cx: &mut Context<Self>,
11701    ) {
11702        self.dismiss_diagnostics(cx);
11703        let snapshot = self.snapshot(window, cx);
11704        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11705            let buffer = self.buffer.read(cx).snapshot(cx);
11706
11707            let mut primary_range = None;
11708            let mut primary_message = None;
11709            let diagnostic_group = buffer
11710                .diagnostic_group(buffer_id, group_id)
11711                .filter_map(|entry| {
11712                    let start = entry.range.start;
11713                    let end = entry.range.end;
11714                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11715                        && (start.row == end.row
11716                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11717                    {
11718                        return None;
11719                    }
11720                    if entry.diagnostic.is_primary {
11721                        primary_range = Some(entry.range.clone());
11722                        primary_message = Some(entry.diagnostic.message.clone());
11723                    }
11724                    Some(entry)
11725                })
11726                .collect::<Vec<_>>();
11727            let primary_range = primary_range?;
11728            let primary_message = primary_message?;
11729
11730            let blocks = display_map
11731                .insert_blocks(
11732                    diagnostic_group.iter().map(|entry| {
11733                        let diagnostic = entry.diagnostic.clone();
11734                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11735                        BlockProperties {
11736                            style: BlockStyle::Fixed,
11737                            placement: BlockPlacement::Below(
11738                                buffer.anchor_after(entry.range.start),
11739                            ),
11740                            height: message_height,
11741                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11742                            priority: 0,
11743                        }
11744                    }),
11745                    cx,
11746                )
11747                .into_iter()
11748                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11749                .collect();
11750
11751            Some(ActiveDiagnosticGroup {
11752                primary_range: buffer.anchor_before(primary_range.start)
11753                    ..buffer.anchor_after(primary_range.end),
11754                primary_message,
11755                group_id,
11756                blocks,
11757                is_valid: true,
11758            })
11759        });
11760    }
11761
11762    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11763        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11764            self.display_map.update(cx, |display_map, cx| {
11765                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11766            });
11767            cx.notify();
11768        }
11769    }
11770
11771    pub fn set_selections_from_remote(
11772        &mut self,
11773        selections: Vec<Selection<Anchor>>,
11774        pending_selection: Option<Selection<Anchor>>,
11775        window: &mut Window,
11776        cx: &mut Context<Self>,
11777    ) {
11778        let old_cursor_position = self.selections.newest_anchor().head();
11779        self.selections.change_with(cx, |s| {
11780            s.select_anchors(selections);
11781            if let Some(pending_selection) = pending_selection {
11782                s.set_pending(pending_selection, SelectMode::Character);
11783            } else {
11784                s.clear_pending();
11785            }
11786        });
11787        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11788    }
11789
11790    fn push_to_selection_history(&mut self) {
11791        self.selection_history.push(SelectionHistoryEntry {
11792            selections: self.selections.disjoint_anchors(),
11793            select_next_state: self.select_next_state.clone(),
11794            select_prev_state: self.select_prev_state.clone(),
11795            add_selections_state: self.add_selections_state.clone(),
11796        });
11797    }
11798
11799    pub fn transact(
11800        &mut self,
11801        window: &mut Window,
11802        cx: &mut Context<Self>,
11803        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11804    ) -> Option<TransactionId> {
11805        self.start_transaction_at(Instant::now(), window, cx);
11806        update(self, window, cx);
11807        self.end_transaction_at(Instant::now(), cx)
11808    }
11809
11810    pub fn start_transaction_at(
11811        &mut self,
11812        now: Instant,
11813        window: &mut Window,
11814        cx: &mut Context<Self>,
11815    ) {
11816        self.end_selection(window, cx);
11817        if let Some(tx_id) = self
11818            .buffer
11819            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11820        {
11821            self.selection_history
11822                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11823            cx.emit(EditorEvent::TransactionBegun {
11824                transaction_id: tx_id,
11825            })
11826        }
11827    }
11828
11829    pub fn end_transaction_at(
11830        &mut self,
11831        now: Instant,
11832        cx: &mut Context<Self>,
11833    ) -> Option<TransactionId> {
11834        if let Some(transaction_id) = self
11835            .buffer
11836            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11837        {
11838            if let Some((_, end_selections)) =
11839                self.selection_history.transaction_mut(transaction_id)
11840            {
11841                *end_selections = Some(self.selections.disjoint_anchors());
11842            } else {
11843                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11844            }
11845
11846            cx.emit(EditorEvent::Edited { transaction_id });
11847            Some(transaction_id)
11848        } else {
11849            None
11850        }
11851    }
11852
11853    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11854        if self.selection_mark_mode {
11855            self.change_selections(None, window, cx, |s| {
11856                s.move_with(|_, sel| {
11857                    sel.collapse_to(sel.head(), SelectionGoal::None);
11858                });
11859            })
11860        }
11861        self.selection_mark_mode = true;
11862        cx.notify();
11863    }
11864
11865    pub fn swap_selection_ends(
11866        &mut self,
11867        _: &actions::SwapSelectionEnds,
11868        window: &mut Window,
11869        cx: &mut Context<Self>,
11870    ) {
11871        self.change_selections(None, window, cx, |s| {
11872            s.move_with(|_, sel| {
11873                if sel.start != sel.end {
11874                    sel.reversed = !sel.reversed
11875                }
11876            });
11877        });
11878        self.request_autoscroll(Autoscroll::newest(), cx);
11879        cx.notify();
11880    }
11881
11882    pub fn toggle_fold(
11883        &mut self,
11884        _: &actions::ToggleFold,
11885        window: &mut Window,
11886        cx: &mut Context<Self>,
11887    ) {
11888        if self.is_singleton(cx) {
11889            let selection = self.selections.newest::<Point>(cx);
11890
11891            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11892            let range = if selection.is_empty() {
11893                let point = selection.head().to_display_point(&display_map);
11894                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11895                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11896                    .to_point(&display_map);
11897                start..end
11898            } else {
11899                selection.range()
11900            };
11901            if display_map.folds_in_range(range).next().is_some() {
11902                self.unfold_lines(&Default::default(), window, cx)
11903            } else {
11904                self.fold(&Default::default(), window, cx)
11905            }
11906        } else {
11907            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11908            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11909                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11910                .map(|(snapshot, _, _)| snapshot.remote_id())
11911                .collect();
11912
11913            for buffer_id in buffer_ids {
11914                if self.is_buffer_folded(buffer_id, cx) {
11915                    self.unfold_buffer(buffer_id, cx);
11916                } else {
11917                    self.fold_buffer(buffer_id, cx);
11918                }
11919            }
11920        }
11921    }
11922
11923    pub fn toggle_fold_recursive(
11924        &mut self,
11925        _: &actions::ToggleFoldRecursive,
11926        window: &mut Window,
11927        cx: &mut Context<Self>,
11928    ) {
11929        let selection = self.selections.newest::<Point>(cx);
11930
11931        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11932        let range = if selection.is_empty() {
11933            let point = selection.head().to_display_point(&display_map);
11934            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11935            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11936                .to_point(&display_map);
11937            start..end
11938        } else {
11939            selection.range()
11940        };
11941        if display_map.folds_in_range(range).next().is_some() {
11942            self.unfold_recursive(&Default::default(), window, cx)
11943        } else {
11944            self.fold_recursive(&Default::default(), window, cx)
11945        }
11946    }
11947
11948    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11949        if self.is_singleton(cx) {
11950            let mut to_fold = Vec::new();
11951            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11952            let selections = self.selections.all_adjusted(cx);
11953
11954            for selection in selections {
11955                let range = selection.range().sorted();
11956                let buffer_start_row = range.start.row;
11957
11958                if range.start.row != range.end.row {
11959                    let mut found = false;
11960                    let mut row = range.start.row;
11961                    while row <= range.end.row {
11962                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11963                        {
11964                            found = true;
11965                            row = crease.range().end.row + 1;
11966                            to_fold.push(crease);
11967                        } else {
11968                            row += 1
11969                        }
11970                    }
11971                    if found {
11972                        continue;
11973                    }
11974                }
11975
11976                for row in (0..=range.start.row).rev() {
11977                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11978                        if crease.range().end.row >= buffer_start_row {
11979                            to_fold.push(crease);
11980                            if row <= range.start.row {
11981                                break;
11982                            }
11983                        }
11984                    }
11985                }
11986            }
11987
11988            self.fold_creases(to_fold, true, window, cx);
11989        } else {
11990            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11991
11992            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11993                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11994                .map(|(snapshot, _, _)| snapshot.remote_id())
11995                .collect();
11996            for buffer_id in buffer_ids {
11997                self.fold_buffer(buffer_id, cx);
11998            }
11999        }
12000    }
12001
12002    fn fold_at_level(
12003        &mut self,
12004        fold_at: &FoldAtLevel,
12005        window: &mut Window,
12006        cx: &mut Context<Self>,
12007    ) {
12008        if !self.buffer.read(cx).is_singleton() {
12009            return;
12010        }
12011
12012        let fold_at_level = fold_at.0;
12013        let snapshot = self.buffer.read(cx).snapshot(cx);
12014        let mut to_fold = Vec::new();
12015        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12016
12017        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12018            while start_row < end_row {
12019                match self
12020                    .snapshot(window, cx)
12021                    .crease_for_buffer_row(MultiBufferRow(start_row))
12022                {
12023                    Some(crease) => {
12024                        let nested_start_row = crease.range().start.row + 1;
12025                        let nested_end_row = crease.range().end.row;
12026
12027                        if current_level < fold_at_level {
12028                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12029                        } else if current_level == fold_at_level {
12030                            to_fold.push(crease);
12031                        }
12032
12033                        start_row = nested_end_row + 1;
12034                    }
12035                    None => start_row += 1,
12036                }
12037            }
12038        }
12039
12040        self.fold_creases(to_fold, true, window, cx);
12041    }
12042
12043    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12044        if self.buffer.read(cx).is_singleton() {
12045            let mut fold_ranges = Vec::new();
12046            let snapshot = self.buffer.read(cx).snapshot(cx);
12047
12048            for row in 0..snapshot.max_row().0 {
12049                if let Some(foldable_range) = self
12050                    .snapshot(window, cx)
12051                    .crease_for_buffer_row(MultiBufferRow(row))
12052                {
12053                    fold_ranges.push(foldable_range);
12054                }
12055            }
12056
12057            self.fold_creases(fold_ranges, true, window, cx);
12058        } else {
12059            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12060                editor
12061                    .update_in(&mut cx, |editor, _, cx| {
12062                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12063                            editor.fold_buffer(buffer_id, cx);
12064                        }
12065                    })
12066                    .ok();
12067            });
12068        }
12069    }
12070
12071    pub fn fold_function_bodies(
12072        &mut self,
12073        _: &actions::FoldFunctionBodies,
12074        window: &mut Window,
12075        cx: &mut Context<Self>,
12076    ) {
12077        let snapshot = self.buffer.read(cx).snapshot(cx);
12078
12079        let ranges = snapshot
12080            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12081            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12082            .collect::<Vec<_>>();
12083
12084        let creases = ranges
12085            .into_iter()
12086            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12087            .collect();
12088
12089        self.fold_creases(creases, true, window, cx);
12090    }
12091
12092    pub fn fold_recursive(
12093        &mut self,
12094        _: &actions::FoldRecursive,
12095        window: &mut Window,
12096        cx: &mut Context<Self>,
12097    ) {
12098        let mut to_fold = Vec::new();
12099        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12100        let selections = self.selections.all_adjusted(cx);
12101
12102        for selection in selections {
12103            let range = selection.range().sorted();
12104            let buffer_start_row = range.start.row;
12105
12106            if range.start.row != range.end.row {
12107                let mut found = false;
12108                for row in range.start.row..=range.end.row {
12109                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12110                        found = true;
12111                        to_fold.push(crease);
12112                    }
12113                }
12114                if found {
12115                    continue;
12116                }
12117            }
12118
12119            for row in (0..=range.start.row).rev() {
12120                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12121                    if crease.range().end.row >= buffer_start_row {
12122                        to_fold.push(crease);
12123                    } else {
12124                        break;
12125                    }
12126                }
12127            }
12128        }
12129
12130        self.fold_creases(to_fold, true, window, cx);
12131    }
12132
12133    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12134        let buffer_row = fold_at.buffer_row;
12135        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12136
12137        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12138            let autoscroll = self
12139                .selections
12140                .all::<Point>(cx)
12141                .iter()
12142                .any(|selection| crease.range().overlaps(&selection.range()));
12143
12144            self.fold_creases(vec![crease], autoscroll, window, cx);
12145        }
12146    }
12147
12148    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12149        if self.is_singleton(cx) {
12150            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12151            let buffer = &display_map.buffer_snapshot;
12152            let selections = self.selections.all::<Point>(cx);
12153            let ranges = selections
12154                .iter()
12155                .map(|s| {
12156                    let range = s.display_range(&display_map).sorted();
12157                    let mut start = range.start.to_point(&display_map);
12158                    let mut end = range.end.to_point(&display_map);
12159                    start.column = 0;
12160                    end.column = buffer.line_len(MultiBufferRow(end.row));
12161                    start..end
12162                })
12163                .collect::<Vec<_>>();
12164
12165            self.unfold_ranges(&ranges, true, true, cx);
12166        } else {
12167            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12168            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12169                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12170                .map(|(snapshot, _, _)| snapshot.remote_id())
12171                .collect();
12172            for buffer_id in buffer_ids {
12173                self.unfold_buffer(buffer_id, cx);
12174            }
12175        }
12176    }
12177
12178    pub fn unfold_recursive(
12179        &mut self,
12180        _: &UnfoldRecursive,
12181        _window: &mut Window,
12182        cx: &mut Context<Self>,
12183    ) {
12184        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12185        let selections = self.selections.all::<Point>(cx);
12186        let ranges = selections
12187            .iter()
12188            .map(|s| {
12189                let mut range = s.display_range(&display_map).sorted();
12190                *range.start.column_mut() = 0;
12191                *range.end.column_mut() = display_map.line_len(range.end.row());
12192                let start = range.start.to_point(&display_map);
12193                let end = range.end.to_point(&display_map);
12194                start..end
12195            })
12196            .collect::<Vec<_>>();
12197
12198        self.unfold_ranges(&ranges, true, true, cx);
12199    }
12200
12201    pub fn unfold_at(
12202        &mut self,
12203        unfold_at: &UnfoldAt,
12204        _window: &mut Window,
12205        cx: &mut Context<Self>,
12206    ) {
12207        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12208
12209        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12210            ..Point::new(
12211                unfold_at.buffer_row.0,
12212                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12213            );
12214
12215        let autoscroll = self
12216            .selections
12217            .all::<Point>(cx)
12218            .iter()
12219            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12220
12221        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12222    }
12223
12224    pub fn unfold_all(
12225        &mut self,
12226        _: &actions::UnfoldAll,
12227        _window: &mut Window,
12228        cx: &mut Context<Self>,
12229    ) {
12230        if self.buffer.read(cx).is_singleton() {
12231            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12232            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12233        } else {
12234            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12235                editor
12236                    .update(&mut cx, |editor, cx| {
12237                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12238                            editor.unfold_buffer(buffer_id, cx);
12239                        }
12240                    })
12241                    .ok();
12242            });
12243        }
12244    }
12245
12246    pub fn fold_selected_ranges(
12247        &mut self,
12248        _: &FoldSelectedRanges,
12249        window: &mut Window,
12250        cx: &mut Context<Self>,
12251    ) {
12252        let selections = self.selections.all::<Point>(cx);
12253        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12254        let line_mode = self.selections.line_mode;
12255        let ranges = selections
12256            .into_iter()
12257            .map(|s| {
12258                if line_mode {
12259                    let start = Point::new(s.start.row, 0);
12260                    let end = Point::new(
12261                        s.end.row,
12262                        display_map
12263                            .buffer_snapshot
12264                            .line_len(MultiBufferRow(s.end.row)),
12265                    );
12266                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12267                } else {
12268                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12269                }
12270            })
12271            .collect::<Vec<_>>();
12272        self.fold_creases(ranges, true, window, cx);
12273    }
12274
12275    pub fn fold_ranges<T: ToOffset + Clone>(
12276        &mut self,
12277        ranges: Vec<Range<T>>,
12278        auto_scroll: bool,
12279        window: &mut Window,
12280        cx: &mut Context<Self>,
12281    ) {
12282        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12283        let ranges = ranges
12284            .into_iter()
12285            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12286            .collect::<Vec<_>>();
12287        self.fold_creases(ranges, auto_scroll, window, cx);
12288    }
12289
12290    pub fn fold_creases<T: ToOffset + Clone>(
12291        &mut self,
12292        creases: Vec<Crease<T>>,
12293        auto_scroll: bool,
12294        window: &mut Window,
12295        cx: &mut Context<Self>,
12296    ) {
12297        if creases.is_empty() {
12298            return;
12299        }
12300
12301        let mut buffers_affected = HashSet::default();
12302        let multi_buffer = self.buffer().read(cx);
12303        for crease in &creases {
12304            if let Some((_, buffer, _)) =
12305                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12306            {
12307                buffers_affected.insert(buffer.read(cx).remote_id());
12308            };
12309        }
12310
12311        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12312
12313        if auto_scroll {
12314            self.request_autoscroll(Autoscroll::fit(), cx);
12315        }
12316
12317        cx.notify();
12318
12319        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12320            // Clear diagnostics block when folding a range that contains it.
12321            let snapshot = self.snapshot(window, cx);
12322            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12323                drop(snapshot);
12324                self.active_diagnostics = Some(active_diagnostics);
12325                self.dismiss_diagnostics(cx);
12326            } else {
12327                self.active_diagnostics = Some(active_diagnostics);
12328            }
12329        }
12330
12331        self.scrollbar_marker_state.dirty = true;
12332    }
12333
12334    /// Removes any folds whose ranges intersect any of the given ranges.
12335    pub fn unfold_ranges<T: ToOffset + Clone>(
12336        &mut self,
12337        ranges: &[Range<T>],
12338        inclusive: bool,
12339        auto_scroll: bool,
12340        cx: &mut Context<Self>,
12341    ) {
12342        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12343            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12344        });
12345    }
12346
12347    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12348        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12349            return;
12350        }
12351        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12352        self.display_map
12353            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12354        cx.emit(EditorEvent::BufferFoldToggled {
12355            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12356            folded: true,
12357        });
12358        cx.notify();
12359    }
12360
12361    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12362        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12363            return;
12364        }
12365        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12366        self.display_map.update(cx, |display_map, cx| {
12367            display_map.unfold_buffer(buffer_id, cx);
12368        });
12369        cx.emit(EditorEvent::BufferFoldToggled {
12370            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12371            folded: false,
12372        });
12373        cx.notify();
12374    }
12375
12376    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12377        self.display_map.read(cx).is_buffer_folded(buffer)
12378    }
12379
12380    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12381        self.display_map.read(cx).folded_buffers()
12382    }
12383
12384    /// Removes any folds with the given ranges.
12385    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12386        &mut self,
12387        ranges: &[Range<T>],
12388        type_id: TypeId,
12389        auto_scroll: bool,
12390        cx: &mut Context<Self>,
12391    ) {
12392        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12393            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12394        });
12395    }
12396
12397    fn remove_folds_with<T: ToOffset + Clone>(
12398        &mut self,
12399        ranges: &[Range<T>],
12400        auto_scroll: bool,
12401        cx: &mut Context<Self>,
12402        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12403    ) {
12404        if ranges.is_empty() {
12405            return;
12406        }
12407
12408        let mut buffers_affected = HashSet::default();
12409        let multi_buffer = self.buffer().read(cx);
12410        for range in ranges {
12411            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12412                buffers_affected.insert(buffer.read(cx).remote_id());
12413            };
12414        }
12415
12416        self.display_map.update(cx, update);
12417
12418        if auto_scroll {
12419            self.request_autoscroll(Autoscroll::fit(), cx);
12420        }
12421
12422        cx.notify();
12423        self.scrollbar_marker_state.dirty = true;
12424        self.active_indent_guides_state.dirty = true;
12425    }
12426
12427    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12428        self.display_map.read(cx).fold_placeholder.clone()
12429    }
12430
12431    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12432        self.buffer.update(cx, |buffer, cx| {
12433            buffer.set_all_diff_hunks_expanded(cx);
12434        });
12435    }
12436
12437    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12438        self.distinguish_unstaged_diff_hunks = true;
12439    }
12440
12441    pub fn expand_all_diff_hunks(
12442        &mut self,
12443        _: &ExpandAllHunkDiffs,
12444        _window: &mut Window,
12445        cx: &mut Context<Self>,
12446    ) {
12447        self.buffer.update(cx, |buffer, cx| {
12448            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12449        });
12450    }
12451
12452    pub fn toggle_selected_diff_hunks(
12453        &mut self,
12454        _: &ToggleSelectedDiffHunks,
12455        _window: &mut Window,
12456        cx: &mut Context<Self>,
12457    ) {
12458        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12459        self.toggle_diff_hunks_in_ranges(ranges, cx);
12460    }
12461
12462    fn diff_hunks_in_ranges<'a>(
12463        &'a self,
12464        ranges: &'a [Range<Anchor>],
12465        buffer: &'a MultiBufferSnapshot,
12466    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12467        ranges.iter().flat_map(move |range| {
12468            let end_excerpt_id = range.end.excerpt_id;
12469            let range = range.to_point(buffer);
12470            let mut peek_end = range.end;
12471            if range.end.row < buffer.max_row().0 {
12472                peek_end = Point::new(range.end.row + 1, 0);
12473            }
12474            buffer
12475                .diff_hunks_in_range(range.start..peek_end)
12476                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12477        })
12478    }
12479
12480    pub fn has_stageable_diff_hunks_in_ranges(
12481        &self,
12482        ranges: &[Range<Anchor>],
12483        snapshot: &MultiBufferSnapshot,
12484    ) -> bool {
12485        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12486        hunks.any(|hunk| {
12487            log::debug!("considering {hunk:?}");
12488            hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk
12489        })
12490    }
12491
12492    pub fn toggle_staged_selected_diff_hunks(
12493        &mut self,
12494        _: &ToggleStagedSelectedDiffHunks,
12495        _window: &mut Window,
12496        cx: &mut Context<Self>,
12497    ) {
12498        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12499        self.stage_or_unstage_diff_hunks(&ranges, cx);
12500    }
12501
12502    pub fn stage_or_unstage_diff_hunks(
12503        &mut self,
12504        ranges: &[Range<Anchor>],
12505        cx: &mut Context<Self>,
12506    ) {
12507        let Some(project) = &self.project else {
12508            return;
12509        };
12510        let snapshot = self.buffer.read(cx).snapshot(cx);
12511        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12512
12513        let chunk_by = self
12514            .diff_hunks_in_ranges(&ranges, &snapshot)
12515            .chunk_by(|hunk| hunk.buffer_id);
12516        for (buffer_id, hunks) in &chunk_by {
12517            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12518                log::debug!("no buffer for id");
12519                continue;
12520            };
12521            let buffer = buffer.read(cx).snapshot();
12522            let Some((repo, path)) = project
12523                .read(cx)
12524                .repository_and_path_for_buffer_id(buffer_id, cx)
12525            else {
12526                log::debug!("no git repo for buffer id");
12527                continue;
12528            };
12529            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12530                log::debug!("no diff for buffer id");
12531                continue;
12532            };
12533            let Some(secondary_diff) = diff.secondary_diff() else {
12534                log::debug!("no secondary diff for buffer id");
12535                continue;
12536            };
12537
12538            let edits = diff.secondary_edits_for_stage_or_unstage(
12539                stage,
12540                hunks.map(|hunk| {
12541                    (
12542                        hunk.diff_base_byte_range.clone(),
12543                        hunk.secondary_diff_base_byte_range.clone(),
12544                        hunk.buffer_range.clone(),
12545                    )
12546                }),
12547                &buffer,
12548            );
12549
12550            let index_base = secondary_diff.base_text().map_or_else(
12551                || Rope::from(""),
12552                |snapshot| snapshot.text.as_rope().clone(),
12553            );
12554            let index_buffer = cx.new(|cx| {
12555                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12556            });
12557            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12558                index_buffer.edit(edits, None, cx);
12559                index_buffer.snapshot().as_rope().to_string()
12560            });
12561            let new_index_text = if new_index_text.is_empty()
12562                && (diff.is_single_insertion
12563                    || buffer
12564                        .file()
12565                        .map_or(false, |file| file.disk_state() == DiskState::New))
12566            {
12567                log::debug!("removing from index");
12568                None
12569            } else {
12570                Some(new_index_text)
12571            };
12572
12573            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12574        }
12575    }
12576
12577    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12578        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12579        self.buffer
12580            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12581    }
12582
12583    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12584        self.buffer.update(cx, |buffer, cx| {
12585            let ranges = vec![Anchor::min()..Anchor::max()];
12586            if !buffer.all_diff_hunks_expanded()
12587                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12588            {
12589                buffer.collapse_diff_hunks(ranges, cx);
12590                true
12591            } else {
12592                false
12593            }
12594        })
12595    }
12596
12597    fn toggle_diff_hunks_in_ranges(
12598        &mut self,
12599        ranges: Vec<Range<Anchor>>,
12600        cx: &mut Context<'_, Editor>,
12601    ) {
12602        self.buffer.update(cx, |buffer, cx| {
12603            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12604            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12605        })
12606    }
12607
12608    fn toggle_diff_hunks_in_ranges_narrow(
12609        &mut self,
12610        ranges: Vec<Range<Anchor>>,
12611        cx: &mut Context<'_, Editor>,
12612    ) {
12613        self.buffer.update(cx, |buffer, cx| {
12614            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12615            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12616        })
12617    }
12618
12619    pub(crate) fn apply_all_diff_hunks(
12620        &mut self,
12621        _: &ApplyAllDiffHunks,
12622        window: &mut Window,
12623        cx: &mut Context<Self>,
12624    ) {
12625        let buffers = self.buffer.read(cx).all_buffers();
12626        for branch_buffer in buffers {
12627            branch_buffer.update(cx, |branch_buffer, cx| {
12628                branch_buffer.merge_into_base(Vec::new(), cx);
12629            });
12630        }
12631
12632        if let Some(project) = self.project.clone() {
12633            self.save(true, project, window, cx).detach_and_log_err(cx);
12634        }
12635    }
12636
12637    pub(crate) fn apply_selected_diff_hunks(
12638        &mut self,
12639        _: &ApplyDiffHunk,
12640        window: &mut Window,
12641        cx: &mut Context<Self>,
12642    ) {
12643        let snapshot = self.snapshot(window, cx);
12644        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12645        let mut ranges_by_buffer = HashMap::default();
12646        self.transact(window, cx, |editor, _window, cx| {
12647            for hunk in hunks {
12648                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12649                    ranges_by_buffer
12650                        .entry(buffer.clone())
12651                        .or_insert_with(Vec::new)
12652                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12653                }
12654            }
12655
12656            for (buffer, ranges) in ranges_by_buffer {
12657                buffer.update(cx, |buffer, cx| {
12658                    buffer.merge_into_base(ranges, cx);
12659                });
12660            }
12661        });
12662
12663        if let Some(project) = self.project.clone() {
12664            self.save(true, project, window, cx).detach_and_log_err(cx);
12665        }
12666    }
12667
12668    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12669        if hovered != self.gutter_hovered {
12670            self.gutter_hovered = hovered;
12671            cx.notify();
12672        }
12673    }
12674
12675    pub fn insert_blocks(
12676        &mut self,
12677        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12678        autoscroll: Option<Autoscroll>,
12679        cx: &mut Context<Self>,
12680    ) -> Vec<CustomBlockId> {
12681        let blocks = self
12682            .display_map
12683            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12684        if let Some(autoscroll) = autoscroll {
12685            self.request_autoscroll(autoscroll, cx);
12686        }
12687        cx.notify();
12688        blocks
12689    }
12690
12691    pub fn resize_blocks(
12692        &mut self,
12693        heights: HashMap<CustomBlockId, u32>,
12694        autoscroll: Option<Autoscroll>,
12695        cx: &mut Context<Self>,
12696    ) {
12697        self.display_map
12698            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12699        if let Some(autoscroll) = autoscroll {
12700            self.request_autoscroll(autoscroll, cx);
12701        }
12702        cx.notify();
12703    }
12704
12705    pub fn replace_blocks(
12706        &mut self,
12707        renderers: HashMap<CustomBlockId, RenderBlock>,
12708        autoscroll: Option<Autoscroll>,
12709        cx: &mut Context<Self>,
12710    ) {
12711        self.display_map
12712            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12713        if let Some(autoscroll) = autoscroll {
12714            self.request_autoscroll(autoscroll, cx);
12715        }
12716        cx.notify();
12717    }
12718
12719    pub fn remove_blocks(
12720        &mut self,
12721        block_ids: HashSet<CustomBlockId>,
12722        autoscroll: Option<Autoscroll>,
12723        cx: &mut Context<Self>,
12724    ) {
12725        self.display_map.update(cx, |display_map, cx| {
12726            display_map.remove_blocks(block_ids, cx)
12727        });
12728        if let Some(autoscroll) = autoscroll {
12729            self.request_autoscroll(autoscroll, cx);
12730        }
12731        cx.notify();
12732    }
12733
12734    pub fn row_for_block(
12735        &self,
12736        block_id: CustomBlockId,
12737        cx: &mut Context<Self>,
12738    ) -> Option<DisplayRow> {
12739        self.display_map
12740            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12741    }
12742
12743    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12744        self.focused_block = Some(focused_block);
12745    }
12746
12747    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12748        self.focused_block.take()
12749    }
12750
12751    pub fn insert_creases(
12752        &mut self,
12753        creases: impl IntoIterator<Item = Crease<Anchor>>,
12754        cx: &mut Context<Self>,
12755    ) -> Vec<CreaseId> {
12756        self.display_map
12757            .update(cx, |map, cx| map.insert_creases(creases, cx))
12758    }
12759
12760    pub fn remove_creases(
12761        &mut self,
12762        ids: impl IntoIterator<Item = CreaseId>,
12763        cx: &mut Context<Self>,
12764    ) {
12765        self.display_map
12766            .update(cx, |map, cx| map.remove_creases(ids, cx));
12767    }
12768
12769    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12770        self.display_map
12771            .update(cx, |map, cx| map.snapshot(cx))
12772            .longest_row()
12773    }
12774
12775    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12776        self.display_map
12777            .update(cx, |map, cx| map.snapshot(cx))
12778            .max_point()
12779    }
12780
12781    pub fn text(&self, cx: &App) -> String {
12782        self.buffer.read(cx).read(cx).text()
12783    }
12784
12785    pub fn is_empty(&self, cx: &App) -> bool {
12786        self.buffer.read(cx).read(cx).is_empty()
12787    }
12788
12789    pub fn text_option(&self, cx: &App) -> Option<String> {
12790        let text = self.text(cx);
12791        let text = text.trim();
12792
12793        if text.is_empty() {
12794            return None;
12795        }
12796
12797        Some(text.to_string())
12798    }
12799
12800    pub fn set_text(
12801        &mut self,
12802        text: impl Into<Arc<str>>,
12803        window: &mut Window,
12804        cx: &mut Context<Self>,
12805    ) {
12806        self.transact(window, cx, |this, _, cx| {
12807            this.buffer
12808                .read(cx)
12809                .as_singleton()
12810                .expect("you can only call set_text on editors for singleton buffers")
12811                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12812        });
12813    }
12814
12815    pub fn display_text(&self, cx: &mut App) -> String {
12816        self.display_map
12817            .update(cx, |map, cx| map.snapshot(cx))
12818            .text()
12819    }
12820
12821    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12822        let mut wrap_guides = smallvec::smallvec![];
12823
12824        if self.show_wrap_guides == Some(false) {
12825            return wrap_guides;
12826        }
12827
12828        let settings = self.buffer.read(cx).settings_at(0, cx);
12829        if settings.show_wrap_guides {
12830            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12831                wrap_guides.push((soft_wrap as usize, true));
12832            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12833                wrap_guides.push((soft_wrap as usize, true));
12834            }
12835            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12836        }
12837
12838        wrap_guides
12839    }
12840
12841    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12842        let settings = self.buffer.read(cx).settings_at(0, cx);
12843        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12844        match mode {
12845            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12846                SoftWrap::None
12847            }
12848            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12849            language_settings::SoftWrap::PreferredLineLength => {
12850                SoftWrap::Column(settings.preferred_line_length)
12851            }
12852            language_settings::SoftWrap::Bounded => {
12853                SoftWrap::Bounded(settings.preferred_line_length)
12854            }
12855        }
12856    }
12857
12858    pub fn set_soft_wrap_mode(
12859        &mut self,
12860        mode: language_settings::SoftWrap,
12861
12862        cx: &mut Context<Self>,
12863    ) {
12864        self.soft_wrap_mode_override = Some(mode);
12865        cx.notify();
12866    }
12867
12868    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12869        self.text_style_refinement = Some(style);
12870    }
12871
12872    /// called by the Element so we know what style we were most recently rendered with.
12873    pub(crate) fn set_style(
12874        &mut self,
12875        style: EditorStyle,
12876        window: &mut Window,
12877        cx: &mut Context<Self>,
12878    ) {
12879        let rem_size = window.rem_size();
12880        self.display_map.update(cx, |map, cx| {
12881            map.set_font(
12882                style.text.font(),
12883                style.text.font_size.to_pixels(rem_size),
12884                cx,
12885            )
12886        });
12887        self.style = Some(style);
12888    }
12889
12890    pub fn style(&self) -> Option<&EditorStyle> {
12891        self.style.as_ref()
12892    }
12893
12894    // Called by the element. This method is not designed to be called outside of the editor
12895    // element's layout code because it does not notify when rewrapping is computed synchronously.
12896    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12897        self.display_map
12898            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12899    }
12900
12901    pub fn set_soft_wrap(&mut self) {
12902        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12903    }
12904
12905    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12906        if self.soft_wrap_mode_override.is_some() {
12907            self.soft_wrap_mode_override.take();
12908        } else {
12909            let soft_wrap = match self.soft_wrap_mode(cx) {
12910                SoftWrap::GitDiff => return,
12911                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12912                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12913                    language_settings::SoftWrap::None
12914                }
12915            };
12916            self.soft_wrap_mode_override = Some(soft_wrap);
12917        }
12918        cx.notify();
12919    }
12920
12921    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12922        let Some(workspace) = self.workspace() else {
12923            return;
12924        };
12925        let fs = workspace.read(cx).app_state().fs.clone();
12926        let current_show = TabBarSettings::get_global(cx).show;
12927        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12928            setting.show = Some(!current_show);
12929        });
12930    }
12931
12932    pub fn toggle_indent_guides(
12933        &mut self,
12934        _: &ToggleIndentGuides,
12935        _: &mut Window,
12936        cx: &mut Context<Self>,
12937    ) {
12938        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12939            self.buffer
12940                .read(cx)
12941                .settings_at(0, cx)
12942                .indent_guides
12943                .enabled
12944        });
12945        self.show_indent_guides = Some(!currently_enabled);
12946        cx.notify();
12947    }
12948
12949    fn should_show_indent_guides(&self) -> Option<bool> {
12950        self.show_indent_guides
12951    }
12952
12953    pub fn toggle_line_numbers(
12954        &mut self,
12955        _: &ToggleLineNumbers,
12956        _: &mut Window,
12957        cx: &mut Context<Self>,
12958    ) {
12959        let mut editor_settings = EditorSettings::get_global(cx).clone();
12960        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12961        EditorSettings::override_global(editor_settings, cx);
12962    }
12963
12964    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12965        self.use_relative_line_numbers
12966            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12967    }
12968
12969    pub fn toggle_relative_line_numbers(
12970        &mut self,
12971        _: &ToggleRelativeLineNumbers,
12972        _: &mut Window,
12973        cx: &mut Context<Self>,
12974    ) {
12975        let is_relative = self.should_use_relative_line_numbers(cx);
12976        self.set_relative_line_number(Some(!is_relative), cx)
12977    }
12978
12979    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12980        self.use_relative_line_numbers = is_relative;
12981        cx.notify();
12982    }
12983
12984    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12985        self.show_gutter = show_gutter;
12986        cx.notify();
12987    }
12988
12989    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12990        self.show_scrollbars = show_scrollbars;
12991        cx.notify();
12992    }
12993
12994    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12995        self.show_line_numbers = Some(show_line_numbers);
12996        cx.notify();
12997    }
12998
12999    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13000        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13001        cx.notify();
13002    }
13003
13004    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13005        self.show_code_actions = Some(show_code_actions);
13006        cx.notify();
13007    }
13008
13009    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13010        self.show_runnables = Some(show_runnables);
13011        cx.notify();
13012    }
13013
13014    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13015        if self.display_map.read(cx).masked != masked {
13016            self.display_map.update(cx, |map, _| map.masked = masked);
13017        }
13018        cx.notify()
13019    }
13020
13021    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13022        self.show_wrap_guides = Some(show_wrap_guides);
13023        cx.notify();
13024    }
13025
13026    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13027        self.show_indent_guides = Some(show_indent_guides);
13028        cx.notify();
13029    }
13030
13031    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13032        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13033            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13034                if let Some(dir) = file.abs_path(cx).parent() {
13035                    return Some(dir.to_owned());
13036                }
13037            }
13038
13039            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13040                return Some(project_path.path.to_path_buf());
13041            }
13042        }
13043
13044        None
13045    }
13046
13047    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13048        self.active_excerpt(cx)?
13049            .1
13050            .read(cx)
13051            .file()
13052            .and_then(|f| f.as_local())
13053    }
13054
13055    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13056        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13057            let buffer = buffer.read(cx);
13058            if let Some(project_path) = buffer.project_path(cx) {
13059                let project = self.project.as_ref()?.read(cx);
13060                project.absolute_path(&project_path, cx)
13061            } else {
13062                buffer
13063                    .file()
13064                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13065            }
13066        })
13067    }
13068
13069    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13070        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13071            let project_path = buffer.read(cx).project_path(cx)?;
13072            let project = self.project.as_ref()?.read(cx);
13073            let entry = project.entry_for_path(&project_path, cx)?;
13074            let path = entry.path.to_path_buf();
13075            Some(path)
13076        })
13077    }
13078
13079    pub fn reveal_in_finder(
13080        &mut self,
13081        _: &RevealInFileManager,
13082        _window: &mut Window,
13083        cx: &mut Context<Self>,
13084    ) {
13085        if let Some(target) = self.target_file(cx) {
13086            cx.reveal_path(&target.abs_path(cx));
13087        }
13088    }
13089
13090    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
13091        if let Some(path) = self.target_file_abs_path(cx) {
13092            if let Some(path) = path.to_str() {
13093                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13094            }
13095        }
13096    }
13097
13098    pub fn copy_relative_path(
13099        &mut self,
13100        _: &CopyRelativePath,
13101        _window: &mut Window,
13102        cx: &mut Context<Self>,
13103    ) {
13104        if let Some(path) = self.target_file_path(cx) {
13105            if let Some(path) = path.to_str() {
13106                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13107            }
13108        }
13109    }
13110
13111    pub fn copy_file_name_without_extension(
13112        &mut self,
13113        _: &CopyFileNameWithoutExtension,
13114        _: &mut Window,
13115        cx: &mut Context<Self>,
13116    ) {
13117        if let Some(file) = self.target_file(cx) {
13118            if let Some(file_stem) = file.path().file_stem() {
13119                if let Some(name) = file_stem.to_str() {
13120                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13121                }
13122            }
13123        }
13124    }
13125
13126    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13127        if let Some(file) = self.target_file(cx) {
13128            if let Some(file_name) = file.path().file_name() {
13129                if let Some(name) = file_name.to_str() {
13130                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13131                }
13132            }
13133        }
13134    }
13135
13136    pub fn toggle_git_blame(
13137        &mut self,
13138        _: &ToggleGitBlame,
13139        window: &mut Window,
13140        cx: &mut Context<Self>,
13141    ) {
13142        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13143
13144        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13145            self.start_git_blame(true, window, cx);
13146        }
13147
13148        cx.notify();
13149    }
13150
13151    pub fn toggle_git_blame_inline(
13152        &mut self,
13153        _: &ToggleGitBlameInline,
13154        window: &mut Window,
13155        cx: &mut Context<Self>,
13156    ) {
13157        self.toggle_git_blame_inline_internal(true, window, cx);
13158        cx.notify();
13159    }
13160
13161    pub fn git_blame_inline_enabled(&self) -> bool {
13162        self.git_blame_inline_enabled
13163    }
13164
13165    pub fn toggle_selection_menu(
13166        &mut self,
13167        _: &ToggleSelectionMenu,
13168        _: &mut Window,
13169        cx: &mut Context<Self>,
13170    ) {
13171        self.show_selection_menu = self
13172            .show_selection_menu
13173            .map(|show_selections_menu| !show_selections_menu)
13174            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13175
13176        cx.notify();
13177    }
13178
13179    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13180        self.show_selection_menu
13181            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13182    }
13183
13184    fn start_git_blame(
13185        &mut self,
13186        user_triggered: bool,
13187        window: &mut Window,
13188        cx: &mut Context<Self>,
13189    ) {
13190        if let Some(project) = self.project.as_ref() {
13191            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13192                return;
13193            };
13194
13195            if buffer.read(cx).file().is_none() {
13196                return;
13197            }
13198
13199            let focused = self.focus_handle(cx).contains_focused(window, cx);
13200
13201            let project = project.clone();
13202            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13203            self.blame_subscription =
13204                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13205            self.blame = Some(blame);
13206        }
13207    }
13208
13209    fn toggle_git_blame_inline_internal(
13210        &mut self,
13211        user_triggered: bool,
13212        window: &mut Window,
13213        cx: &mut Context<Self>,
13214    ) {
13215        if self.git_blame_inline_enabled {
13216            self.git_blame_inline_enabled = false;
13217            self.show_git_blame_inline = false;
13218            self.show_git_blame_inline_delay_task.take();
13219        } else {
13220            self.git_blame_inline_enabled = true;
13221            self.start_git_blame_inline(user_triggered, window, cx);
13222        }
13223
13224        cx.notify();
13225    }
13226
13227    fn start_git_blame_inline(
13228        &mut self,
13229        user_triggered: bool,
13230        window: &mut Window,
13231        cx: &mut Context<Self>,
13232    ) {
13233        self.start_git_blame(user_triggered, window, cx);
13234
13235        if ProjectSettings::get_global(cx)
13236            .git
13237            .inline_blame_delay()
13238            .is_some()
13239        {
13240            self.start_inline_blame_timer(window, cx);
13241        } else {
13242            self.show_git_blame_inline = true
13243        }
13244    }
13245
13246    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13247        self.blame.as_ref()
13248    }
13249
13250    pub fn show_git_blame_gutter(&self) -> bool {
13251        self.show_git_blame_gutter
13252    }
13253
13254    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13255        self.show_git_blame_gutter && self.has_blame_entries(cx)
13256    }
13257
13258    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13259        self.show_git_blame_inline
13260            && self.focus_handle.is_focused(window)
13261            && !self.newest_selection_head_on_empty_line(cx)
13262            && self.has_blame_entries(cx)
13263    }
13264
13265    fn has_blame_entries(&self, cx: &App) -> bool {
13266        self.blame()
13267            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13268    }
13269
13270    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13271        let cursor_anchor = self.selections.newest_anchor().head();
13272
13273        let snapshot = self.buffer.read(cx).snapshot(cx);
13274        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13275
13276        snapshot.line_len(buffer_row) == 0
13277    }
13278
13279    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13280        let buffer_and_selection = maybe!({
13281            let selection = self.selections.newest::<Point>(cx);
13282            let selection_range = selection.range();
13283
13284            let multi_buffer = self.buffer().read(cx);
13285            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13286            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13287
13288            let (buffer, range, _) = if selection.reversed {
13289                buffer_ranges.first()
13290            } else {
13291                buffer_ranges.last()
13292            }?;
13293
13294            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13295                ..text::ToPoint::to_point(&range.end, &buffer).row;
13296            Some((
13297                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13298                selection,
13299            ))
13300        });
13301
13302        let Some((buffer, selection)) = buffer_and_selection else {
13303            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13304        };
13305
13306        let Some(project) = self.project.as_ref() else {
13307            return Task::ready(Err(anyhow!("editor does not have project")));
13308        };
13309
13310        project.update(cx, |project, cx| {
13311            project.get_permalink_to_line(&buffer, selection, cx)
13312        })
13313    }
13314
13315    pub fn copy_permalink_to_line(
13316        &mut self,
13317        _: &CopyPermalinkToLine,
13318        window: &mut Window,
13319        cx: &mut Context<Self>,
13320    ) {
13321        let permalink_task = self.get_permalink_to_line(cx);
13322        let workspace = self.workspace();
13323
13324        cx.spawn_in(window, |_, mut cx| async move {
13325            match permalink_task.await {
13326                Ok(permalink) => {
13327                    cx.update(|_, cx| {
13328                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13329                    })
13330                    .ok();
13331                }
13332                Err(err) => {
13333                    let message = format!("Failed to copy permalink: {err}");
13334
13335                    Err::<(), anyhow::Error>(err).log_err();
13336
13337                    if let Some(workspace) = workspace {
13338                        workspace
13339                            .update_in(&mut cx, |workspace, _, cx| {
13340                                struct CopyPermalinkToLine;
13341
13342                                workspace.show_toast(
13343                                    Toast::new(
13344                                        NotificationId::unique::<CopyPermalinkToLine>(),
13345                                        message,
13346                                    ),
13347                                    cx,
13348                                )
13349                            })
13350                            .ok();
13351                    }
13352                }
13353            }
13354        })
13355        .detach();
13356    }
13357
13358    pub fn copy_file_location(
13359        &mut self,
13360        _: &CopyFileLocation,
13361        _: &mut Window,
13362        cx: &mut Context<Self>,
13363    ) {
13364        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13365        if let Some(file) = self.target_file(cx) {
13366            if let Some(path) = file.path().to_str() {
13367                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13368            }
13369        }
13370    }
13371
13372    pub fn open_permalink_to_line(
13373        &mut self,
13374        _: &OpenPermalinkToLine,
13375        window: &mut Window,
13376        cx: &mut Context<Self>,
13377    ) {
13378        let permalink_task = self.get_permalink_to_line(cx);
13379        let workspace = self.workspace();
13380
13381        cx.spawn_in(window, |_, mut cx| async move {
13382            match permalink_task.await {
13383                Ok(permalink) => {
13384                    cx.update(|_, cx| {
13385                        cx.open_url(permalink.as_ref());
13386                    })
13387                    .ok();
13388                }
13389                Err(err) => {
13390                    let message = format!("Failed to open permalink: {err}");
13391
13392                    Err::<(), anyhow::Error>(err).log_err();
13393
13394                    if let Some(workspace) = workspace {
13395                        workspace
13396                            .update(&mut cx, |workspace, cx| {
13397                                struct OpenPermalinkToLine;
13398
13399                                workspace.show_toast(
13400                                    Toast::new(
13401                                        NotificationId::unique::<OpenPermalinkToLine>(),
13402                                        message,
13403                                    ),
13404                                    cx,
13405                                )
13406                            })
13407                            .ok();
13408                    }
13409                }
13410            }
13411        })
13412        .detach();
13413    }
13414
13415    pub fn insert_uuid_v4(
13416        &mut self,
13417        _: &InsertUuidV4,
13418        window: &mut Window,
13419        cx: &mut Context<Self>,
13420    ) {
13421        self.insert_uuid(UuidVersion::V4, window, cx);
13422    }
13423
13424    pub fn insert_uuid_v7(
13425        &mut self,
13426        _: &InsertUuidV7,
13427        window: &mut Window,
13428        cx: &mut Context<Self>,
13429    ) {
13430        self.insert_uuid(UuidVersion::V7, window, cx);
13431    }
13432
13433    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13434        self.transact(window, cx, |this, window, cx| {
13435            let edits = this
13436                .selections
13437                .all::<Point>(cx)
13438                .into_iter()
13439                .map(|selection| {
13440                    let uuid = match version {
13441                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13442                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13443                    };
13444
13445                    (selection.range(), uuid.to_string())
13446                });
13447            this.edit(edits, cx);
13448            this.refresh_inline_completion(true, false, window, cx);
13449        });
13450    }
13451
13452    pub fn open_selections_in_multibuffer(
13453        &mut self,
13454        _: &OpenSelectionsInMultibuffer,
13455        window: &mut Window,
13456        cx: &mut Context<Self>,
13457    ) {
13458        let multibuffer = self.buffer.read(cx);
13459
13460        let Some(buffer) = multibuffer.as_singleton() else {
13461            return;
13462        };
13463
13464        let Some(workspace) = self.workspace() else {
13465            return;
13466        };
13467
13468        let locations = self
13469            .selections
13470            .disjoint_anchors()
13471            .iter()
13472            .map(|range| Location {
13473                buffer: buffer.clone(),
13474                range: range.start.text_anchor..range.end.text_anchor,
13475            })
13476            .collect::<Vec<_>>();
13477
13478        let title = multibuffer.title(cx).to_string();
13479
13480        cx.spawn_in(window, |_, mut cx| async move {
13481            workspace.update_in(&mut cx, |workspace, window, cx| {
13482                Self::open_locations_in_multibuffer(
13483                    workspace,
13484                    locations,
13485                    format!("Selections for '{title}'"),
13486                    false,
13487                    MultibufferSelectionMode::All,
13488                    window,
13489                    cx,
13490                );
13491            })
13492        })
13493        .detach();
13494    }
13495
13496    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13497    /// last highlight added will be used.
13498    ///
13499    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13500    pub fn highlight_rows<T: 'static>(
13501        &mut self,
13502        range: Range<Anchor>,
13503        color: Hsla,
13504        should_autoscroll: bool,
13505        cx: &mut Context<Self>,
13506    ) {
13507        let snapshot = self.buffer().read(cx).snapshot(cx);
13508        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13509        let ix = row_highlights.binary_search_by(|highlight| {
13510            Ordering::Equal
13511                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13512                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13513        });
13514
13515        if let Err(mut ix) = ix {
13516            let index = post_inc(&mut self.highlight_order);
13517
13518            // If this range intersects with the preceding highlight, then merge it with
13519            // the preceding highlight. Otherwise insert a new highlight.
13520            let mut merged = false;
13521            if ix > 0 {
13522                let prev_highlight = &mut row_highlights[ix - 1];
13523                if prev_highlight
13524                    .range
13525                    .end
13526                    .cmp(&range.start, &snapshot)
13527                    .is_ge()
13528                {
13529                    ix -= 1;
13530                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13531                        prev_highlight.range.end = range.end;
13532                    }
13533                    merged = true;
13534                    prev_highlight.index = index;
13535                    prev_highlight.color = color;
13536                    prev_highlight.should_autoscroll = should_autoscroll;
13537                }
13538            }
13539
13540            if !merged {
13541                row_highlights.insert(
13542                    ix,
13543                    RowHighlight {
13544                        range: range.clone(),
13545                        index,
13546                        color,
13547                        should_autoscroll,
13548                    },
13549                );
13550            }
13551
13552            // If any of the following highlights intersect with this one, merge them.
13553            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13554                let highlight = &row_highlights[ix];
13555                if next_highlight
13556                    .range
13557                    .start
13558                    .cmp(&highlight.range.end, &snapshot)
13559                    .is_le()
13560                {
13561                    if next_highlight
13562                        .range
13563                        .end
13564                        .cmp(&highlight.range.end, &snapshot)
13565                        .is_gt()
13566                    {
13567                        row_highlights[ix].range.end = next_highlight.range.end;
13568                    }
13569                    row_highlights.remove(ix + 1);
13570                } else {
13571                    break;
13572                }
13573            }
13574        }
13575    }
13576
13577    /// Remove any highlighted row ranges of the given type that intersect the
13578    /// given ranges.
13579    pub fn remove_highlighted_rows<T: 'static>(
13580        &mut self,
13581        ranges_to_remove: Vec<Range<Anchor>>,
13582        cx: &mut Context<Self>,
13583    ) {
13584        let snapshot = self.buffer().read(cx).snapshot(cx);
13585        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13586        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13587        row_highlights.retain(|highlight| {
13588            while let Some(range_to_remove) = ranges_to_remove.peek() {
13589                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13590                    Ordering::Less | Ordering::Equal => {
13591                        ranges_to_remove.next();
13592                    }
13593                    Ordering::Greater => {
13594                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13595                            Ordering::Less | Ordering::Equal => {
13596                                return false;
13597                            }
13598                            Ordering::Greater => break,
13599                        }
13600                    }
13601                }
13602            }
13603
13604            true
13605        })
13606    }
13607
13608    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13609    pub fn clear_row_highlights<T: 'static>(&mut self) {
13610        self.highlighted_rows.remove(&TypeId::of::<T>());
13611    }
13612
13613    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13614    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13615        self.highlighted_rows
13616            .get(&TypeId::of::<T>())
13617            .map_or(&[] as &[_], |vec| vec.as_slice())
13618            .iter()
13619            .map(|highlight| (highlight.range.clone(), highlight.color))
13620    }
13621
13622    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13623    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13624    /// Allows to ignore certain kinds of highlights.
13625    pub fn highlighted_display_rows(
13626        &self,
13627        window: &mut Window,
13628        cx: &mut App,
13629    ) -> BTreeMap<DisplayRow, Background> {
13630        let snapshot = self.snapshot(window, cx);
13631        let mut used_highlight_orders = HashMap::default();
13632        self.highlighted_rows
13633            .iter()
13634            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13635            .fold(
13636                BTreeMap::<DisplayRow, Background>::new(),
13637                |mut unique_rows, highlight| {
13638                    let start = highlight.range.start.to_display_point(&snapshot);
13639                    let end = highlight.range.end.to_display_point(&snapshot);
13640                    let start_row = start.row().0;
13641                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13642                        && end.column() == 0
13643                    {
13644                        end.row().0.saturating_sub(1)
13645                    } else {
13646                        end.row().0
13647                    };
13648                    for row in start_row..=end_row {
13649                        let used_index =
13650                            used_highlight_orders.entry(row).or_insert(highlight.index);
13651                        if highlight.index >= *used_index {
13652                            *used_index = highlight.index;
13653                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13654                        }
13655                    }
13656                    unique_rows
13657                },
13658            )
13659    }
13660
13661    pub fn highlighted_display_row_for_autoscroll(
13662        &self,
13663        snapshot: &DisplaySnapshot,
13664    ) -> Option<DisplayRow> {
13665        self.highlighted_rows
13666            .values()
13667            .flat_map(|highlighted_rows| highlighted_rows.iter())
13668            .filter_map(|highlight| {
13669                if highlight.should_autoscroll {
13670                    Some(highlight.range.start.to_display_point(snapshot).row())
13671                } else {
13672                    None
13673                }
13674            })
13675            .min()
13676    }
13677
13678    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13679        self.highlight_background::<SearchWithinRange>(
13680            ranges,
13681            |colors| colors.editor_document_highlight_read_background,
13682            cx,
13683        )
13684    }
13685
13686    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13687        self.breadcrumb_header = Some(new_header);
13688    }
13689
13690    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13691        self.clear_background_highlights::<SearchWithinRange>(cx);
13692    }
13693
13694    pub fn highlight_background<T: 'static>(
13695        &mut self,
13696        ranges: &[Range<Anchor>],
13697        color_fetcher: fn(&ThemeColors) -> Hsla,
13698        cx: &mut Context<Self>,
13699    ) {
13700        self.background_highlights
13701            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13702        self.scrollbar_marker_state.dirty = true;
13703        cx.notify();
13704    }
13705
13706    pub fn clear_background_highlights<T: 'static>(
13707        &mut self,
13708        cx: &mut Context<Self>,
13709    ) -> Option<BackgroundHighlight> {
13710        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13711        if !text_highlights.1.is_empty() {
13712            self.scrollbar_marker_state.dirty = true;
13713            cx.notify();
13714        }
13715        Some(text_highlights)
13716    }
13717
13718    pub fn highlight_gutter<T: 'static>(
13719        &mut self,
13720        ranges: &[Range<Anchor>],
13721        color_fetcher: fn(&App) -> Hsla,
13722        cx: &mut Context<Self>,
13723    ) {
13724        self.gutter_highlights
13725            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13726        cx.notify();
13727    }
13728
13729    pub fn clear_gutter_highlights<T: 'static>(
13730        &mut self,
13731        cx: &mut Context<Self>,
13732    ) -> Option<GutterHighlight> {
13733        cx.notify();
13734        self.gutter_highlights.remove(&TypeId::of::<T>())
13735    }
13736
13737    #[cfg(feature = "test-support")]
13738    pub fn all_text_background_highlights(
13739        &self,
13740        window: &mut Window,
13741        cx: &mut Context<Self>,
13742    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13743        let snapshot = self.snapshot(window, cx);
13744        let buffer = &snapshot.buffer_snapshot;
13745        let start = buffer.anchor_before(0);
13746        let end = buffer.anchor_after(buffer.len());
13747        let theme = cx.theme().colors();
13748        self.background_highlights_in_range(start..end, &snapshot, theme)
13749    }
13750
13751    #[cfg(feature = "test-support")]
13752    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13753        let snapshot = self.buffer().read(cx).snapshot(cx);
13754
13755        let highlights = self
13756            .background_highlights
13757            .get(&TypeId::of::<items::BufferSearchHighlights>());
13758
13759        if let Some((_color, ranges)) = highlights {
13760            ranges
13761                .iter()
13762                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13763                .collect_vec()
13764        } else {
13765            vec![]
13766        }
13767    }
13768
13769    fn document_highlights_for_position<'a>(
13770        &'a self,
13771        position: Anchor,
13772        buffer: &'a MultiBufferSnapshot,
13773    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13774        let read_highlights = self
13775            .background_highlights
13776            .get(&TypeId::of::<DocumentHighlightRead>())
13777            .map(|h| &h.1);
13778        let write_highlights = self
13779            .background_highlights
13780            .get(&TypeId::of::<DocumentHighlightWrite>())
13781            .map(|h| &h.1);
13782        let left_position = position.bias_left(buffer);
13783        let right_position = position.bias_right(buffer);
13784        read_highlights
13785            .into_iter()
13786            .chain(write_highlights)
13787            .flat_map(move |ranges| {
13788                let start_ix = match ranges.binary_search_by(|probe| {
13789                    let cmp = probe.end.cmp(&left_position, buffer);
13790                    if cmp.is_ge() {
13791                        Ordering::Greater
13792                    } else {
13793                        Ordering::Less
13794                    }
13795                }) {
13796                    Ok(i) | Err(i) => i,
13797                };
13798
13799                ranges[start_ix..]
13800                    .iter()
13801                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13802            })
13803    }
13804
13805    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13806        self.background_highlights
13807            .get(&TypeId::of::<T>())
13808            .map_or(false, |(_, highlights)| !highlights.is_empty())
13809    }
13810
13811    pub fn background_highlights_in_range(
13812        &self,
13813        search_range: Range<Anchor>,
13814        display_snapshot: &DisplaySnapshot,
13815        theme: &ThemeColors,
13816    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13817        let mut results = Vec::new();
13818        for (color_fetcher, ranges) in self.background_highlights.values() {
13819            let color = color_fetcher(theme);
13820            let start_ix = match ranges.binary_search_by(|probe| {
13821                let cmp = probe
13822                    .end
13823                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13824                if cmp.is_gt() {
13825                    Ordering::Greater
13826                } else {
13827                    Ordering::Less
13828                }
13829            }) {
13830                Ok(i) | Err(i) => i,
13831            };
13832            for range in &ranges[start_ix..] {
13833                if range
13834                    .start
13835                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13836                    .is_ge()
13837                {
13838                    break;
13839                }
13840
13841                let start = range.start.to_display_point(display_snapshot);
13842                let end = range.end.to_display_point(display_snapshot);
13843                results.push((start..end, color))
13844            }
13845        }
13846        results
13847    }
13848
13849    pub fn background_highlight_row_ranges<T: 'static>(
13850        &self,
13851        search_range: Range<Anchor>,
13852        display_snapshot: &DisplaySnapshot,
13853        count: usize,
13854    ) -> Vec<RangeInclusive<DisplayPoint>> {
13855        let mut results = Vec::new();
13856        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13857            return vec![];
13858        };
13859
13860        let start_ix = match ranges.binary_search_by(|probe| {
13861            let cmp = probe
13862                .end
13863                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13864            if cmp.is_gt() {
13865                Ordering::Greater
13866            } else {
13867                Ordering::Less
13868            }
13869        }) {
13870            Ok(i) | Err(i) => i,
13871        };
13872        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13873            if let (Some(start_display), Some(end_display)) = (start, end) {
13874                results.push(
13875                    start_display.to_display_point(display_snapshot)
13876                        ..=end_display.to_display_point(display_snapshot),
13877                );
13878            }
13879        };
13880        let mut start_row: Option<Point> = None;
13881        let mut end_row: Option<Point> = None;
13882        if ranges.len() > count {
13883            return Vec::new();
13884        }
13885        for range in &ranges[start_ix..] {
13886            if range
13887                .start
13888                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13889                .is_ge()
13890            {
13891                break;
13892            }
13893            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13894            if let Some(current_row) = &end_row {
13895                if end.row == current_row.row {
13896                    continue;
13897                }
13898            }
13899            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13900            if start_row.is_none() {
13901                assert_eq!(end_row, None);
13902                start_row = Some(start);
13903                end_row = Some(end);
13904                continue;
13905            }
13906            if let Some(current_end) = end_row.as_mut() {
13907                if start.row > current_end.row + 1 {
13908                    push_region(start_row, end_row);
13909                    start_row = Some(start);
13910                    end_row = Some(end);
13911                } else {
13912                    // Merge two hunks.
13913                    *current_end = end;
13914                }
13915            } else {
13916                unreachable!();
13917            }
13918        }
13919        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13920        push_region(start_row, end_row);
13921        results
13922    }
13923
13924    pub fn gutter_highlights_in_range(
13925        &self,
13926        search_range: Range<Anchor>,
13927        display_snapshot: &DisplaySnapshot,
13928        cx: &App,
13929    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13930        let mut results = Vec::new();
13931        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13932            let color = color_fetcher(cx);
13933            let start_ix = match ranges.binary_search_by(|probe| {
13934                let cmp = probe
13935                    .end
13936                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13937                if cmp.is_gt() {
13938                    Ordering::Greater
13939                } else {
13940                    Ordering::Less
13941                }
13942            }) {
13943                Ok(i) | Err(i) => i,
13944            };
13945            for range in &ranges[start_ix..] {
13946                if range
13947                    .start
13948                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13949                    .is_ge()
13950                {
13951                    break;
13952                }
13953
13954                let start = range.start.to_display_point(display_snapshot);
13955                let end = range.end.to_display_point(display_snapshot);
13956                results.push((start..end, color))
13957            }
13958        }
13959        results
13960    }
13961
13962    /// Get the text ranges corresponding to the redaction query
13963    pub fn redacted_ranges(
13964        &self,
13965        search_range: Range<Anchor>,
13966        display_snapshot: &DisplaySnapshot,
13967        cx: &App,
13968    ) -> Vec<Range<DisplayPoint>> {
13969        display_snapshot
13970            .buffer_snapshot
13971            .redacted_ranges(search_range, |file| {
13972                if let Some(file) = file {
13973                    file.is_private()
13974                        && EditorSettings::get(
13975                            Some(SettingsLocation {
13976                                worktree_id: file.worktree_id(cx),
13977                                path: file.path().as_ref(),
13978                            }),
13979                            cx,
13980                        )
13981                        .redact_private_values
13982                } else {
13983                    false
13984                }
13985            })
13986            .map(|range| {
13987                range.start.to_display_point(display_snapshot)
13988                    ..range.end.to_display_point(display_snapshot)
13989            })
13990            .collect()
13991    }
13992
13993    pub fn highlight_text<T: 'static>(
13994        &mut self,
13995        ranges: Vec<Range<Anchor>>,
13996        style: HighlightStyle,
13997        cx: &mut Context<Self>,
13998    ) {
13999        self.display_map.update(cx, |map, _| {
14000            map.highlight_text(TypeId::of::<T>(), ranges, style)
14001        });
14002        cx.notify();
14003    }
14004
14005    pub(crate) fn highlight_inlays<T: 'static>(
14006        &mut self,
14007        highlights: Vec<InlayHighlight>,
14008        style: HighlightStyle,
14009        cx: &mut Context<Self>,
14010    ) {
14011        self.display_map.update(cx, |map, _| {
14012            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14013        });
14014        cx.notify();
14015    }
14016
14017    pub fn text_highlights<'a, T: 'static>(
14018        &'a self,
14019        cx: &'a App,
14020    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14021        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14022    }
14023
14024    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14025        let cleared = self
14026            .display_map
14027            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14028        if cleared {
14029            cx.notify();
14030        }
14031    }
14032
14033    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14034        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14035            && self.focus_handle.is_focused(window)
14036    }
14037
14038    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14039        self.show_cursor_when_unfocused = is_enabled;
14040        cx.notify();
14041    }
14042
14043    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
14044        self.project
14045            .as_ref()
14046            .map(|project| project.read(cx).lsp_store())
14047    }
14048
14049    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14050        cx.notify();
14051    }
14052
14053    fn on_buffer_event(
14054        &mut self,
14055        multibuffer: &Entity<MultiBuffer>,
14056        event: &multi_buffer::Event,
14057        window: &mut Window,
14058        cx: &mut Context<Self>,
14059    ) {
14060        match event {
14061            multi_buffer::Event::Edited {
14062                singleton_buffer_edited,
14063                edited_buffer: buffer_edited,
14064            } => {
14065                self.scrollbar_marker_state.dirty = true;
14066                self.active_indent_guides_state.dirty = true;
14067                self.refresh_active_diagnostics(cx);
14068                self.refresh_code_actions(window, cx);
14069                if self.has_active_inline_completion() {
14070                    self.update_visible_inline_completion(window, cx);
14071                }
14072                if let Some(buffer) = buffer_edited {
14073                    let buffer_id = buffer.read(cx).remote_id();
14074                    if !self.registered_buffers.contains_key(&buffer_id) {
14075                        if let Some(lsp_store) = self.lsp_store(cx) {
14076                            lsp_store.update(cx, |lsp_store, cx| {
14077                                self.registered_buffers.insert(
14078                                    buffer_id,
14079                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
14080                                );
14081                            })
14082                        }
14083                    }
14084                }
14085                cx.emit(EditorEvent::BufferEdited);
14086                cx.emit(SearchEvent::MatchesInvalidated);
14087                if *singleton_buffer_edited {
14088                    if let Some(project) = &self.project {
14089                        let project = project.read(cx);
14090                        #[allow(clippy::mutable_key_type)]
14091                        let languages_affected = multibuffer
14092                            .read(cx)
14093                            .all_buffers()
14094                            .into_iter()
14095                            .filter_map(|buffer| {
14096                                let buffer = buffer.read(cx);
14097                                let language = buffer.language()?;
14098                                if project.is_local()
14099                                    && project
14100                                        .language_servers_for_local_buffer(buffer, cx)
14101                                        .count()
14102                                        == 0
14103                                {
14104                                    None
14105                                } else {
14106                                    Some(language)
14107                                }
14108                            })
14109                            .cloned()
14110                            .collect::<HashSet<_>>();
14111                        if !languages_affected.is_empty() {
14112                            self.refresh_inlay_hints(
14113                                InlayHintRefreshReason::BufferEdited(languages_affected),
14114                                cx,
14115                            );
14116                        }
14117                    }
14118                }
14119
14120                let Some(project) = &self.project else { return };
14121                let (telemetry, is_via_ssh) = {
14122                    let project = project.read(cx);
14123                    let telemetry = project.client().telemetry().clone();
14124                    let is_via_ssh = project.is_via_ssh();
14125                    (telemetry, is_via_ssh)
14126                };
14127                refresh_linked_ranges(self, window, cx);
14128                telemetry.log_edit_event("editor", is_via_ssh);
14129            }
14130            multi_buffer::Event::ExcerptsAdded {
14131                buffer,
14132                predecessor,
14133                excerpts,
14134            } => {
14135                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14136                let buffer_id = buffer.read(cx).remote_id();
14137                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14138                    if let Some(project) = &self.project {
14139                        get_uncommitted_diff_for_buffer(
14140                            project,
14141                            [buffer.clone()],
14142                            self.buffer.clone(),
14143                            cx,
14144                        );
14145                    }
14146                }
14147                cx.emit(EditorEvent::ExcerptsAdded {
14148                    buffer: buffer.clone(),
14149                    predecessor: *predecessor,
14150                    excerpts: excerpts.clone(),
14151                });
14152                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14153            }
14154            multi_buffer::Event::ExcerptsRemoved { ids } => {
14155                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14156                let buffer = self.buffer.read(cx);
14157                self.registered_buffers
14158                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14159                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14160            }
14161            multi_buffer::Event::ExcerptsEdited { ids } => {
14162                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14163            }
14164            multi_buffer::Event::ExcerptsExpanded { ids } => {
14165                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14166                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14167            }
14168            multi_buffer::Event::Reparsed(buffer_id) => {
14169                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14170
14171                cx.emit(EditorEvent::Reparsed(*buffer_id));
14172            }
14173            multi_buffer::Event::DiffHunksToggled => {
14174                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14175            }
14176            multi_buffer::Event::LanguageChanged(buffer_id) => {
14177                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14178                cx.emit(EditorEvent::Reparsed(*buffer_id));
14179                cx.notify();
14180            }
14181            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14182            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14183            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14184                cx.emit(EditorEvent::TitleChanged)
14185            }
14186            // multi_buffer::Event::DiffBaseChanged => {
14187            //     self.scrollbar_marker_state.dirty = true;
14188            //     cx.emit(EditorEvent::DiffBaseChanged);
14189            //     cx.notify();
14190            // }
14191            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14192            multi_buffer::Event::DiagnosticsUpdated => {
14193                self.refresh_active_diagnostics(cx);
14194                self.scrollbar_marker_state.dirty = true;
14195                cx.notify();
14196            }
14197            _ => {}
14198        };
14199    }
14200
14201    fn on_display_map_changed(
14202        &mut self,
14203        _: Entity<DisplayMap>,
14204        _: &mut Window,
14205        cx: &mut Context<Self>,
14206    ) {
14207        cx.notify();
14208    }
14209
14210    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14211        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14212        self.refresh_inline_completion(true, false, window, cx);
14213        self.refresh_inlay_hints(
14214            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14215                self.selections.newest_anchor().head(),
14216                &self.buffer.read(cx).snapshot(cx),
14217                cx,
14218            )),
14219            cx,
14220        );
14221
14222        let old_cursor_shape = self.cursor_shape;
14223
14224        {
14225            let editor_settings = EditorSettings::get_global(cx);
14226            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14227            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14228            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14229        }
14230
14231        if old_cursor_shape != self.cursor_shape {
14232            cx.emit(EditorEvent::CursorShapeChanged);
14233        }
14234
14235        let project_settings = ProjectSettings::get_global(cx);
14236        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14237
14238        if self.mode == EditorMode::Full {
14239            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14240            if self.git_blame_inline_enabled != inline_blame_enabled {
14241                self.toggle_git_blame_inline_internal(false, window, cx);
14242            }
14243        }
14244
14245        cx.notify();
14246    }
14247
14248    pub fn set_searchable(&mut self, searchable: bool) {
14249        self.searchable = searchable;
14250    }
14251
14252    pub fn searchable(&self) -> bool {
14253        self.searchable
14254    }
14255
14256    fn open_proposed_changes_editor(
14257        &mut self,
14258        _: &OpenProposedChangesEditor,
14259        window: &mut Window,
14260        cx: &mut Context<Self>,
14261    ) {
14262        let Some(workspace) = self.workspace() else {
14263            cx.propagate();
14264            return;
14265        };
14266
14267        let selections = self.selections.all::<usize>(cx);
14268        let multi_buffer = self.buffer.read(cx);
14269        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14270        let mut new_selections_by_buffer = HashMap::default();
14271        for selection in selections {
14272            for (buffer, range, _) in
14273                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14274            {
14275                let mut range = range.to_point(buffer);
14276                range.start.column = 0;
14277                range.end.column = buffer.line_len(range.end.row);
14278                new_selections_by_buffer
14279                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14280                    .or_insert(Vec::new())
14281                    .push(range)
14282            }
14283        }
14284
14285        let proposed_changes_buffers = new_selections_by_buffer
14286            .into_iter()
14287            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14288            .collect::<Vec<_>>();
14289        let proposed_changes_editor = cx.new(|cx| {
14290            ProposedChangesEditor::new(
14291                "Proposed changes",
14292                proposed_changes_buffers,
14293                self.project.clone(),
14294                window,
14295                cx,
14296            )
14297        });
14298
14299        window.defer(cx, move |window, cx| {
14300            workspace.update(cx, |workspace, cx| {
14301                workspace.active_pane().update(cx, |pane, cx| {
14302                    pane.add_item(
14303                        Box::new(proposed_changes_editor),
14304                        true,
14305                        true,
14306                        None,
14307                        window,
14308                        cx,
14309                    );
14310                });
14311            });
14312        });
14313    }
14314
14315    pub fn open_excerpts_in_split(
14316        &mut self,
14317        _: &OpenExcerptsSplit,
14318        window: &mut Window,
14319        cx: &mut Context<Self>,
14320    ) {
14321        self.open_excerpts_common(None, true, window, cx)
14322    }
14323
14324    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14325        self.open_excerpts_common(None, false, window, cx)
14326    }
14327
14328    fn open_excerpts_common(
14329        &mut self,
14330        jump_data: Option<JumpData>,
14331        split: bool,
14332        window: &mut Window,
14333        cx: &mut Context<Self>,
14334    ) {
14335        let Some(workspace) = self.workspace() else {
14336            cx.propagate();
14337            return;
14338        };
14339
14340        if self.buffer.read(cx).is_singleton() {
14341            cx.propagate();
14342            return;
14343        }
14344
14345        let mut new_selections_by_buffer = HashMap::default();
14346        match &jump_data {
14347            Some(JumpData::MultiBufferPoint {
14348                excerpt_id,
14349                position,
14350                anchor,
14351                line_offset_from_top,
14352            }) => {
14353                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14354                if let Some(buffer) = multi_buffer_snapshot
14355                    .buffer_id_for_excerpt(*excerpt_id)
14356                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14357                {
14358                    let buffer_snapshot = buffer.read(cx).snapshot();
14359                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14360                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14361                    } else {
14362                        buffer_snapshot.clip_point(*position, Bias::Left)
14363                    };
14364                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14365                    new_selections_by_buffer.insert(
14366                        buffer,
14367                        (
14368                            vec![jump_to_offset..jump_to_offset],
14369                            Some(*line_offset_from_top),
14370                        ),
14371                    );
14372                }
14373            }
14374            Some(JumpData::MultiBufferRow {
14375                row,
14376                line_offset_from_top,
14377            }) => {
14378                let point = MultiBufferPoint::new(row.0, 0);
14379                if let Some((buffer, buffer_point, _)) =
14380                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14381                {
14382                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14383                    new_selections_by_buffer
14384                        .entry(buffer)
14385                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14386                        .0
14387                        .push(buffer_offset..buffer_offset)
14388                }
14389            }
14390            None => {
14391                let selections = self.selections.all::<usize>(cx);
14392                let multi_buffer = self.buffer.read(cx);
14393                for selection in selections {
14394                    for (buffer, mut range, _) in multi_buffer
14395                        .snapshot(cx)
14396                        .range_to_buffer_ranges(selection.range())
14397                    {
14398                        // When editing branch buffers, jump to the corresponding location
14399                        // in their base buffer.
14400                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14401                        let buffer = buffer_handle.read(cx);
14402                        if let Some(base_buffer) = buffer.base_buffer() {
14403                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14404                            buffer_handle = base_buffer;
14405                        }
14406
14407                        if selection.reversed {
14408                            mem::swap(&mut range.start, &mut range.end);
14409                        }
14410                        new_selections_by_buffer
14411                            .entry(buffer_handle)
14412                            .or_insert((Vec::new(), None))
14413                            .0
14414                            .push(range)
14415                    }
14416                }
14417            }
14418        }
14419
14420        if new_selections_by_buffer.is_empty() {
14421            return;
14422        }
14423
14424        // We defer the pane interaction because we ourselves are a workspace item
14425        // and activating a new item causes the pane to call a method on us reentrantly,
14426        // which panics if we're on the stack.
14427        window.defer(cx, move |window, cx| {
14428            workspace.update(cx, |workspace, cx| {
14429                let pane = if split {
14430                    workspace.adjacent_pane(window, cx)
14431                } else {
14432                    workspace.active_pane().clone()
14433                };
14434
14435                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14436                    let editor = buffer
14437                        .read(cx)
14438                        .file()
14439                        .is_none()
14440                        .then(|| {
14441                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14442                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14443                            // Instead, we try to activate the existing editor in the pane first.
14444                            let (editor, pane_item_index) =
14445                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14446                                    let editor = item.downcast::<Editor>()?;
14447                                    let singleton_buffer =
14448                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14449                                    if singleton_buffer == buffer {
14450                                        Some((editor, i))
14451                                    } else {
14452                                        None
14453                                    }
14454                                })?;
14455                            pane.update(cx, |pane, cx| {
14456                                pane.activate_item(pane_item_index, true, true, window, cx)
14457                            });
14458                            Some(editor)
14459                        })
14460                        .flatten()
14461                        .unwrap_or_else(|| {
14462                            workspace.open_project_item::<Self>(
14463                                pane.clone(),
14464                                buffer,
14465                                true,
14466                                true,
14467                                window,
14468                                cx,
14469                            )
14470                        });
14471
14472                    editor.update(cx, |editor, cx| {
14473                        let autoscroll = match scroll_offset {
14474                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14475                            None => Autoscroll::newest(),
14476                        };
14477                        let nav_history = editor.nav_history.take();
14478                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14479                            s.select_ranges(ranges);
14480                        });
14481                        editor.nav_history = nav_history;
14482                    });
14483                }
14484            })
14485        });
14486    }
14487
14488    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14489        let snapshot = self.buffer.read(cx).read(cx);
14490        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14491        Some(
14492            ranges
14493                .iter()
14494                .map(move |range| {
14495                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14496                })
14497                .collect(),
14498        )
14499    }
14500
14501    fn selection_replacement_ranges(
14502        &self,
14503        range: Range<OffsetUtf16>,
14504        cx: &mut App,
14505    ) -> Vec<Range<OffsetUtf16>> {
14506        let selections = self.selections.all::<OffsetUtf16>(cx);
14507        let newest_selection = selections
14508            .iter()
14509            .max_by_key(|selection| selection.id)
14510            .unwrap();
14511        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14512        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14513        let snapshot = self.buffer.read(cx).read(cx);
14514        selections
14515            .into_iter()
14516            .map(|mut selection| {
14517                selection.start.0 =
14518                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14519                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14520                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14521                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14522            })
14523            .collect()
14524    }
14525
14526    fn report_editor_event(
14527        &self,
14528        event_type: &'static str,
14529        file_extension: Option<String>,
14530        cx: &App,
14531    ) {
14532        if cfg!(any(test, feature = "test-support")) {
14533            return;
14534        }
14535
14536        let Some(project) = &self.project else { return };
14537
14538        // If None, we are in a file without an extension
14539        let file = self
14540            .buffer
14541            .read(cx)
14542            .as_singleton()
14543            .and_then(|b| b.read(cx).file());
14544        let file_extension = file_extension.or(file
14545            .as_ref()
14546            .and_then(|file| Path::new(file.file_name(cx)).extension())
14547            .and_then(|e| e.to_str())
14548            .map(|a| a.to_string()));
14549
14550        let vim_mode = cx
14551            .global::<SettingsStore>()
14552            .raw_user_settings()
14553            .get("vim_mode")
14554            == Some(&serde_json::Value::Bool(true));
14555
14556        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14557        let copilot_enabled = edit_predictions_provider
14558            == language::language_settings::EditPredictionProvider::Copilot;
14559        let copilot_enabled_for_language = self
14560            .buffer
14561            .read(cx)
14562            .settings_at(0, cx)
14563            .show_edit_predictions;
14564
14565        let project = project.read(cx);
14566        telemetry::event!(
14567            event_type,
14568            file_extension,
14569            vim_mode,
14570            copilot_enabled,
14571            copilot_enabled_for_language,
14572            edit_predictions_provider,
14573            is_via_ssh = project.is_via_ssh(),
14574        );
14575    }
14576
14577    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14578    /// with each line being an array of {text, highlight} objects.
14579    fn copy_highlight_json(
14580        &mut self,
14581        _: &CopyHighlightJson,
14582        window: &mut Window,
14583        cx: &mut Context<Self>,
14584    ) {
14585        #[derive(Serialize)]
14586        struct Chunk<'a> {
14587            text: String,
14588            highlight: Option<&'a str>,
14589        }
14590
14591        let snapshot = self.buffer.read(cx).snapshot(cx);
14592        let range = self
14593            .selected_text_range(false, window, cx)
14594            .and_then(|selection| {
14595                if selection.range.is_empty() {
14596                    None
14597                } else {
14598                    Some(selection.range)
14599                }
14600            })
14601            .unwrap_or_else(|| 0..snapshot.len());
14602
14603        let chunks = snapshot.chunks(range, true);
14604        let mut lines = Vec::new();
14605        let mut line: VecDeque<Chunk> = VecDeque::new();
14606
14607        let Some(style) = self.style.as_ref() else {
14608            return;
14609        };
14610
14611        for chunk in chunks {
14612            let highlight = chunk
14613                .syntax_highlight_id
14614                .and_then(|id| id.name(&style.syntax));
14615            let mut chunk_lines = chunk.text.split('\n').peekable();
14616            while let Some(text) = chunk_lines.next() {
14617                let mut merged_with_last_token = false;
14618                if let Some(last_token) = line.back_mut() {
14619                    if last_token.highlight == highlight {
14620                        last_token.text.push_str(text);
14621                        merged_with_last_token = true;
14622                    }
14623                }
14624
14625                if !merged_with_last_token {
14626                    line.push_back(Chunk {
14627                        text: text.into(),
14628                        highlight,
14629                    });
14630                }
14631
14632                if chunk_lines.peek().is_some() {
14633                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14634                        line.pop_front();
14635                    }
14636                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14637                        line.pop_back();
14638                    }
14639
14640                    lines.push(mem::take(&mut line));
14641                }
14642            }
14643        }
14644
14645        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14646            return;
14647        };
14648        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14649    }
14650
14651    pub fn open_context_menu(
14652        &mut self,
14653        _: &OpenContextMenu,
14654        window: &mut Window,
14655        cx: &mut Context<Self>,
14656    ) {
14657        self.request_autoscroll(Autoscroll::newest(), cx);
14658        let position = self.selections.newest_display(cx).start;
14659        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14660    }
14661
14662    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14663        &self.inlay_hint_cache
14664    }
14665
14666    pub fn replay_insert_event(
14667        &mut self,
14668        text: &str,
14669        relative_utf16_range: Option<Range<isize>>,
14670        window: &mut Window,
14671        cx: &mut Context<Self>,
14672    ) {
14673        if !self.input_enabled {
14674            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14675            return;
14676        }
14677        if let Some(relative_utf16_range) = relative_utf16_range {
14678            let selections = self.selections.all::<OffsetUtf16>(cx);
14679            self.change_selections(None, window, cx, |s| {
14680                let new_ranges = selections.into_iter().map(|range| {
14681                    let start = OffsetUtf16(
14682                        range
14683                            .head()
14684                            .0
14685                            .saturating_add_signed(relative_utf16_range.start),
14686                    );
14687                    let end = OffsetUtf16(
14688                        range
14689                            .head()
14690                            .0
14691                            .saturating_add_signed(relative_utf16_range.end),
14692                    );
14693                    start..end
14694                });
14695                s.select_ranges(new_ranges);
14696            });
14697        }
14698
14699        self.handle_input(text, window, cx);
14700    }
14701
14702    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14703        let Some(provider) = self.semantics_provider.as_ref() else {
14704            return false;
14705        };
14706
14707        let mut supports = false;
14708        self.buffer().read(cx).for_each_buffer(|buffer| {
14709            supports |= provider.supports_inlay_hints(buffer, cx);
14710        });
14711        supports
14712    }
14713
14714    pub fn is_focused(&self, window: &Window) -> bool {
14715        self.focus_handle.is_focused(window)
14716    }
14717
14718    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14719        cx.emit(EditorEvent::Focused);
14720
14721        if let Some(descendant) = self
14722            .last_focused_descendant
14723            .take()
14724            .and_then(|descendant| descendant.upgrade())
14725        {
14726            window.focus(&descendant);
14727        } else {
14728            if let Some(blame) = self.blame.as_ref() {
14729                blame.update(cx, GitBlame::focus)
14730            }
14731
14732            self.blink_manager.update(cx, BlinkManager::enable);
14733            self.show_cursor_names(window, cx);
14734            self.buffer.update(cx, |buffer, cx| {
14735                buffer.finalize_last_transaction(cx);
14736                if self.leader_peer_id.is_none() {
14737                    buffer.set_active_selections(
14738                        &self.selections.disjoint_anchors(),
14739                        self.selections.line_mode,
14740                        self.cursor_shape,
14741                        cx,
14742                    );
14743                }
14744            });
14745        }
14746    }
14747
14748    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14749        cx.emit(EditorEvent::FocusedIn)
14750    }
14751
14752    fn handle_focus_out(
14753        &mut self,
14754        event: FocusOutEvent,
14755        _window: &mut Window,
14756        _cx: &mut Context<Self>,
14757    ) {
14758        if event.blurred != self.focus_handle {
14759            self.last_focused_descendant = Some(event.blurred);
14760        }
14761    }
14762
14763    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14764        self.blink_manager.update(cx, BlinkManager::disable);
14765        self.buffer
14766            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14767
14768        if let Some(blame) = self.blame.as_ref() {
14769            blame.update(cx, GitBlame::blur)
14770        }
14771        if !self.hover_state.focused(window, cx) {
14772            hide_hover(self, cx);
14773        }
14774
14775        self.hide_context_menu(window, cx);
14776        self.discard_inline_completion(false, cx);
14777        cx.emit(EditorEvent::Blurred);
14778        cx.notify();
14779    }
14780
14781    pub fn register_action<A: Action>(
14782        &mut self,
14783        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14784    ) -> Subscription {
14785        let id = self.next_editor_action_id.post_inc();
14786        let listener = Arc::new(listener);
14787        self.editor_actions.borrow_mut().insert(
14788            id,
14789            Box::new(move |window, _| {
14790                let listener = listener.clone();
14791                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14792                    let action = action.downcast_ref().unwrap();
14793                    if phase == DispatchPhase::Bubble {
14794                        listener(action, window, cx)
14795                    }
14796                })
14797            }),
14798        );
14799
14800        let editor_actions = self.editor_actions.clone();
14801        Subscription::new(move || {
14802            editor_actions.borrow_mut().remove(&id);
14803        })
14804    }
14805
14806    pub fn file_header_size(&self) -> u32 {
14807        FILE_HEADER_HEIGHT
14808    }
14809
14810    pub fn revert(
14811        &mut self,
14812        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14813        window: &mut Window,
14814        cx: &mut Context<Self>,
14815    ) {
14816        self.buffer().update(cx, |multi_buffer, cx| {
14817            for (buffer_id, changes) in revert_changes {
14818                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14819                    buffer.update(cx, |buffer, cx| {
14820                        buffer.edit(
14821                            changes.into_iter().map(|(range, text)| {
14822                                (range, text.to_string().map(Arc::<str>::from))
14823                            }),
14824                            None,
14825                            cx,
14826                        );
14827                    });
14828                }
14829            }
14830        });
14831        self.change_selections(None, window, cx, |selections| selections.refresh());
14832    }
14833
14834    pub fn to_pixel_point(
14835        &self,
14836        source: multi_buffer::Anchor,
14837        editor_snapshot: &EditorSnapshot,
14838        window: &mut Window,
14839    ) -> Option<gpui::Point<Pixels>> {
14840        let source_point = source.to_display_point(editor_snapshot);
14841        self.display_to_pixel_point(source_point, editor_snapshot, window)
14842    }
14843
14844    pub fn display_to_pixel_point(
14845        &self,
14846        source: DisplayPoint,
14847        editor_snapshot: &EditorSnapshot,
14848        window: &mut Window,
14849    ) -> Option<gpui::Point<Pixels>> {
14850        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14851        let text_layout_details = self.text_layout_details(window);
14852        let scroll_top = text_layout_details
14853            .scroll_anchor
14854            .scroll_position(editor_snapshot)
14855            .y;
14856
14857        if source.row().as_f32() < scroll_top.floor() {
14858            return None;
14859        }
14860        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14861        let source_y = line_height * (source.row().as_f32() - scroll_top);
14862        Some(gpui::Point::new(source_x, source_y))
14863    }
14864
14865    pub fn has_visible_completions_menu(&self) -> bool {
14866        !self.edit_prediction_preview_is_active()
14867            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14868                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14869            })
14870    }
14871
14872    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14873        self.addons
14874            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14875    }
14876
14877    pub fn unregister_addon<T: Addon>(&mut self) {
14878        self.addons.remove(&std::any::TypeId::of::<T>());
14879    }
14880
14881    pub fn addon<T: Addon>(&self) -> Option<&T> {
14882        let type_id = std::any::TypeId::of::<T>();
14883        self.addons
14884            .get(&type_id)
14885            .and_then(|item| item.to_any().downcast_ref::<T>())
14886    }
14887
14888    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14889        let text_layout_details = self.text_layout_details(window);
14890        let style = &text_layout_details.editor_style;
14891        let font_id = window.text_system().resolve_font(&style.text.font());
14892        let font_size = style.text.font_size.to_pixels(window.rem_size());
14893        let line_height = style.text.line_height_in_pixels(window.rem_size());
14894        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14895
14896        gpui::Size::new(em_width, line_height)
14897    }
14898}
14899
14900fn get_uncommitted_diff_for_buffer(
14901    project: &Entity<Project>,
14902    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14903    buffer: Entity<MultiBuffer>,
14904    cx: &mut App,
14905) {
14906    let mut tasks = Vec::new();
14907    project.update(cx, |project, cx| {
14908        for buffer in buffers {
14909            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14910        }
14911    });
14912    cx.spawn(|mut cx| async move {
14913        let diffs = futures::future::join_all(tasks).await;
14914        buffer
14915            .update(&mut cx, |buffer, cx| {
14916                for diff in diffs.into_iter().flatten() {
14917                    buffer.add_diff(diff, cx);
14918                }
14919            })
14920            .ok();
14921    })
14922    .detach();
14923}
14924
14925fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14926    let tab_size = tab_size.get() as usize;
14927    let mut width = offset;
14928
14929    for ch in text.chars() {
14930        width += if ch == '\t' {
14931            tab_size - (width % tab_size)
14932        } else {
14933            1
14934        };
14935    }
14936
14937    width - offset
14938}
14939
14940#[cfg(test)]
14941mod tests {
14942    use super::*;
14943
14944    #[test]
14945    fn test_string_size_with_expanded_tabs() {
14946        let nz = |val| NonZeroU32::new(val).unwrap();
14947        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14948        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14949        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14950        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14951        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14952        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14953        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14954        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14955    }
14956}
14957
14958/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14959struct WordBreakingTokenizer<'a> {
14960    input: &'a str,
14961}
14962
14963impl<'a> WordBreakingTokenizer<'a> {
14964    fn new(input: &'a str) -> Self {
14965        Self { input }
14966    }
14967}
14968
14969fn is_char_ideographic(ch: char) -> bool {
14970    use unicode_script::Script::*;
14971    use unicode_script::UnicodeScript;
14972    matches!(ch.script(), Han | Tangut | Yi)
14973}
14974
14975fn is_grapheme_ideographic(text: &str) -> bool {
14976    text.chars().any(is_char_ideographic)
14977}
14978
14979fn is_grapheme_whitespace(text: &str) -> bool {
14980    text.chars().any(|x| x.is_whitespace())
14981}
14982
14983fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14984    text.chars().next().map_or(false, |ch| {
14985        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14986    })
14987}
14988
14989#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14990struct WordBreakToken<'a> {
14991    token: &'a str,
14992    grapheme_len: usize,
14993    is_whitespace: bool,
14994}
14995
14996impl<'a> Iterator for WordBreakingTokenizer<'a> {
14997    /// Yields a span, the count of graphemes in the token, and whether it was
14998    /// whitespace. Note that it also breaks at word boundaries.
14999    type Item = WordBreakToken<'a>;
15000
15001    fn next(&mut self) -> Option<Self::Item> {
15002        use unicode_segmentation::UnicodeSegmentation;
15003        if self.input.is_empty() {
15004            return None;
15005        }
15006
15007        let mut iter = self.input.graphemes(true).peekable();
15008        let mut offset = 0;
15009        let mut graphemes = 0;
15010        if let Some(first_grapheme) = iter.next() {
15011            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15012            offset += first_grapheme.len();
15013            graphemes += 1;
15014            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15015                if let Some(grapheme) = iter.peek().copied() {
15016                    if should_stay_with_preceding_ideograph(grapheme) {
15017                        offset += grapheme.len();
15018                        graphemes += 1;
15019                    }
15020                }
15021            } else {
15022                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15023                let mut next_word_bound = words.peek().copied();
15024                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15025                    next_word_bound = words.next();
15026                }
15027                while let Some(grapheme) = iter.peek().copied() {
15028                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15029                        break;
15030                    };
15031                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15032                        break;
15033                    };
15034                    offset += grapheme.len();
15035                    graphemes += 1;
15036                    iter.next();
15037                }
15038            }
15039            let token = &self.input[..offset];
15040            self.input = &self.input[offset..];
15041            if is_whitespace {
15042                Some(WordBreakToken {
15043                    token: " ",
15044                    grapheme_len: 1,
15045                    is_whitespace: true,
15046                })
15047            } else {
15048                Some(WordBreakToken {
15049                    token,
15050                    grapheme_len: graphemes,
15051                    is_whitespace: false,
15052                })
15053            }
15054        } else {
15055            None
15056        }
15057    }
15058}
15059
15060#[test]
15061fn test_word_breaking_tokenizer() {
15062    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15063        ("", &[]),
15064        ("  ", &[(" ", 1, true)]),
15065        ("Ʒ", &[("Ʒ", 1, false)]),
15066        ("Ǽ", &[("Ǽ", 1, false)]),
15067        ("", &[("", 1, false)]),
15068        ("⋑⋑", &[("⋑⋑", 2, false)]),
15069        (
15070            "原理,进而",
15071            &[
15072                ("", 1, false),
15073                ("理,", 2, false),
15074                ("", 1, false),
15075                ("", 1, false),
15076            ],
15077        ),
15078        (
15079            "hello world",
15080            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15081        ),
15082        (
15083            "hello, world",
15084            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15085        ),
15086        (
15087            "  hello world",
15088            &[
15089                (" ", 1, true),
15090                ("hello", 5, false),
15091                (" ", 1, true),
15092                ("world", 5, false),
15093            ],
15094        ),
15095        (
15096            "这是什么 \n 钢笔",
15097            &[
15098                ("", 1, false),
15099                ("", 1, false),
15100                ("", 1, false),
15101                ("", 1, false),
15102                (" ", 1, true),
15103                ("", 1, false),
15104                ("", 1, false),
15105            ],
15106        ),
15107        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15108    ];
15109
15110    for (input, result) in tests {
15111        assert_eq!(
15112            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15113            result
15114                .iter()
15115                .copied()
15116                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15117                    token,
15118                    grapheme_len,
15119                    is_whitespace,
15120                })
15121                .collect::<Vec<_>>()
15122        );
15123    }
15124}
15125
15126fn wrap_with_prefix(
15127    line_prefix: String,
15128    unwrapped_text: String,
15129    wrap_column: usize,
15130    tab_size: NonZeroU32,
15131) -> String {
15132    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15133    let mut wrapped_text = String::new();
15134    let mut current_line = line_prefix.clone();
15135
15136    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15137    let mut current_line_len = line_prefix_len;
15138    for WordBreakToken {
15139        token,
15140        grapheme_len,
15141        is_whitespace,
15142    } in tokenizer
15143    {
15144        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15145            wrapped_text.push_str(current_line.trim_end());
15146            wrapped_text.push('\n');
15147            current_line.truncate(line_prefix.len());
15148            current_line_len = line_prefix_len;
15149            if !is_whitespace {
15150                current_line.push_str(token);
15151                current_line_len += grapheme_len;
15152            }
15153        } else if !is_whitespace {
15154            current_line.push_str(token);
15155            current_line_len += grapheme_len;
15156        } else if current_line_len != line_prefix_len {
15157            current_line.push(' ');
15158            current_line_len += 1;
15159        }
15160    }
15161
15162    if !current_line.is_empty() {
15163        wrapped_text.push_str(&current_line);
15164    }
15165    wrapped_text
15166}
15167
15168#[test]
15169fn test_wrap_with_prefix() {
15170    assert_eq!(
15171        wrap_with_prefix(
15172            "# ".to_string(),
15173            "abcdefg".to_string(),
15174            4,
15175            NonZeroU32::new(4).unwrap()
15176        ),
15177        "# abcdefg"
15178    );
15179    assert_eq!(
15180        wrap_with_prefix(
15181            "".to_string(),
15182            "\thello world".to_string(),
15183            8,
15184            NonZeroU32::new(4).unwrap()
15185        ),
15186        "hello\nworld"
15187    );
15188    assert_eq!(
15189        wrap_with_prefix(
15190            "// ".to_string(),
15191            "xx \nyy zz aa bb cc".to_string(),
15192            12,
15193            NonZeroU32::new(4).unwrap()
15194        ),
15195        "// xx yy zz\n// aa bb cc"
15196    );
15197    assert_eq!(
15198        wrap_with_prefix(
15199            String::new(),
15200            "这是什么 \n 钢笔".to_string(),
15201            3,
15202            NonZeroU32::new(4).unwrap()
15203        ),
15204        "这是什\n么 钢\n"
15205    );
15206}
15207
15208pub trait CollaborationHub {
15209    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15210    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15211    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15212}
15213
15214impl CollaborationHub for Entity<Project> {
15215    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15216        self.read(cx).collaborators()
15217    }
15218
15219    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15220        self.read(cx).user_store().read(cx).participant_indices()
15221    }
15222
15223    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15224        let this = self.read(cx);
15225        let user_ids = this.collaborators().values().map(|c| c.user_id);
15226        this.user_store().read_with(cx, |user_store, cx| {
15227            user_store.participant_names(user_ids, cx)
15228        })
15229    }
15230}
15231
15232pub trait SemanticsProvider {
15233    fn hover(
15234        &self,
15235        buffer: &Entity<Buffer>,
15236        position: text::Anchor,
15237        cx: &mut App,
15238    ) -> Option<Task<Vec<project::Hover>>>;
15239
15240    fn inlay_hints(
15241        &self,
15242        buffer_handle: Entity<Buffer>,
15243        range: Range<text::Anchor>,
15244        cx: &mut App,
15245    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15246
15247    fn resolve_inlay_hint(
15248        &self,
15249        hint: InlayHint,
15250        buffer_handle: Entity<Buffer>,
15251        server_id: LanguageServerId,
15252        cx: &mut App,
15253    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15254
15255    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
15256
15257    fn document_highlights(
15258        &self,
15259        buffer: &Entity<Buffer>,
15260        position: text::Anchor,
15261        cx: &mut App,
15262    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15263
15264    fn definitions(
15265        &self,
15266        buffer: &Entity<Buffer>,
15267        position: text::Anchor,
15268        kind: GotoDefinitionKind,
15269        cx: &mut App,
15270    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15271
15272    fn range_for_rename(
15273        &self,
15274        buffer: &Entity<Buffer>,
15275        position: text::Anchor,
15276        cx: &mut App,
15277    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15278
15279    fn perform_rename(
15280        &self,
15281        buffer: &Entity<Buffer>,
15282        position: text::Anchor,
15283        new_name: String,
15284        cx: &mut App,
15285    ) -> Option<Task<Result<ProjectTransaction>>>;
15286}
15287
15288pub trait CompletionProvider {
15289    fn completions(
15290        &self,
15291        buffer: &Entity<Buffer>,
15292        buffer_position: text::Anchor,
15293        trigger: CompletionContext,
15294        window: &mut Window,
15295        cx: &mut Context<Editor>,
15296    ) -> Task<Result<Vec<Completion>>>;
15297
15298    fn resolve_completions(
15299        &self,
15300        buffer: Entity<Buffer>,
15301        completion_indices: Vec<usize>,
15302        completions: Rc<RefCell<Box<[Completion]>>>,
15303        cx: &mut Context<Editor>,
15304    ) -> Task<Result<bool>>;
15305
15306    fn apply_additional_edits_for_completion(
15307        &self,
15308        _buffer: Entity<Buffer>,
15309        _completions: Rc<RefCell<Box<[Completion]>>>,
15310        _completion_index: usize,
15311        _push_to_history: bool,
15312        _cx: &mut Context<Editor>,
15313    ) -> Task<Result<Option<language::Transaction>>> {
15314        Task::ready(Ok(None))
15315    }
15316
15317    fn is_completion_trigger(
15318        &self,
15319        buffer: &Entity<Buffer>,
15320        position: language::Anchor,
15321        text: &str,
15322        trigger_in_words: bool,
15323        cx: &mut Context<Editor>,
15324    ) -> bool;
15325
15326    fn sort_completions(&self) -> bool {
15327        true
15328    }
15329}
15330
15331pub trait CodeActionProvider {
15332    fn id(&self) -> Arc<str>;
15333
15334    fn code_actions(
15335        &self,
15336        buffer: &Entity<Buffer>,
15337        range: Range<text::Anchor>,
15338        window: &mut Window,
15339        cx: &mut App,
15340    ) -> Task<Result<Vec<CodeAction>>>;
15341
15342    fn apply_code_action(
15343        &self,
15344        buffer_handle: Entity<Buffer>,
15345        action: CodeAction,
15346        excerpt_id: ExcerptId,
15347        push_to_history: bool,
15348        window: &mut Window,
15349        cx: &mut App,
15350    ) -> Task<Result<ProjectTransaction>>;
15351}
15352
15353impl CodeActionProvider for Entity<Project> {
15354    fn id(&self) -> Arc<str> {
15355        "project".into()
15356    }
15357
15358    fn code_actions(
15359        &self,
15360        buffer: &Entity<Buffer>,
15361        range: Range<text::Anchor>,
15362        _window: &mut Window,
15363        cx: &mut App,
15364    ) -> Task<Result<Vec<CodeAction>>> {
15365        self.update(cx, |project, cx| {
15366            project.code_actions(buffer, range, None, cx)
15367        })
15368    }
15369
15370    fn apply_code_action(
15371        &self,
15372        buffer_handle: Entity<Buffer>,
15373        action: CodeAction,
15374        _excerpt_id: ExcerptId,
15375        push_to_history: bool,
15376        _window: &mut Window,
15377        cx: &mut App,
15378    ) -> Task<Result<ProjectTransaction>> {
15379        self.update(cx, |project, cx| {
15380            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15381        })
15382    }
15383}
15384
15385fn snippet_completions(
15386    project: &Project,
15387    buffer: &Entity<Buffer>,
15388    buffer_position: text::Anchor,
15389    cx: &mut App,
15390) -> Task<Result<Vec<Completion>>> {
15391    let language = buffer.read(cx).language_at(buffer_position);
15392    let language_name = language.as_ref().map(|language| language.lsp_id());
15393    let snippet_store = project.snippets().read(cx);
15394    let snippets = snippet_store.snippets_for(language_name, cx);
15395
15396    if snippets.is_empty() {
15397        return Task::ready(Ok(vec![]));
15398    }
15399    let snapshot = buffer.read(cx).text_snapshot();
15400    let chars: String = snapshot
15401        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15402        .collect();
15403
15404    let scope = language.map(|language| language.default_scope());
15405    let executor = cx.background_executor().clone();
15406
15407    cx.background_executor().spawn(async move {
15408        let classifier = CharClassifier::new(scope).for_completion(true);
15409        let mut last_word = chars
15410            .chars()
15411            .take_while(|c| classifier.is_word(*c))
15412            .collect::<String>();
15413        last_word = last_word.chars().rev().collect();
15414
15415        if last_word.is_empty() {
15416            return Ok(vec![]);
15417        }
15418
15419        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15420        let to_lsp = |point: &text::Anchor| {
15421            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15422            point_to_lsp(end)
15423        };
15424        let lsp_end = to_lsp(&buffer_position);
15425
15426        let candidates = snippets
15427            .iter()
15428            .enumerate()
15429            .flat_map(|(ix, snippet)| {
15430                snippet
15431                    .prefix
15432                    .iter()
15433                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15434            })
15435            .collect::<Vec<StringMatchCandidate>>();
15436
15437        let mut matches = fuzzy::match_strings(
15438            &candidates,
15439            &last_word,
15440            last_word.chars().any(|c| c.is_uppercase()),
15441            100,
15442            &Default::default(),
15443            executor,
15444        )
15445        .await;
15446
15447        // Remove all candidates where the query's start does not match the start of any word in the candidate
15448        if let Some(query_start) = last_word.chars().next() {
15449            matches.retain(|string_match| {
15450                split_words(&string_match.string).any(|word| {
15451                    // Check that the first codepoint of the word as lowercase matches the first
15452                    // codepoint of the query as lowercase
15453                    word.chars()
15454                        .flat_map(|codepoint| codepoint.to_lowercase())
15455                        .zip(query_start.to_lowercase())
15456                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15457                })
15458            });
15459        }
15460
15461        let matched_strings = matches
15462            .into_iter()
15463            .map(|m| m.string)
15464            .collect::<HashSet<_>>();
15465
15466        let result: Vec<Completion> = snippets
15467            .into_iter()
15468            .filter_map(|snippet| {
15469                let matching_prefix = snippet
15470                    .prefix
15471                    .iter()
15472                    .find(|prefix| matched_strings.contains(*prefix))?;
15473                let start = as_offset - last_word.len();
15474                let start = snapshot.anchor_before(start);
15475                let range = start..buffer_position;
15476                let lsp_start = to_lsp(&start);
15477                let lsp_range = lsp::Range {
15478                    start: lsp_start,
15479                    end: lsp_end,
15480                };
15481                Some(Completion {
15482                    old_range: range,
15483                    new_text: snippet.body.clone(),
15484                    resolved: false,
15485                    label: CodeLabel {
15486                        text: matching_prefix.clone(),
15487                        runs: vec![],
15488                        filter_range: 0..matching_prefix.len(),
15489                    },
15490                    server_id: LanguageServerId(usize::MAX),
15491                    documentation: snippet
15492                        .description
15493                        .clone()
15494                        .map(CompletionDocumentation::SingleLine),
15495                    lsp_completion: lsp::CompletionItem {
15496                        label: snippet.prefix.first().unwrap().clone(),
15497                        kind: Some(CompletionItemKind::SNIPPET),
15498                        label_details: snippet.description.as_ref().map(|description| {
15499                            lsp::CompletionItemLabelDetails {
15500                                detail: Some(description.clone()),
15501                                description: None,
15502                            }
15503                        }),
15504                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15505                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15506                            lsp::InsertReplaceEdit {
15507                                new_text: snippet.body.clone(),
15508                                insert: lsp_range,
15509                                replace: lsp_range,
15510                            },
15511                        )),
15512                        filter_text: Some(snippet.body.clone()),
15513                        sort_text: Some(char::MAX.to_string()),
15514                        ..Default::default()
15515                    },
15516                    confirm: None,
15517                })
15518            })
15519            .collect();
15520
15521        Ok(result)
15522    })
15523}
15524
15525impl CompletionProvider for Entity<Project> {
15526    fn completions(
15527        &self,
15528        buffer: &Entity<Buffer>,
15529        buffer_position: text::Anchor,
15530        options: CompletionContext,
15531        _window: &mut Window,
15532        cx: &mut Context<Editor>,
15533    ) -> Task<Result<Vec<Completion>>> {
15534        self.update(cx, |project, cx| {
15535            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15536            let project_completions = project.completions(buffer, buffer_position, options, cx);
15537            cx.background_executor().spawn(async move {
15538                let mut completions = project_completions.await?;
15539                let snippets_completions = snippets.await?;
15540                completions.extend(snippets_completions);
15541                Ok(completions)
15542            })
15543        })
15544    }
15545
15546    fn resolve_completions(
15547        &self,
15548        buffer: Entity<Buffer>,
15549        completion_indices: Vec<usize>,
15550        completions: Rc<RefCell<Box<[Completion]>>>,
15551        cx: &mut Context<Editor>,
15552    ) -> Task<Result<bool>> {
15553        self.update(cx, |project, cx| {
15554            project.lsp_store().update(cx, |lsp_store, cx| {
15555                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15556            })
15557        })
15558    }
15559
15560    fn apply_additional_edits_for_completion(
15561        &self,
15562        buffer: Entity<Buffer>,
15563        completions: Rc<RefCell<Box<[Completion]>>>,
15564        completion_index: usize,
15565        push_to_history: bool,
15566        cx: &mut Context<Editor>,
15567    ) -> Task<Result<Option<language::Transaction>>> {
15568        self.update(cx, |project, cx| {
15569            project.lsp_store().update(cx, |lsp_store, cx| {
15570                lsp_store.apply_additional_edits_for_completion(
15571                    buffer,
15572                    completions,
15573                    completion_index,
15574                    push_to_history,
15575                    cx,
15576                )
15577            })
15578        })
15579    }
15580
15581    fn is_completion_trigger(
15582        &self,
15583        buffer: &Entity<Buffer>,
15584        position: language::Anchor,
15585        text: &str,
15586        trigger_in_words: bool,
15587        cx: &mut Context<Editor>,
15588    ) -> bool {
15589        let mut chars = text.chars();
15590        let char = if let Some(char) = chars.next() {
15591            char
15592        } else {
15593            return false;
15594        };
15595        if chars.next().is_some() {
15596            return false;
15597        }
15598
15599        let buffer = buffer.read(cx);
15600        let snapshot = buffer.snapshot();
15601        if !snapshot.settings_at(position, cx).show_completions_on_input {
15602            return false;
15603        }
15604        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15605        if trigger_in_words && classifier.is_word(char) {
15606            return true;
15607        }
15608
15609        buffer.completion_triggers().contains(text)
15610    }
15611}
15612
15613impl SemanticsProvider for Entity<Project> {
15614    fn hover(
15615        &self,
15616        buffer: &Entity<Buffer>,
15617        position: text::Anchor,
15618        cx: &mut App,
15619    ) -> Option<Task<Vec<project::Hover>>> {
15620        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15621    }
15622
15623    fn document_highlights(
15624        &self,
15625        buffer: &Entity<Buffer>,
15626        position: text::Anchor,
15627        cx: &mut App,
15628    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15629        Some(self.update(cx, |project, cx| {
15630            project.document_highlights(buffer, position, cx)
15631        }))
15632    }
15633
15634    fn definitions(
15635        &self,
15636        buffer: &Entity<Buffer>,
15637        position: text::Anchor,
15638        kind: GotoDefinitionKind,
15639        cx: &mut App,
15640    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15641        Some(self.update(cx, |project, cx| match kind {
15642            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15643            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15644            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15645            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15646        }))
15647    }
15648
15649    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15650        // TODO: make this work for remote projects
15651        self.read(cx)
15652            .language_servers_for_local_buffer(buffer.read(cx), cx)
15653            .any(
15654                |(_, server)| match server.capabilities().inlay_hint_provider {
15655                    Some(lsp::OneOf::Left(enabled)) => enabled,
15656                    Some(lsp::OneOf::Right(_)) => true,
15657                    None => false,
15658                },
15659            )
15660    }
15661
15662    fn inlay_hints(
15663        &self,
15664        buffer_handle: Entity<Buffer>,
15665        range: Range<text::Anchor>,
15666        cx: &mut App,
15667    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15668        Some(self.update(cx, |project, cx| {
15669            project.inlay_hints(buffer_handle, range, cx)
15670        }))
15671    }
15672
15673    fn resolve_inlay_hint(
15674        &self,
15675        hint: InlayHint,
15676        buffer_handle: Entity<Buffer>,
15677        server_id: LanguageServerId,
15678        cx: &mut App,
15679    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15680        Some(self.update(cx, |project, cx| {
15681            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15682        }))
15683    }
15684
15685    fn range_for_rename(
15686        &self,
15687        buffer: &Entity<Buffer>,
15688        position: text::Anchor,
15689        cx: &mut App,
15690    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15691        Some(self.update(cx, |project, cx| {
15692            let buffer = buffer.clone();
15693            let task = project.prepare_rename(buffer.clone(), position, cx);
15694            cx.spawn(|_, mut cx| async move {
15695                Ok(match task.await? {
15696                    PrepareRenameResponse::Success(range) => Some(range),
15697                    PrepareRenameResponse::InvalidPosition => None,
15698                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15699                        // Fallback on using TreeSitter info to determine identifier range
15700                        buffer.update(&mut cx, |buffer, _| {
15701                            let snapshot = buffer.snapshot();
15702                            let (range, kind) = snapshot.surrounding_word(position);
15703                            if kind != Some(CharKind::Word) {
15704                                return None;
15705                            }
15706                            Some(
15707                                snapshot.anchor_before(range.start)
15708                                    ..snapshot.anchor_after(range.end),
15709                            )
15710                        })?
15711                    }
15712                })
15713            })
15714        }))
15715    }
15716
15717    fn perform_rename(
15718        &self,
15719        buffer: &Entity<Buffer>,
15720        position: text::Anchor,
15721        new_name: String,
15722        cx: &mut App,
15723    ) -> Option<Task<Result<ProjectTransaction>>> {
15724        Some(self.update(cx, |project, cx| {
15725            project.perform_rename(buffer.clone(), position, new_name, cx)
15726        }))
15727    }
15728}
15729
15730fn inlay_hint_settings(
15731    location: Anchor,
15732    snapshot: &MultiBufferSnapshot,
15733    cx: &mut Context<Editor>,
15734) -> InlayHintSettings {
15735    let file = snapshot.file_at(location);
15736    let language = snapshot.language_at(location).map(|l| l.name());
15737    language_settings(language, file, cx).inlay_hints
15738}
15739
15740fn consume_contiguous_rows(
15741    contiguous_row_selections: &mut Vec<Selection<Point>>,
15742    selection: &Selection<Point>,
15743    display_map: &DisplaySnapshot,
15744    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15745) -> (MultiBufferRow, MultiBufferRow) {
15746    contiguous_row_selections.push(selection.clone());
15747    let start_row = MultiBufferRow(selection.start.row);
15748    let mut end_row = ending_row(selection, display_map);
15749
15750    while let Some(next_selection) = selections.peek() {
15751        if next_selection.start.row <= end_row.0 {
15752            end_row = ending_row(next_selection, display_map);
15753            contiguous_row_selections.push(selections.next().unwrap().clone());
15754        } else {
15755            break;
15756        }
15757    }
15758    (start_row, end_row)
15759}
15760
15761fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15762    if next_selection.end.column > 0 || next_selection.is_empty() {
15763        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15764    } else {
15765        MultiBufferRow(next_selection.end.row)
15766    }
15767}
15768
15769impl EditorSnapshot {
15770    pub fn remote_selections_in_range<'a>(
15771        &'a self,
15772        range: &'a Range<Anchor>,
15773        collaboration_hub: &dyn CollaborationHub,
15774        cx: &'a App,
15775    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15776        let participant_names = collaboration_hub.user_names(cx);
15777        let participant_indices = collaboration_hub.user_participant_indices(cx);
15778        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15779        let collaborators_by_replica_id = collaborators_by_peer_id
15780            .iter()
15781            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15782            .collect::<HashMap<_, _>>();
15783        self.buffer_snapshot
15784            .selections_in_range(range, false)
15785            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15786                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15787                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15788                let user_name = participant_names.get(&collaborator.user_id).cloned();
15789                Some(RemoteSelection {
15790                    replica_id,
15791                    selection,
15792                    cursor_shape,
15793                    line_mode,
15794                    participant_index,
15795                    peer_id: collaborator.peer_id,
15796                    user_name,
15797                })
15798            })
15799    }
15800
15801    pub fn hunks_for_ranges(
15802        &self,
15803        ranges: impl Iterator<Item = Range<Point>>,
15804    ) -> Vec<MultiBufferDiffHunk> {
15805        let mut hunks = Vec::new();
15806        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15807            HashMap::default();
15808        for query_range in ranges {
15809            let query_rows =
15810                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15811            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15812                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15813            ) {
15814                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15815                // when the caret is just above or just below the deleted hunk.
15816                let allow_adjacent = hunk.status().is_removed();
15817                let related_to_selection = if allow_adjacent {
15818                    hunk.row_range.overlaps(&query_rows)
15819                        || hunk.row_range.start == query_rows.end
15820                        || hunk.row_range.end == query_rows.start
15821                } else {
15822                    hunk.row_range.overlaps(&query_rows)
15823                };
15824                if related_to_selection {
15825                    if !processed_buffer_rows
15826                        .entry(hunk.buffer_id)
15827                        .or_default()
15828                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15829                    {
15830                        continue;
15831                    }
15832                    hunks.push(hunk);
15833                }
15834            }
15835        }
15836
15837        hunks
15838    }
15839
15840    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15841        self.display_snapshot.buffer_snapshot.language_at(position)
15842    }
15843
15844    pub fn is_focused(&self) -> bool {
15845        self.is_focused
15846    }
15847
15848    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15849        self.placeholder_text.as_ref()
15850    }
15851
15852    pub fn scroll_position(&self) -> gpui::Point<f32> {
15853        self.scroll_anchor.scroll_position(&self.display_snapshot)
15854    }
15855
15856    fn gutter_dimensions(
15857        &self,
15858        font_id: FontId,
15859        font_size: Pixels,
15860        max_line_number_width: Pixels,
15861        cx: &App,
15862    ) -> Option<GutterDimensions> {
15863        if !self.show_gutter {
15864            return None;
15865        }
15866
15867        let descent = cx.text_system().descent(font_id, font_size);
15868        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15869        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15870
15871        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15872            matches!(
15873                ProjectSettings::get_global(cx).git.git_gutter,
15874                Some(GitGutterSetting::TrackedFiles)
15875            )
15876        });
15877        let gutter_settings = EditorSettings::get_global(cx).gutter;
15878        let show_line_numbers = self
15879            .show_line_numbers
15880            .unwrap_or(gutter_settings.line_numbers);
15881        let line_gutter_width = if show_line_numbers {
15882            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15883            let min_width_for_number_on_gutter = em_advance * 4.0;
15884            max_line_number_width.max(min_width_for_number_on_gutter)
15885        } else {
15886            0.0.into()
15887        };
15888
15889        let show_code_actions = self
15890            .show_code_actions
15891            .unwrap_or(gutter_settings.code_actions);
15892
15893        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15894
15895        let git_blame_entries_width =
15896            self.git_blame_gutter_max_author_length
15897                .map(|max_author_length| {
15898                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15899
15900                    /// The number of characters to dedicate to gaps and margins.
15901                    const SPACING_WIDTH: usize = 4;
15902
15903                    let max_char_count = max_author_length
15904                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15905                        + ::git::SHORT_SHA_LENGTH
15906                        + MAX_RELATIVE_TIMESTAMP.len()
15907                        + SPACING_WIDTH;
15908
15909                    em_advance * max_char_count
15910                });
15911
15912        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15913        left_padding += if show_code_actions || show_runnables {
15914            em_width * 3.0
15915        } else if show_git_gutter && show_line_numbers {
15916            em_width * 2.0
15917        } else if show_git_gutter || show_line_numbers {
15918            em_width
15919        } else {
15920            px(0.)
15921        };
15922
15923        let right_padding = if gutter_settings.folds && show_line_numbers {
15924            em_width * 4.0
15925        } else if gutter_settings.folds {
15926            em_width * 3.0
15927        } else if show_line_numbers {
15928            em_width
15929        } else {
15930            px(0.)
15931        };
15932
15933        Some(GutterDimensions {
15934            left_padding,
15935            right_padding,
15936            width: line_gutter_width + left_padding + right_padding,
15937            margin: -descent,
15938            git_blame_entries_width,
15939        })
15940    }
15941
15942    pub fn render_crease_toggle(
15943        &self,
15944        buffer_row: MultiBufferRow,
15945        row_contains_cursor: bool,
15946        editor: Entity<Editor>,
15947        window: &mut Window,
15948        cx: &mut App,
15949    ) -> Option<AnyElement> {
15950        let folded = self.is_line_folded(buffer_row);
15951        let mut is_foldable = false;
15952
15953        if let Some(crease) = self
15954            .crease_snapshot
15955            .query_row(buffer_row, &self.buffer_snapshot)
15956        {
15957            is_foldable = true;
15958            match crease {
15959                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15960                    if let Some(render_toggle) = render_toggle {
15961                        let toggle_callback =
15962                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15963                                if folded {
15964                                    editor.update(cx, |editor, cx| {
15965                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15966                                    });
15967                                } else {
15968                                    editor.update(cx, |editor, cx| {
15969                                        editor.unfold_at(
15970                                            &crate::UnfoldAt { buffer_row },
15971                                            window,
15972                                            cx,
15973                                        )
15974                                    });
15975                                }
15976                            });
15977                        return Some((render_toggle)(
15978                            buffer_row,
15979                            folded,
15980                            toggle_callback,
15981                            window,
15982                            cx,
15983                        ));
15984                    }
15985                }
15986            }
15987        }
15988
15989        is_foldable |= self.starts_indent(buffer_row);
15990
15991        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15992            Some(
15993                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15994                    .toggle_state(folded)
15995                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15996                        if folded {
15997                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15998                        } else {
15999                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16000                        }
16001                    }))
16002                    .into_any_element(),
16003            )
16004        } else {
16005            None
16006        }
16007    }
16008
16009    pub fn render_crease_trailer(
16010        &self,
16011        buffer_row: MultiBufferRow,
16012        window: &mut Window,
16013        cx: &mut App,
16014    ) -> Option<AnyElement> {
16015        let folded = self.is_line_folded(buffer_row);
16016        if let Crease::Inline { render_trailer, .. } = self
16017            .crease_snapshot
16018            .query_row(buffer_row, &self.buffer_snapshot)?
16019        {
16020            let render_trailer = render_trailer.as_ref()?;
16021            Some(render_trailer(buffer_row, folded, window, cx))
16022        } else {
16023            None
16024        }
16025    }
16026}
16027
16028impl Deref for EditorSnapshot {
16029    type Target = DisplaySnapshot;
16030
16031    fn deref(&self) -> &Self::Target {
16032        &self.display_snapshot
16033    }
16034}
16035
16036#[derive(Clone, Debug, PartialEq, Eq)]
16037pub enum EditorEvent {
16038    InputIgnored {
16039        text: Arc<str>,
16040    },
16041    InputHandled {
16042        utf16_range_to_replace: Option<Range<isize>>,
16043        text: Arc<str>,
16044    },
16045    ExcerptsAdded {
16046        buffer: Entity<Buffer>,
16047        predecessor: ExcerptId,
16048        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16049    },
16050    ExcerptsRemoved {
16051        ids: Vec<ExcerptId>,
16052    },
16053    BufferFoldToggled {
16054        ids: Vec<ExcerptId>,
16055        folded: bool,
16056    },
16057    ExcerptsEdited {
16058        ids: Vec<ExcerptId>,
16059    },
16060    ExcerptsExpanded {
16061        ids: Vec<ExcerptId>,
16062    },
16063    BufferEdited,
16064    Edited {
16065        transaction_id: clock::Lamport,
16066    },
16067    Reparsed(BufferId),
16068    Focused,
16069    FocusedIn,
16070    Blurred,
16071    DirtyChanged,
16072    Saved,
16073    TitleChanged,
16074    DiffBaseChanged,
16075    SelectionsChanged {
16076        local: bool,
16077    },
16078    ScrollPositionChanged {
16079        local: bool,
16080        autoscroll: bool,
16081    },
16082    Closed,
16083    TransactionUndone {
16084        transaction_id: clock::Lamport,
16085    },
16086    TransactionBegun {
16087        transaction_id: clock::Lamport,
16088    },
16089    Reloaded,
16090    CursorShapeChanged,
16091}
16092
16093impl EventEmitter<EditorEvent> for Editor {}
16094
16095impl Focusable for Editor {
16096    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16097        self.focus_handle.clone()
16098    }
16099}
16100
16101impl Render for Editor {
16102    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16103        let settings = ThemeSettings::get_global(cx);
16104
16105        let mut text_style = match self.mode {
16106            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16107                color: cx.theme().colors().editor_foreground,
16108                font_family: settings.ui_font.family.clone(),
16109                font_features: settings.ui_font.features.clone(),
16110                font_fallbacks: settings.ui_font.fallbacks.clone(),
16111                font_size: rems(0.875).into(),
16112                font_weight: settings.ui_font.weight,
16113                line_height: relative(settings.buffer_line_height.value()),
16114                ..Default::default()
16115            },
16116            EditorMode::Full => TextStyle {
16117                color: cx.theme().colors().editor_foreground,
16118                font_family: settings.buffer_font.family.clone(),
16119                font_features: settings.buffer_font.features.clone(),
16120                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16121                font_size: settings.buffer_font_size().into(),
16122                font_weight: settings.buffer_font.weight,
16123                line_height: relative(settings.buffer_line_height.value()),
16124                ..Default::default()
16125            },
16126        };
16127        if let Some(text_style_refinement) = &self.text_style_refinement {
16128            text_style.refine(text_style_refinement)
16129        }
16130
16131        let background = match self.mode {
16132            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16133            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16134            EditorMode::Full => cx.theme().colors().editor_background,
16135        };
16136
16137        EditorElement::new(
16138            &cx.entity(),
16139            EditorStyle {
16140                background,
16141                local_player: cx.theme().players().local(),
16142                text: text_style,
16143                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16144                syntax: cx.theme().syntax().clone(),
16145                status: cx.theme().status().clone(),
16146                inlay_hints_style: make_inlay_hints_style(cx),
16147                inline_completion_styles: make_suggestion_styles(cx),
16148                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16149            },
16150        )
16151    }
16152}
16153
16154impl EntityInputHandler for Editor {
16155    fn text_for_range(
16156        &mut self,
16157        range_utf16: Range<usize>,
16158        adjusted_range: &mut Option<Range<usize>>,
16159        _: &mut Window,
16160        cx: &mut Context<Self>,
16161    ) -> Option<String> {
16162        let snapshot = self.buffer.read(cx).read(cx);
16163        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16164        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16165        if (start.0..end.0) != range_utf16 {
16166            adjusted_range.replace(start.0..end.0);
16167        }
16168        Some(snapshot.text_for_range(start..end).collect())
16169    }
16170
16171    fn selected_text_range(
16172        &mut self,
16173        ignore_disabled_input: bool,
16174        _: &mut Window,
16175        cx: &mut Context<Self>,
16176    ) -> Option<UTF16Selection> {
16177        // Prevent the IME menu from appearing when holding down an alphabetic key
16178        // while input is disabled.
16179        if !ignore_disabled_input && !self.input_enabled {
16180            return None;
16181        }
16182
16183        let selection = self.selections.newest::<OffsetUtf16>(cx);
16184        let range = selection.range();
16185
16186        Some(UTF16Selection {
16187            range: range.start.0..range.end.0,
16188            reversed: selection.reversed,
16189        })
16190    }
16191
16192    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16193        let snapshot = self.buffer.read(cx).read(cx);
16194        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16195        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16196    }
16197
16198    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16199        self.clear_highlights::<InputComposition>(cx);
16200        self.ime_transaction.take();
16201    }
16202
16203    fn replace_text_in_range(
16204        &mut self,
16205        range_utf16: Option<Range<usize>>,
16206        text: &str,
16207        window: &mut Window,
16208        cx: &mut Context<Self>,
16209    ) {
16210        if !self.input_enabled {
16211            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16212            return;
16213        }
16214
16215        self.transact(window, cx, |this, window, cx| {
16216            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16217                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16218                Some(this.selection_replacement_ranges(range_utf16, cx))
16219            } else {
16220                this.marked_text_ranges(cx)
16221            };
16222
16223            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16224                let newest_selection_id = this.selections.newest_anchor().id;
16225                this.selections
16226                    .all::<OffsetUtf16>(cx)
16227                    .iter()
16228                    .zip(ranges_to_replace.iter())
16229                    .find_map(|(selection, range)| {
16230                        if selection.id == newest_selection_id {
16231                            Some(
16232                                (range.start.0 as isize - selection.head().0 as isize)
16233                                    ..(range.end.0 as isize - selection.head().0 as isize),
16234                            )
16235                        } else {
16236                            None
16237                        }
16238                    })
16239            });
16240
16241            cx.emit(EditorEvent::InputHandled {
16242                utf16_range_to_replace: range_to_replace,
16243                text: text.into(),
16244            });
16245
16246            if let Some(new_selected_ranges) = new_selected_ranges {
16247                this.change_selections(None, window, cx, |selections| {
16248                    selections.select_ranges(new_selected_ranges)
16249                });
16250                this.backspace(&Default::default(), window, cx);
16251            }
16252
16253            this.handle_input(text, window, cx);
16254        });
16255
16256        if let Some(transaction) = self.ime_transaction {
16257            self.buffer.update(cx, |buffer, cx| {
16258                buffer.group_until_transaction(transaction, cx);
16259            });
16260        }
16261
16262        self.unmark_text(window, cx);
16263    }
16264
16265    fn replace_and_mark_text_in_range(
16266        &mut self,
16267        range_utf16: Option<Range<usize>>,
16268        text: &str,
16269        new_selected_range_utf16: Option<Range<usize>>,
16270        window: &mut Window,
16271        cx: &mut Context<Self>,
16272    ) {
16273        if !self.input_enabled {
16274            return;
16275        }
16276
16277        let transaction = self.transact(window, cx, |this, window, cx| {
16278            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16279                let snapshot = this.buffer.read(cx).read(cx);
16280                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16281                    for marked_range in &mut marked_ranges {
16282                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16283                        marked_range.start.0 += relative_range_utf16.start;
16284                        marked_range.start =
16285                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16286                        marked_range.end =
16287                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16288                    }
16289                }
16290                Some(marked_ranges)
16291            } else if let Some(range_utf16) = range_utf16 {
16292                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16293                Some(this.selection_replacement_ranges(range_utf16, cx))
16294            } else {
16295                None
16296            };
16297
16298            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16299                let newest_selection_id = this.selections.newest_anchor().id;
16300                this.selections
16301                    .all::<OffsetUtf16>(cx)
16302                    .iter()
16303                    .zip(ranges_to_replace.iter())
16304                    .find_map(|(selection, range)| {
16305                        if selection.id == newest_selection_id {
16306                            Some(
16307                                (range.start.0 as isize - selection.head().0 as isize)
16308                                    ..(range.end.0 as isize - selection.head().0 as isize),
16309                            )
16310                        } else {
16311                            None
16312                        }
16313                    })
16314            });
16315
16316            cx.emit(EditorEvent::InputHandled {
16317                utf16_range_to_replace: range_to_replace,
16318                text: text.into(),
16319            });
16320
16321            if let Some(ranges) = ranges_to_replace {
16322                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16323            }
16324
16325            let marked_ranges = {
16326                let snapshot = this.buffer.read(cx).read(cx);
16327                this.selections
16328                    .disjoint_anchors()
16329                    .iter()
16330                    .map(|selection| {
16331                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16332                    })
16333                    .collect::<Vec<_>>()
16334            };
16335
16336            if text.is_empty() {
16337                this.unmark_text(window, cx);
16338            } else {
16339                this.highlight_text::<InputComposition>(
16340                    marked_ranges.clone(),
16341                    HighlightStyle {
16342                        underline: Some(UnderlineStyle {
16343                            thickness: px(1.),
16344                            color: None,
16345                            wavy: false,
16346                        }),
16347                        ..Default::default()
16348                    },
16349                    cx,
16350                );
16351            }
16352
16353            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16354            let use_autoclose = this.use_autoclose;
16355            let use_auto_surround = this.use_auto_surround;
16356            this.set_use_autoclose(false);
16357            this.set_use_auto_surround(false);
16358            this.handle_input(text, window, cx);
16359            this.set_use_autoclose(use_autoclose);
16360            this.set_use_auto_surround(use_auto_surround);
16361
16362            if let Some(new_selected_range) = new_selected_range_utf16 {
16363                let snapshot = this.buffer.read(cx).read(cx);
16364                let new_selected_ranges = marked_ranges
16365                    .into_iter()
16366                    .map(|marked_range| {
16367                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16368                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16369                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16370                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16371                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16372                    })
16373                    .collect::<Vec<_>>();
16374
16375                drop(snapshot);
16376                this.change_selections(None, window, cx, |selections| {
16377                    selections.select_ranges(new_selected_ranges)
16378                });
16379            }
16380        });
16381
16382        self.ime_transaction = self.ime_transaction.or(transaction);
16383        if let Some(transaction) = self.ime_transaction {
16384            self.buffer.update(cx, |buffer, cx| {
16385                buffer.group_until_transaction(transaction, cx);
16386            });
16387        }
16388
16389        if self.text_highlights::<InputComposition>(cx).is_none() {
16390            self.ime_transaction.take();
16391        }
16392    }
16393
16394    fn bounds_for_range(
16395        &mut self,
16396        range_utf16: Range<usize>,
16397        element_bounds: gpui::Bounds<Pixels>,
16398        window: &mut Window,
16399        cx: &mut Context<Self>,
16400    ) -> Option<gpui::Bounds<Pixels>> {
16401        let text_layout_details = self.text_layout_details(window);
16402        let gpui::Size {
16403            width: em_width,
16404            height: line_height,
16405        } = self.character_size(window);
16406
16407        let snapshot = self.snapshot(window, cx);
16408        let scroll_position = snapshot.scroll_position();
16409        let scroll_left = scroll_position.x * em_width;
16410
16411        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16412        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16413            + self.gutter_dimensions.width
16414            + self.gutter_dimensions.margin;
16415        let y = line_height * (start.row().as_f32() - scroll_position.y);
16416
16417        Some(Bounds {
16418            origin: element_bounds.origin + point(x, y),
16419            size: size(em_width, line_height),
16420        })
16421    }
16422
16423    fn character_index_for_point(
16424        &mut self,
16425        point: gpui::Point<Pixels>,
16426        _window: &mut Window,
16427        _cx: &mut Context<Self>,
16428    ) -> Option<usize> {
16429        let position_map = self.last_position_map.as_ref()?;
16430        if !position_map.text_hitbox.contains(&point) {
16431            return None;
16432        }
16433        let display_point = position_map.point_for_position(point).previous_valid;
16434        let anchor = position_map
16435            .snapshot
16436            .display_point_to_anchor(display_point, Bias::Left);
16437        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16438        Some(utf16_offset.0)
16439    }
16440}
16441
16442trait SelectionExt {
16443    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16444    fn spanned_rows(
16445        &self,
16446        include_end_if_at_line_start: bool,
16447        map: &DisplaySnapshot,
16448    ) -> Range<MultiBufferRow>;
16449}
16450
16451impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16452    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16453        let start = self
16454            .start
16455            .to_point(&map.buffer_snapshot)
16456            .to_display_point(map);
16457        let end = self
16458            .end
16459            .to_point(&map.buffer_snapshot)
16460            .to_display_point(map);
16461        if self.reversed {
16462            end..start
16463        } else {
16464            start..end
16465        }
16466    }
16467
16468    fn spanned_rows(
16469        &self,
16470        include_end_if_at_line_start: bool,
16471        map: &DisplaySnapshot,
16472    ) -> Range<MultiBufferRow> {
16473        let start = self.start.to_point(&map.buffer_snapshot);
16474        let mut end = self.end.to_point(&map.buffer_snapshot);
16475        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16476            end.row -= 1;
16477        }
16478
16479        let buffer_start = map.prev_line_boundary(start).0;
16480        let buffer_end = map.next_line_boundary(end).0;
16481        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16482    }
16483}
16484
16485impl<T: InvalidationRegion> InvalidationStack<T> {
16486    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16487    where
16488        S: Clone + ToOffset,
16489    {
16490        while let Some(region) = self.last() {
16491            let all_selections_inside_invalidation_ranges =
16492                if selections.len() == region.ranges().len() {
16493                    selections
16494                        .iter()
16495                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16496                        .all(|(selection, invalidation_range)| {
16497                            let head = selection.head().to_offset(buffer);
16498                            invalidation_range.start <= head && invalidation_range.end >= head
16499                        })
16500                } else {
16501                    false
16502                };
16503
16504            if all_selections_inside_invalidation_ranges {
16505                break;
16506            } else {
16507                self.pop();
16508            }
16509        }
16510    }
16511}
16512
16513impl<T> Default for InvalidationStack<T> {
16514    fn default() -> Self {
16515        Self(Default::default())
16516    }
16517}
16518
16519impl<T> Deref for InvalidationStack<T> {
16520    type Target = Vec<T>;
16521
16522    fn deref(&self) -> &Self::Target {
16523        &self.0
16524    }
16525}
16526
16527impl<T> DerefMut for InvalidationStack<T> {
16528    fn deref_mut(&mut self) -> &mut Self::Target {
16529        &mut self.0
16530    }
16531}
16532
16533impl InvalidationRegion for SnippetState {
16534    fn ranges(&self) -> &[Range<Anchor>] {
16535        &self.ranges[self.active_index]
16536    }
16537}
16538
16539pub fn diagnostic_block_renderer(
16540    diagnostic: Diagnostic,
16541    max_message_rows: Option<u8>,
16542    allow_closing: bool,
16543    _is_valid: bool,
16544) -> RenderBlock {
16545    let (text_without_backticks, code_ranges) =
16546        highlight_diagnostic_message(&diagnostic, max_message_rows);
16547
16548    Arc::new(move |cx: &mut BlockContext| {
16549        let group_id: SharedString = cx.block_id.to_string().into();
16550
16551        let mut text_style = cx.window.text_style().clone();
16552        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16553        let theme_settings = ThemeSettings::get_global(cx);
16554        text_style.font_family = theme_settings.buffer_font.family.clone();
16555        text_style.font_style = theme_settings.buffer_font.style;
16556        text_style.font_features = theme_settings.buffer_font.features.clone();
16557        text_style.font_weight = theme_settings.buffer_font.weight;
16558
16559        let multi_line_diagnostic = diagnostic.message.contains('\n');
16560
16561        let buttons = |diagnostic: &Diagnostic| {
16562            if multi_line_diagnostic {
16563                v_flex()
16564            } else {
16565                h_flex()
16566            }
16567            .when(allow_closing, |div| {
16568                div.children(diagnostic.is_primary.then(|| {
16569                    IconButton::new("close-block", IconName::XCircle)
16570                        .icon_color(Color::Muted)
16571                        .size(ButtonSize::Compact)
16572                        .style(ButtonStyle::Transparent)
16573                        .visible_on_hover(group_id.clone())
16574                        .on_click(move |_click, window, cx| {
16575                            window.dispatch_action(Box::new(Cancel), cx)
16576                        })
16577                        .tooltip(|window, cx| {
16578                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16579                        })
16580                }))
16581            })
16582            .child(
16583                IconButton::new("copy-block", IconName::Copy)
16584                    .icon_color(Color::Muted)
16585                    .size(ButtonSize::Compact)
16586                    .style(ButtonStyle::Transparent)
16587                    .visible_on_hover(group_id.clone())
16588                    .on_click({
16589                        let message = diagnostic.message.clone();
16590                        move |_click, _, cx| {
16591                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16592                        }
16593                    })
16594                    .tooltip(Tooltip::text("Copy diagnostic message")),
16595            )
16596        };
16597
16598        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16599            AvailableSpace::min_size(),
16600            cx.window,
16601            cx.app,
16602        );
16603
16604        h_flex()
16605            .id(cx.block_id)
16606            .group(group_id.clone())
16607            .relative()
16608            .size_full()
16609            .block_mouse_down()
16610            .pl(cx.gutter_dimensions.width)
16611            .w(cx.max_width - cx.gutter_dimensions.full_width())
16612            .child(
16613                div()
16614                    .flex()
16615                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16616                    .flex_shrink(),
16617            )
16618            .child(buttons(&diagnostic))
16619            .child(div().flex().flex_shrink_0().child(
16620                StyledText::new(text_without_backticks.clone()).with_highlights(
16621                    &text_style,
16622                    code_ranges.iter().map(|range| {
16623                        (
16624                            range.clone(),
16625                            HighlightStyle {
16626                                font_weight: Some(FontWeight::BOLD),
16627                                ..Default::default()
16628                            },
16629                        )
16630                    }),
16631                ),
16632            ))
16633            .into_any_element()
16634    })
16635}
16636
16637fn inline_completion_edit_text(
16638    current_snapshot: &BufferSnapshot,
16639    edits: &[(Range<Anchor>, String)],
16640    edit_preview: &EditPreview,
16641    include_deletions: bool,
16642    cx: &App,
16643) -> HighlightedText {
16644    let edits = edits
16645        .iter()
16646        .map(|(anchor, text)| {
16647            (
16648                anchor.start.text_anchor..anchor.end.text_anchor,
16649                text.clone(),
16650            )
16651        })
16652        .collect::<Vec<_>>();
16653
16654    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16655}
16656
16657pub fn highlight_diagnostic_message(
16658    diagnostic: &Diagnostic,
16659    mut max_message_rows: Option<u8>,
16660) -> (SharedString, Vec<Range<usize>>) {
16661    let mut text_without_backticks = String::new();
16662    let mut code_ranges = Vec::new();
16663
16664    if let Some(source) = &diagnostic.source {
16665        text_without_backticks.push_str(source);
16666        code_ranges.push(0..source.len());
16667        text_without_backticks.push_str(": ");
16668    }
16669
16670    let mut prev_offset = 0;
16671    let mut in_code_block = false;
16672    let has_row_limit = max_message_rows.is_some();
16673    let mut newline_indices = diagnostic
16674        .message
16675        .match_indices('\n')
16676        .filter(|_| has_row_limit)
16677        .map(|(ix, _)| ix)
16678        .fuse()
16679        .peekable();
16680
16681    for (quote_ix, _) in diagnostic
16682        .message
16683        .match_indices('`')
16684        .chain([(diagnostic.message.len(), "")])
16685    {
16686        let mut first_newline_ix = None;
16687        let mut last_newline_ix = None;
16688        while let Some(newline_ix) = newline_indices.peek() {
16689            if *newline_ix < quote_ix {
16690                if first_newline_ix.is_none() {
16691                    first_newline_ix = Some(*newline_ix);
16692                }
16693                last_newline_ix = Some(*newline_ix);
16694
16695                if let Some(rows_left) = &mut max_message_rows {
16696                    if *rows_left == 0 {
16697                        break;
16698                    } else {
16699                        *rows_left -= 1;
16700                    }
16701                }
16702                let _ = newline_indices.next();
16703            } else {
16704                break;
16705            }
16706        }
16707        let prev_len = text_without_backticks.len();
16708        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16709        text_without_backticks.push_str(new_text);
16710        if in_code_block {
16711            code_ranges.push(prev_len..text_without_backticks.len());
16712        }
16713        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16714        in_code_block = !in_code_block;
16715        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16716            text_without_backticks.push_str("...");
16717            break;
16718        }
16719    }
16720
16721    (text_without_backticks.into(), code_ranges)
16722}
16723
16724fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16725    match severity {
16726        DiagnosticSeverity::ERROR => colors.error,
16727        DiagnosticSeverity::WARNING => colors.warning,
16728        DiagnosticSeverity::INFORMATION => colors.info,
16729        DiagnosticSeverity::HINT => colors.info,
16730        _ => colors.ignored,
16731    }
16732}
16733
16734pub fn styled_runs_for_code_label<'a>(
16735    label: &'a CodeLabel,
16736    syntax_theme: &'a theme::SyntaxTheme,
16737) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16738    let fade_out = HighlightStyle {
16739        fade_out: Some(0.35),
16740        ..Default::default()
16741    };
16742
16743    let mut prev_end = label.filter_range.end;
16744    label
16745        .runs
16746        .iter()
16747        .enumerate()
16748        .flat_map(move |(ix, (range, highlight_id))| {
16749            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16750                style
16751            } else {
16752                return Default::default();
16753            };
16754            let mut muted_style = style;
16755            muted_style.highlight(fade_out);
16756
16757            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16758            if range.start >= label.filter_range.end {
16759                if range.start > prev_end {
16760                    runs.push((prev_end..range.start, fade_out));
16761                }
16762                runs.push((range.clone(), muted_style));
16763            } else if range.end <= label.filter_range.end {
16764                runs.push((range.clone(), style));
16765            } else {
16766                runs.push((range.start..label.filter_range.end, style));
16767                runs.push((label.filter_range.end..range.end, muted_style));
16768            }
16769            prev_end = cmp::max(prev_end, range.end);
16770
16771            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16772                runs.push((prev_end..label.text.len(), fade_out));
16773            }
16774
16775            runs
16776        })
16777}
16778
16779pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16780    let mut prev_index = 0;
16781    let mut prev_codepoint: Option<char> = None;
16782    text.char_indices()
16783        .chain([(text.len(), '\0')])
16784        .filter_map(move |(index, codepoint)| {
16785            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16786            let is_boundary = index == text.len()
16787                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16788                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16789            if is_boundary {
16790                let chunk = &text[prev_index..index];
16791                prev_index = index;
16792                Some(chunk)
16793            } else {
16794                None
16795            }
16796        })
16797}
16798
16799pub trait RangeToAnchorExt: Sized {
16800    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16801
16802    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16803        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16804        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16805    }
16806}
16807
16808impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16809    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16810        let start_offset = self.start.to_offset(snapshot);
16811        let end_offset = self.end.to_offset(snapshot);
16812        if start_offset == end_offset {
16813            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16814        } else {
16815            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16816        }
16817    }
16818}
16819
16820pub trait RowExt {
16821    fn as_f32(&self) -> f32;
16822
16823    fn next_row(&self) -> Self;
16824
16825    fn previous_row(&self) -> Self;
16826
16827    fn minus(&self, other: Self) -> u32;
16828}
16829
16830impl RowExt for DisplayRow {
16831    fn as_f32(&self) -> f32 {
16832        self.0 as f32
16833    }
16834
16835    fn next_row(&self) -> Self {
16836        Self(self.0 + 1)
16837    }
16838
16839    fn previous_row(&self) -> Self {
16840        Self(self.0.saturating_sub(1))
16841    }
16842
16843    fn minus(&self, other: Self) -> u32 {
16844        self.0 - other.0
16845    }
16846}
16847
16848impl RowExt for MultiBufferRow {
16849    fn as_f32(&self) -> f32 {
16850        self.0 as f32
16851    }
16852
16853    fn next_row(&self) -> Self {
16854        Self(self.0 + 1)
16855    }
16856
16857    fn previous_row(&self) -> Self {
16858        Self(self.0.saturating_sub(1))
16859    }
16860
16861    fn minus(&self, other: Self) -> u32 {
16862        self.0 - other.0
16863    }
16864}
16865
16866trait RowRangeExt {
16867    type Row;
16868
16869    fn len(&self) -> usize;
16870
16871    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16872}
16873
16874impl RowRangeExt for Range<MultiBufferRow> {
16875    type Row = MultiBufferRow;
16876
16877    fn len(&self) -> usize {
16878        (self.end.0 - self.start.0) as usize
16879    }
16880
16881    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16882        (self.start.0..self.end.0).map(MultiBufferRow)
16883    }
16884}
16885
16886impl RowRangeExt for Range<DisplayRow> {
16887    type Row = DisplayRow;
16888
16889    fn len(&self) -> usize {
16890        (self.end.0 - self.start.0) as usize
16891    }
16892
16893    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16894        (self.start.0..self.end.0).map(DisplayRow)
16895    }
16896}
16897
16898/// If select range has more than one line, we
16899/// just point the cursor to range.start.
16900fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16901    if range.start.row == range.end.row {
16902        range
16903    } else {
16904        range.start..range.start
16905    }
16906}
16907pub struct KillRing(ClipboardItem);
16908impl Global for KillRing {}
16909
16910const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16911
16912fn all_edits_insertions_or_deletions(
16913    edits: &Vec<(Range<Anchor>, String)>,
16914    snapshot: &MultiBufferSnapshot,
16915) -> bool {
16916    let mut all_insertions = true;
16917    let mut all_deletions = true;
16918
16919    for (range, new_text) in edits.iter() {
16920        let range_is_empty = range.to_offset(&snapshot).is_empty();
16921        let text_is_empty = new_text.is_empty();
16922
16923        if range_is_empty != text_is_empty {
16924            if range_is_empty {
16925                all_deletions = false;
16926            } else {
16927                all_insertions = false;
16928            }
16929        } else {
16930            return false;
16931        }
16932
16933        if !all_insertions && !all_deletions {
16934            return false;
16935        }
16936    }
16937    all_insertions || all_deletions
16938}