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::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use code_context_menus::{
   77    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   78    CompletionsMenu, ContextMenuOrigin,
   79};
   80use git::blame::GitBlame;
   81use gpui::{
   82    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   83    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   84    ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
   85    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   86    HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
   87    PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
   88    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   89    WeakEntity, WeakFocusHandle, Window,
   90};
   91use highlight_matching_bracket::refresh_matching_bracket_highlights;
   92use hover_popover::{hide_hover, HoverState};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview, HighlightedText,
  103    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  104    TransactionId, TreeSitterOptions,
  105};
  106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  107use linked_editing_ranges::refresh_linked_ranges;
  108use mouse_context_menu::MouseContextMenu;
  109use persistence::DB;
  110pub use proposed_changes_editor::{
  111    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  112};
  113use similar::{ChangeTag, TextDiff};
  114use std::iter::Peekable;
  115use task::{ResolvedTask, TaskTemplate, TaskVariables};
  116
  117use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  118pub use lsp::CompletionContext;
  119use lsp::{
  120    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  121    LanguageServerId, LanguageServerName,
  122};
  123
  124use language::BufferSnapshot;
  125use movement::TextLayoutDetails;
  126pub use multi_buffer::{
  127    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  128    ToOffset, ToPoint,
  129};
  130use multi_buffer::{
  131    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  132    ToOffsetUtf16,
  133};
  134use project::{
  135    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  136    project_settings::{GitGutterSetting, ProjectSettings},
  137    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  138    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  139};
  140use rand::prelude::*;
  141use rpc::{proto::*, ErrorExt};
  142use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  143use selections_collection::{
  144    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  145};
  146use serde::{Deserialize, Serialize};
  147use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  148use smallvec::SmallVec;
  149use snippet::Snippet;
  150use std::{
  151    any::TypeId,
  152    borrow::Cow,
  153    cell::RefCell,
  154    cmp::{self, Ordering, Reverse},
  155    mem,
  156    num::NonZeroU32,
  157    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  158    path::{Path, PathBuf},
  159    rc::Rc,
  160    sync::Arc,
  161    time::{Duration, Instant},
  162};
  163pub use sum_tree::Bias;
  164use sum_tree::TreeMap;
  165use text::{BufferId, OffsetUtf16, Rope};
  166use theme::{
  167    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  168    ThemeColors, ThemeSettings,
  169};
  170use ui::{
  171    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  172    Tooltip,
  173};
  174use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  175use workspace::{
  176    item::{ItemHandle, PreviewTabsSettings},
  177    ItemId, RestoreOnStartupBehavior,
  178};
  179use workspace::{
  180    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  181    WorkspaceSettings,
  182};
  183use workspace::{
  184    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  185};
  186use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  187
  188use crate::hover_links::{find_url, find_url_from_range};
  189use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  190
  191pub const FILE_HEADER_HEIGHT: u32 = 2;
  192pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  193pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  194pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  195const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  196const MAX_LINE_LEN: usize = 1024;
  197const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  198const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  199pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  200#[doc(hidden)]
  201pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  202
  203pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  204pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  205
  206pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  207pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  208
  209const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  210    alt: true,
  211    shift: true,
  212    control: false,
  213    platform: false,
  214    function: false,
  215};
  216
  217pub fn render_parsed_markdown(
  218    element_id: impl Into<ElementId>,
  219    parsed: &language::ParsedMarkdown,
  220    editor_style: &EditorStyle,
  221    workspace: Option<WeakEntity<Workspace>>,
  222    cx: &mut App,
  223) -> InteractiveText {
  224    let code_span_background_color = cx
  225        .theme()
  226        .colors()
  227        .editor_document_highlight_read_background;
  228
  229    let highlights = gpui::combine_highlights(
  230        parsed.highlights.iter().filter_map(|(range, highlight)| {
  231            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  232            Some((range.clone(), highlight))
  233        }),
  234        parsed
  235            .regions
  236            .iter()
  237            .zip(&parsed.region_ranges)
  238            .filter_map(|(region, range)| {
  239                if region.code {
  240                    Some((
  241                        range.clone(),
  242                        HighlightStyle {
  243                            background_color: Some(code_span_background_color),
  244                            ..Default::default()
  245                        },
  246                    ))
  247                } else {
  248                    None
  249                }
  250            }),
  251    );
  252
  253    let mut links = Vec::new();
  254    let mut link_ranges = Vec::new();
  255    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  256        if let Some(link) = region.link.clone() {
  257            links.push(link);
  258            link_ranges.push(range.clone());
  259        }
  260    }
  261
  262    InteractiveText::new(
  263        element_id,
  264        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  265    )
  266    .on_click(
  267        link_ranges,
  268        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  269            markdown::Link::Web { url } => cx.open_url(url),
  270            markdown::Link::Path { path } => {
  271                if let Some(workspace) = &workspace {
  272                    _ = workspace.update(cx, |workspace, cx| {
  273                        workspace
  274                            .open_abs_path(path.clone(), false, window, cx)
  275                            .detach();
  276                    });
  277                }
  278            }
  279        },
  280    )
  281}
  282
  283#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  284pub enum InlayId {
  285    InlineCompletion(usize),
  286    Hint(usize),
  287}
  288
  289impl InlayId {
  290    fn id(&self) -> usize {
  291        match self {
  292            Self::InlineCompletion(id) => *id,
  293            Self::Hint(id) => *id,
  294        }
  295    }
  296}
  297
  298enum DocumentHighlightRead {}
  299enum DocumentHighlightWrite {}
  300enum InputComposition {}
  301enum SelectedTextHighlight {}
  302
  303#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  304pub enum Navigated {
  305    Yes,
  306    No,
  307}
  308
  309impl Navigated {
  310    pub fn from_bool(yes: bool) -> Navigated {
  311        if yes {
  312            Navigated::Yes
  313        } else {
  314            Navigated::No
  315        }
  316    }
  317}
  318
  319pub fn init_settings(cx: &mut App) {
  320    EditorSettings::register(cx);
  321}
  322
  323pub fn init(cx: &mut App) {
  324    init_settings(cx);
  325
  326    workspace::register_project_item::<Editor>(cx);
  327    workspace::FollowableViewRegistry::register::<Editor>(cx);
  328    workspace::register_serializable_item::<Editor>(cx);
  329
  330    cx.observe_new(
  331        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  332            workspace.register_action(Editor::new_file);
  333            workspace.register_action(Editor::new_file_vertical);
  334            workspace.register_action(Editor::new_file_horizontal);
  335            workspace.register_action(Editor::cancel_language_server_work);
  336        },
  337    )
  338    .detach();
  339
  340    cx.on_action(move |_: &workspace::NewFile, cx| {
  341        let app_state = workspace::AppState::global(cx);
  342        if let Some(app_state) = app_state.upgrade() {
  343            workspace::open_new(
  344                Default::default(),
  345                app_state,
  346                cx,
  347                |workspace, window, cx| {
  348                    Editor::new_file(workspace, &Default::default(), window, cx)
  349                },
  350            )
  351            .detach();
  352        }
  353    });
  354    cx.on_action(move |_: &workspace::NewWindow, cx| {
  355        let app_state = workspace::AppState::global(cx);
  356        if let Some(app_state) = app_state.upgrade() {
  357            workspace::open_new(
  358                Default::default(),
  359                app_state,
  360                cx,
  361                |workspace, window, cx| {
  362                    cx.activate(true);
  363                    Editor::new_file(workspace, &Default::default(), window, cx)
  364                },
  365            )
  366            .detach();
  367        }
  368    });
  369}
  370
  371pub struct SearchWithinRange;
  372
  373trait InvalidationRegion {
  374    fn ranges(&self) -> &[Range<Anchor>];
  375}
  376
  377#[derive(Clone, Debug, PartialEq)]
  378pub enum SelectPhase {
  379    Begin {
  380        position: DisplayPoint,
  381        add: bool,
  382        click_count: usize,
  383    },
  384    BeginColumnar {
  385        position: DisplayPoint,
  386        reset: bool,
  387        goal_column: u32,
  388    },
  389    Extend {
  390        position: DisplayPoint,
  391        click_count: usize,
  392    },
  393    Update {
  394        position: DisplayPoint,
  395        goal_column: u32,
  396        scroll_delta: gpui::Point<f32>,
  397    },
  398    End,
  399}
  400
  401#[derive(Clone, Debug)]
  402pub enum SelectMode {
  403    Character,
  404    Word(Range<Anchor>),
  405    Line(Range<Anchor>),
  406    All,
  407}
  408
  409#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  410pub enum EditorMode {
  411    SingleLine { auto_width: bool },
  412    AutoHeight { max_lines: usize },
  413    Full,
  414}
  415
  416#[derive(Copy, Clone, Debug)]
  417pub enum SoftWrap {
  418    /// Prefer not to wrap at all.
  419    ///
  420    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  421    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  422    GitDiff,
  423    /// Prefer a single line generally, unless an overly long line is encountered.
  424    None,
  425    /// Soft wrap lines that exceed the editor width.
  426    EditorWidth,
  427    /// Soft wrap lines at the preferred line length.
  428    Column(u32),
  429    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  430    Bounded(u32),
  431}
  432
  433#[derive(Clone)]
  434pub struct EditorStyle {
  435    pub background: Hsla,
  436    pub local_player: PlayerColor,
  437    pub text: TextStyle,
  438    pub scrollbar_width: Pixels,
  439    pub syntax: Arc<SyntaxTheme>,
  440    pub status: StatusColors,
  441    pub inlay_hints_style: HighlightStyle,
  442    pub inline_completion_styles: InlineCompletionStyles,
  443    pub unnecessary_code_fade: f32,
  444}
  445
  446impl Default for EditorStyle {
  447    fn default() -> Self {
  448        Self {
  449            background: Hsla::default(),
  450            local_player: PlayerColor::default(),
  451            text: TextStyle::default(),
  452            scrollbar_width: Pixels::default(),
  453            syntax: Default::default(),
  454            // HACK: Status colors don't have a real default.
  455            // We should look into removing the status colors from the editor
  456            // style and retrieve them directly from the theme.
  457            status: StatusColors::dark(),
  458            inlay_hints_style: HighlightStyle::default(),
  459            inline_completion_styles: InlineCompletionStyles {
  460                insertion: HighlightStyle::default(),
  461                whitespace: HighlightStyle::default(),
  462            },
  463            unnecessary_code_fade: Default::default(),
  464        }
  465    }
  466}
  467
  468pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  469    let show_background = language_settings::language_settings(None, None, cx)
  470        .inlay_hints
  471        .show_background;
  472
  473    HighlightStyle {
  474        color: Some(cx.theme().status().hint),
  475        background_color: show_background.then(|| cx.theme().status().hint_background),
  476        ..HighlightStyle::default()
  477    }
  478}
  479
  480pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  481    InlineCompletionStyles {
  482        insertion: HighlightStyle {
  483            color: Some(cx.theme().status().predictive),
  484            ..HighlightStyle::default()
  485        },
  486        whitespace: HighlightStyle {
  487            background_color: Some(cx.theme().status().created_background),
  488            ..HighlightStyle::default()
  489        },
  490    }
  491}
  492
  493type CompletionId = usize;
  494
  495pub(crate) enum EditDisplayMode {
  496    TabAccept,
  497    DiffPopover,
  498    Inline,
  499}
  500
  501enum InlineCompletion {
  502    Edit {
  503        edits: Vec<(Range<Anchor>, String)>,
  504        edit_preview: Option<EditPreview>,
  505        display_mode: EditDisplayMode,
  506        snapshot: BufferSnapshot,
  507    },
  508    Move {
  509        target: Anchor,
  510        snapshot: BufferSnapshot,
  511    },
  512}
  513
  514struct InlineCompletionState {
  515    inlay_ids: Vec<InlayId>,
  516    completion: InlineCompletion,
  517    completion_id: Option<SharedString>,
  518    invalidation_range: Range<Anchor>,
  519}
  520
  521enum EditPredictionSettings {
  522    Disabled,
  523    Enabled {
  524        show_in_menu: bool,
  525        preview_requires_modifier: bool,
  526    },
  527}
  528
  529enum InlineCompletionHighlight {}
  530
  531pub enum MenuInlineCompletionsPolicy {
  532    Never,
  533    ByProvider,
  534}
  535
  536pub enum EditPredictionPreview {
  537    /// Modifier is not pressed
  538    Inactive,
  539    /// Modifier pressed
  540    Active {
  541        previous_scroll_position: Option<ScrollAnchor>,
  542    },
  543}
  544
  545#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  546struct EditorActionId(usize);
  547
  548impl EditorActionId {
  549    pub fn post_inc(&mut self) -> Self {
  550        let answer = self.0;
  551
  552        *self = Self(answer + 1);
  553
  554        Self(answer)
  555    }
  556}
  557
  558// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  559// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  560
  561type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  562type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  563
  564#[derive(Default)]
  565struct ScrollbarMarkerState {
  566    scrollbar_size: Size<Pixels>,
  567    dirty: bool,
  568    markers: Arc<[PaintQuad]>,
  569    pending_refresh: Option<Task<Result<()>>>,
  570}
  571
  572impl ScrollbarMarkerState {
  573    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  574        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  575    }
  576}
  577
  578#[derive(Clone, Debug)]
  579struct RunnableTasks {
  580    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  581    offset: MultiBufferOffset,
  582    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  583    column: u32,
  584    // Values of all named captures, including those starting with '_'
  585    extra_variables: HashMap<String, String>,
  586    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  587    context_range: Range<BufferOffset>,
  588}
  589
  590impl RunnableTasks {
  591    fn resolve<'a>(
  592        &'a self,
  593        cx: &'a task::TaskContext,
  594    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  595        self.templates.iter().filter_map(|(kind, template)| {
  596            template
  597                .resolve_task(&kind.to_id_base(), cx)
  598                .map(|task| (kind.clone(), task))
  599        })
  600    }
  601}
  602
  603#[derive(Clone)]
  604struct ResolvedTasks {
  605    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  606    position: Anchor,
  607}
  608#[derive(Copy, Clone, Debug)]
  609struct MultiBufferOffset(usize);
  610#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  611struct BufferOffset(usize);
  612
  613// Addons allow storing per-editor state in other crates (e.g. Vim)
  614pub trait Addon: 'static {
  615    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  616
  617    fn render_buffer_header_controls(
  618        &self,
  619        _: &ExcerptInfo,
  620        _: &Window,
  621        _: &App,
  622    ) -> Option<AnyElement> {
  623        None
  624    }
  625
  626    fn to_any(&self) -> &dyn std::any::Any;
  627}
  628
  629#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  630pub enum IsVimMode {
  631    Yes,
  632    No,
  633}
  634
  635/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  636///
  637/// See the [module level documentation](self) for more information.
  638pub struct Editor {
  639    focus_handle: FocusHandle,
  640    last_focused_descendant: Option<WeakFocusHandle>,
  641    /// The text buffer being edited
  642    buffer: Entity<MultiBuffer>,
  643    /// Map of how text in the buffer should be displayed.
  644    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  645    pub display_map: Entity<DisplayMap>,
  646    pub selections: SelectionsCollection,
  647    pub scroll_manager: ScrollManager,
  648    /// When inline assist editors are linked, they all render cursors because
  649    /// typing enters text into each of them, even the ones that aren't focused.
  650    pub(crate) show_cursor_when_unfocused: bool,
  651    columnar_selection_tail: Option<Anchor>,
  652    add_selections_state: Option<AddSelectionsState>,
  653    select_next_state: Option<SelectNextState>,
  654    select_prev_state: Option<SelectNextState>,
  655    selection_history: SelectionHistory,
  656    autoclose_regions: Vec<AutocloseRegion>,
  657    snippet_stack: InvalidationStack<SnippetState>,
  658    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  659    ime_transaction: Option<TransactionId>,
  660    active_diagnostics: Option<ActiveDiagnosticGroup>,
  661    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  662
  663    // TODO: make this a access method
  664    pub project: Option<Entity<Project>>,
  665    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  666    completion_provider: Option<Box<dyn CompletionProvider>>,
  667    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  668    blink_manager: Entity<BlinkManager>,
  669    show_cursor_names: bool,
  670    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  671    pub show_local_selections: bool,
  672    mode: EditorMode,
  673    show_breadcrumbs: bool,
  674    show_gutter: bool,
  675    show_scrollbars: bool,
  676    show_line_numbers: Option<bool>,
  677    use_relative_line_numbers: Option<bool>,
  678    show_git_diff_gutter: Option<bool>,
  679    show_code_actions: Option<bool>,
  680    show_runnables: Option<bool>,
  681    show_wrap_guides: Option<bool>,
  682    show_indent_guides: Option<bool>,
  683    placeholder_text: Option<Arc<str>>,
  684    highlight_order: usize,
  685    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  686    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  687    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  688    scrollbar_marker_state: ScrollbarMarkerState,
  689    active_indent_guides_state: ActiveIndentGuidesState,
  690    nav_history: Option<ItemNavHistory>,
  691    context_menu: RefCell<Option<CodeContextMenu>>,
  692    mouse_context_menu: Option<MouseContextMenu>,
  693    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  694    signature_help_state: SignatureHelpState,
  695    auto_signature_help: Option<bool>,
  696    find_all_references_task_sources: Vec<Anchor>,
  697    next_completion_id: CompletionId,
  698    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  699    code_actions_task: Option<Task<Result<()>>>,
  700    selection_highlight_task: Option<Task<()>>,
  701    document_highlights_task: Option<Task<()>>,
  702    linked_editing_range_task: Option<Task<Option<()>>>,
  703    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  704    pending_rename: Option<RenameState>,
  705    searchable: bool,
  706    cursor_shape: CursorShape,
  707    current_line_highlight: Option<CurrentLineHighlight>,
  708    collapse_matches: bool,
  709    autoindent_mode: Option<AutoindentMode>,
  710    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  711    input_enabled: bool,
  712    use_modal_editing: bool,
  713    read_only: bool,
  714    leader_peer_id: Option<PeerId>,
  715    remote_id: Option<ViewId>,
  716    hover_state: HoverState,
  717    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  718    gutter_hovered: bool,
  719    hovered_link_state: Option<HoveredLinkState>,
  720    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  721    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  722    active_inline_completion: Option<InlineCompletionState>,
  723    /// Used to prevent flickering as the user types while the menu is open
  724    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  725    edit_prediction_settings: EditPredictionSettings,
  726    inline_completions_hidden_for_vim_mode: bool,
  727    show_inline_completions_override: Option<bool>,
  728    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  729    edit_prediction_preview: EditPredictionPreview,
  730    edit_prediction_cursor_on_leading_whitespace: bool,
  731    edit_prediction_requires_modifier_in_leading_space: bool,
  732    inlay_hint_cache: InlayHintCache,
  733    next_inlay_id: usize,
  734    _subscriptions: Vec<Subscription>,
  735    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  736    gutter_dimensions: GutterDimensions,
  737    style: Option<EditorStyle>,
  738    text_style_refinement: Option<TextStyleRefinement>,
  739    next_editor_action_id: EditorActionId,
  740    editor_actions:
  741        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  742    use_autoclose: bool,
  743    use_auto_surround: bool,
  744    auto_replace_emoji_shortcode: bool,
  745    show_git_blame_gutter: bool,
  746    show_git_blame_inline: bool,
  747    show_git_blame_inline_delay_task: Option<Task<()>>,
  748    distinguish_unstaged_diff_hunks: bool,
  749    git_blame_inline_enabled: bool,
  750    serialize_dirty_buffers: bool,
  751    show_selection_menu: Option<bool>,
  752    blame: Option<Entity<GitBlame>>,
  753    blame_subscription: Option<Subscription>,
  754    custom_context_menu: Option<
  755        Box<
  756            dyn 'static
  757                + Fn(
  758                    &mut Self,
  759                    DisplayPoint,
  760                    &mut Window,
  761                    &mut Context<Self>,
  762                ) -> Option<Entity<ui::ContextMenu>>,
  763        >,
  764    >,
  765    last_bounds: Option<Bounds<Pixels>>,
  766    last_position_map: Option<Rc<PositionMap>>,
  767    expect_bounds_change: Option<Bounds<Pixels>>,
  768    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  769    tasks_update_task: Option<Task<()>>,
  770    in_project_search: bool,
  771    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  772    breadcrumb_header: Option<String>,
  773    focused_block: Option<FocusedBlock>,
  774    next_scroll_position: NextScrollCursorCenterTopBottom,
  775    addons: HashMap<TypeId, Box<dyn Addon>>,
  776    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  777    load_diff_task: Option<Shared<Task<()>>>,
  778    selection_mark_mode: bool,
  779    toggle_fold_multiple_buffers: Task<()>,
  780    _scroll_cursor_center_top_bottom_task: Task<()>,
  781    serialize_selections: Task<()>,
  782}
  783
  784#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  785enum NextScrollCursorCenterTopBottom {
  786    #[default]
  787    Center,
  788    Top,
  789    Bottom,
  790}
  791
  792impl NextScrollCursorCenterTopBottom {
  793    fn next(&self) -> Self {
  794        match self {
  795            Self::Center => Self::Top,
  796            Self::Top => Self::Bottom,
  797            Self::Bottom => Self::Center,
  798        }
  799    }
  800}
  801
  802#[derive(Clone)]
  803pub struct EditorSnapshot {
  804    pub mode: EditorMode,
  805    show_gutter: bool,
  806    show_line_numbers: Option<bool>,
  807    show_git_diff_gutter: Option<bool>,
  808    show_code_actions: Option<bool>,
  809    show_runnables: Option<bool>,
  810    git_blame_gutter_max_author_length: Option<usize>,
  811    pub display_snapshot: DisplaySnapshot,
  812    pub placeholder_text: Option<Arc<str>>,
  813    is_focused: bool,
  814    scroll_anchor: ScrollAnchor,
  815    ongoing_scroll: OngoingScroll,
  816    current_line_highlight: CurrentLineHighlight,
  817    gutter_hovered: bool,
  818}
  819
  820const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  821
  822#[derive(Default, Debug, Clone, Copy)]
  823pub struct GutterDimensions {
  824    pub left_padding: Pixels,
  825    pub right_padding: Pixels,
  826    pub width: Pixels,
  827    pub margin: Pixels,
  828    pub git_blame_entries_width: Option<Pixels>,
  829}
  830
  831impl GutterDimensions {
  832    /// The full width of the space taken up by the gutter.
  833    pub fn full_width(&self) -> Pixels {
  834        self.margin + self.width
  835    }
  836
  837    /// The width of the space reserved for the fold indicators,
  838    /// use alongside 'justify_end' and `gutter_width` to
  839    /// right align content with the line numbers
  840    pub fn fold_area_width(&self) -> Pixels {
  841        self.margin + self.right_padding
  842    }
  843}
  844
  845#[derive(Debug)]
  846pub struct RemoteSelection {
  847    pub replica_id: ReplicaId,
  848    pub selection: Selection<Anchor>,
  849    pub cursor_shape: CursorShape,
  850    pub peer_id: PeerId,
  851    pub line_mode: bool,
  852    pub participant_index: Option<ParticipantIndex>,
  853    pub user_name: Option<SharedString>,
  854}
  855
  856#[derive(Clone, Debug)]
  857struct SelectionHistoryEntry {
  858    selections: Arc<[Selection<Anchor>]>,
  859    select_next_state: Option<SelectNextState>,
  860    select_prev_state: Option<SelectNextState>,
  861    add_selections_state: Option<AddSelectionsState>,
  862}
  863
  864enum SelectionHistoryMode {
  865    Normal,
  866    Undoing,
  867    Redoing,
  868}
  869
  870#[derive(Clone, PartialEq, Eq, Hash)]
  871struct HoveredCursor {
  872    replica_id: u16,
  873    selection_id: usize,
  874}
  875
  876impl Default for SelectionHistoryMode {
  877    fn default() -> Self {
  878        Self::Normal
  879    }
  880}
  881
  882#[derive(Default)]
  883struct SelectionHistory {
  884    #[allow(clippy::type_complexity)]
  885    selections_by_transaction:
  886        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  887    mode: SelectionHistoryMode,
  888    undo_stack: VecDeque<SelectionHistoryEntry>,
  889    redo_stack: VecDeque<SelectionHistoryEntry>,
  890}
  891
  892impl SelectionHistory {
  893    fn insert_transaction(
  894        &mut self,
  895        transaction_id: TransactionId,
  896        selections: Arc<[Selection<Anchor>]>,
  897    ) {
  898        self.selections_by_transaction
  899            .insert(transaction_id, (selections, None));
  900    }
  901
  902    #[allow(clippy::type_complexity)]
  903    fn transaction(
  904        &self,
  905        transaction_id: TransactionId,
  906    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  907        self.selections_by_transaction.get(&transaction_id)
  908    }
  909
  910    #[allow(clippy::type_complexity)]
  911    fn transaction_mut(
  912        &mut self,
  913        transaction_id: TransactionId,
  914    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  915        self.selections_by_transaction.get_mut(&transaction_id)
  916    }
  917
  918    fn push(&mut self, entry: SelectionHistoryEntry) {
  919        if !entry.selections.is_empty() {
  920            match self.mode {
  921                SelectionHistoryMode::Normal => {
  922                    self.push_undo(entry);
  923                    self.redo_stack.clear();
  924                }
  925                SelectionHistoryMode::Undoing => self.push_redo(entry),
  926                SelectionHistoryMode::Redoing => self.push_undo(entry),
  927            }
  928        }
  929    }
  930
  931    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  932        if self
  933            .undo_stack
  934            .back()
  935            .map_or(true, |e| e.selections != entry.selections)
  936        {
  937            self.undo_stack.push_back(entry);
  938            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  939                self.undo_stack.pop_front();
  940            }
  941        }
  942    }
  943
  944    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  945        if self
  946            .redo_stack
  947            .back()
  948            .map_or(true, |e| e.selections != entry.selections)
  949        {
  950            self.redo_stack.push_back(entry);
  951            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  952                self.redo_stack.pop_front();
  953            }
  954        }
  955    }
  956}
  957
  958struct RowHighlight {
  959    index: usize,
  960    range: Range<Anchor>,
  961    color: Hsla,
  962    should_autoscroll: bool,
  963}
  964
  965#[derive(Clone, Debug)]
  966struct AddSelectionsState {
  967    above: bool,
  968    stack: Vec<usize>,
  969}
  970
  971#[derive(Clone)]
  972struct SelectNextState {
  973    query: AhoCorasick,
  974    wordwise: bool,
  975    done: bool,
  976}
  977
  978impl std::fmt::Debug for SelectNextState {
  979    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  980        f.debug_struct(std::any::type_name::<Self>())
  981            .field("wordwise", &self.wordwise)
  982            .field("done", &self.done)
  983            .finish()
  984    }
  985}
  986
  987#[derive(Debug)]
  988struct AutocloseRegion {
  989    selection_id: usize,
  990    range: Range<Anchor>,
  991    pair: BracketPair,
  992}
  993
  994#[derive(Debug)]
  995struct SnippetState {
  996    ranges: Vec<Vec<Range<Anchor>>>,
  997    active_index: usize,
  998    choices: Vec<Option<Vec<String>>>,
  999}
 1000
 1001#[doc(hidden)]
 1002pub struct RenameState {
 1003    pub range: Range<Anchor>,
 1004    pub old_name: Arc<str>,
 1005    pub editor: Entity<Editor>,
 1006    block_id: CustomBlockId,
 1007}
 1008
 1009struct InvalidationStack<T>(Vec<T>);
 1010
 1011struct RegisteredInlineCompletionProvider {
 1012    provider: Arc<dyn InlineCompletionProviderHandle>,
 1013    _subscription: Subscription,
 1014}
 1015
 1016#[derive(Debug)]
 1017struct ActiveDiagnosticGroup {
 1018    primary_range: Range<Anchor>,
 1019    primary_message: String,
 1020    group_id: usize,
 1021    blocks: HashMap<CustomBlockId, Diagnostic>,
 1022    is_valid: bool,
 1023}
 1024
 1025#[derive(Serialize, Deserialize, Clone, Debug)]
 1026pub struct ClipboardSelection {
 1027    pub len: usize,
 1028    pub is_entire_line: bool,
 1029    pub first_line_indent: u32,
 1030}
 1031
 1032#[derive(Debug)]
 1033pub(crate) struct NavigationData {
 1034    cursor_anchor: Anchor,
 1035    cursor_position: Point,
 1036    scroll_anchor: ScrollAnchor,
 1037    scroll_top_row: u32,
 1038}
 1039
 1040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1041pub enum GotoDefinitionKind {
 1042    Symbol,
 1043    Declaration,
 1044    Type,
 1045    Implementation,
 1046}
 1047
 1048#[derive(Debug, Clone)]
 1049enum InlayHintRefreshReason {
 1050    Toggle(bool),
 1051    SettingsChange(InlayHintSettings),
 1052    NewLinesShown,
 1053    BufferEdited(HashSet<Arc<Language>>),
 1054    RefreshRequested,
 1055    ExcerptsRemoved(Vec<ExcerptId>),
 1056}
 1057
 1058impl InlayHintRefreshReason {
 1059    fn description(&self) -> &'static str {
 1060        match self {
 1061            Self::Toggle(_) => "toggle",
 1062            Self::SettingsChange(_) => "settings change",
 1063            Self::NewLinesShown => "new lines shown",
 1064            Self::BufferEdited(_) => "buffer edited",
 1065            Self::RefreshRequested => "refresh requested",
 1066            Self::ExcerptsRemoved(_) => "excerpts removed",
 1067        }
 1068    }
 1069}
 1070
 1071pub enum FormatTarget {
 1072    Buffers,
 1073    Ranges(Vec<Range<MultiBufferPoint>>),
 1074}
 1075
 1076pub(crate) struct FocusedBlock {
 1077    id: BlockId,
 1078    focus_handle: WeakFocusHandle,
 1079}
 1080
 1081#[derive(Clone)]
 1082enum JumpData {
 1083    MultiBufferRow {
 1084        row: MultiBufferRow,
 1085        line_offset_from_top: u32,
 1086    },
 1087    MultiBufferPoint {
 1088        excerpt_id: ExcerptId,
 1089        position: Point,
 1090        anchor: text::Anchor,
 1091        line_offset_from_top: u32,
 1092    },
 1093}
 1094
 1095pub enum MultibufferSelectionMode {
 1096    First,
 1097    All,
 1098}
 1099
 1100impl Editor {
 1101    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1102        let buffer = cx.new(|cx| Buffer::local("", cx));
 1103        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1104        Self::new(
 1105            EditorMode::SingleLine { auto_width: false },
 1106            buffer,
 1107            None,
 1108            false,
 1109            window,
 1110            cx,
 1111        )
 1112    }
 1113
 1114    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1115        let buffer = cx.new(|cx| Buffer::local("", cx));
 1116        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1117        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1118    }
 1119
 1120    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1121        let buffer = cx.new(|cx| Buffer::local("", cx));
 1122        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1123        Self::new(
 1124            EditorMode::SingleLine { auto_width: true },
 1125            buffer,
 1126            None,
 1127            false,
 1128            window,
 1129            cx,
 1130        )
 1131    }
 1132
 1133    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1134        let buffer = cx.new(|cx| Buffer::local("", cx));
 1135        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1136        Self::new(
 1137            EditorMode::AutoHeight { max_lines },
 1138            buffer,
 1139            None,
 1140            false,
 1141            window,
 1142            cx,
 1143        )
 1144    }
 1145
 1146    pub fn for_buffer(
 1147        buffer: Entity<Buffer>,
 1148        project: Option<Entity<Project>>,
 1149        window: &mut Window,
 1150        cx: &mut Context<Self>,
 1151    ) -> Self {
 1152        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1153        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1154    }
 1155
 1156    pub fn for_multibuffer(
 1157        buffer: Entity<MultiBuffer>,
 1158        project: Option<Entity<Project>>,
 1159        show_excerpt_controls: bool,
 1160        window: &mut Window,
 1161        cx: &mut Context<Self>,
 1162    ) -> Self {
 1163        Self::new(
 1164            EditorMode::Full,
 1165            buffer,
 1166            project,
 1167            show_excerpt_controls,
 1168            window,
 1169            cx,
 1170        )
 1171    }
 1172
 1173    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1174        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1175        let mut clone = Self::new(
 1176            self.mode,
 1177            self.buffer.clone(),
 1178            self.project.clone(),
 1179            show_excerpt_controls,
 1180            window,
 1181            cx,
 1182        );
 1183        self.display_map.update(cx, |display_map, cx| {
 1184            let snapshot = display_map.snapshot(cx);
 1185            clone.display_map.update(cx, |display_map, cx| {
 1186                display_map.set_state(&snapshot, cx);
 1187            });
 1188        });
 1189        clone.selections.clone_state(&self.selections);
 1190        clone.scroll_manager.clone_state(&self.scroll_manager);
 1191        clone.searchable = self.searchable;
 1192        clone
 1193    }
 1194
 1195    pub fn new(
 1196        mode: EditorMode,
 1197        buffer: Entity<MultiBuffer>,
 1198        project: Option<Entity<Project>>,
 1199        show_excerpt_controls: bool,
 1200        window: &mut Window,
 1201        cx: &mut Context<Self>,
 1202    ) -> Self {
 1203        let style = window.text_style();
 1204        let font_size = style.font_size.to_pixels(window.rem_size());
 1205        let editor = cx.entity().downgrade();
 1206        let fold_placeholder = FoldPlaceholder {
 1207            constrain_width: true,
 1208            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1209                let editor = editor.clone();
 1210                div()
 1211                    .id(fold_id)
 1212                    .bg(cx.theme().colors().ghost_element_background)
 1213                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1214                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1215                    .rounded_sm()
 1216                    .size_full()
 1217                    .cursor_pointer()
 1218                    .child("")
 1219                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1220                    .on_click(move |_, _window, cx| {
 1221                        editor
 1222                            .update(cx, |editor, cx| {
 1223                                editor.unfold_ranges(
 1224                                    &[fold_range.start..fold_range.end],
 1225                                    true,
 1226                                    false,
 1227                                    cx,
 1228                                );
 1229                                cx.stop_propagation();
 1230                            })
 1231                            .ok();
 1232                    })
 1233                    .into_any()
 1234            }),
 1235            merge_adjacent: true,
 1236            ..Default::default()
 1237        };
 1238        let display_map = cx.new(|cx| {
 1239            DisplayMap::new(
 1240                buffer.clone(),
 1241                style.font(),
 1242                font_size,
 1243                None,
 1244                show_excerpt_controls,
 1245                FILE_HEADER_HEIGHT,
 1246                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1247                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1248                fold_placeholder,
 1249                cx,
 1250            )
 1251        });
 1252
 1253        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1254
 1255        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1256
 1257        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1258            .then(|| language_settings::SoftWrap::None);
 1259
 1260        let mut project_subscriptions = Vec::new();
 1261        if mode == EditorMode::Full {
 1262            if let Some(project) = project.as_ref() {
 1263                if buffer.read(cx).is_singleton() {
 1264                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1265                        cx.emit(EditorEvent::TitleChanged);
 1266                    }));
 1267                }
 1268                project_subscriptions.push(cx.subscribe_in(
 1269                    project,
 1270                    window,
 1271                    |editor, _, event, window, cx| {
 1272                        if let project::Event::RefreshInlayHints = event {
 1273                            editor
 1274                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1275                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1276                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1277                                let focus_handle = editor.focus_handle(cx);
 1278                                if focus_handle.is_focused(window) {
 1279                                    let snapshot = buffer.read(cx).snapshot();
 1280                                    for (range, snippet) in snippet_edits {
 1281                                        let editor_range =
 1282                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1283                                        editor
 1284                                            .insert_snippet(
 1285                                                &[editor_range],
 1286                                                snippet.clone(),
 1287                                                window,
 1288                                                cx,
 1289                                            )
 1290                                            .ok();
 1291                                    }
 1292                                }
 1293                            }
 1294                        }
 1295                    },
 1296                ));
 1297                if let Some(task_inventory) = project
 1298                    .read(cx)
 1299                    .task_store()
 1300                    .read(cx)
 1301                    .task_inventory()
 1302                    .cloned()
 1303                {
 1304                    project_subscriptions.push(cx.observe_in(
 1305                        &task_inventory,
 1306                        window,
 1307                        |editor, _, window, cx| {
 1308                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1309                        },
 1310                    ));
 1311                }
 1312            }
 1313        }
 1314
 1315        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1316
 1317        let inlay_hint_settings =
 1318            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1319        let focus_handle = cx.focus_handle();
 1320        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1321            .detach();
 1322        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1323            .detach();
 1324        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1325            .detach();
 1326        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1327            .detach();
 1328
 1329        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1330            Some(false)
 1331        } else {
 1332            None
 1333        };
 1334
 1335        let mut code_action_providers = Vec::new();
 1336        let mut load_uncommitted_diff = None;
 1337        if let Some(project) = project.clone() {
 1338            load_uncommitted_diff = Some(
 1339                get_uncommitted_diff_for_buffer(
 1340                    &project,
 1341                    buffer.read(cx).all_buffers(),
 1342                    buffer.clone(),
 1343                    cx,
 1344                )
 1345                .shared(),
 1346            );
 1347            code_action_providers.push(Rc::new(project) as Rc<_>);
 1348        }
 1349
 1350        let mut this = Self {
 1351            focus_handle,
 1352            show_cursor_when_unfocused: false,
 1353            last_focused_descendant: None,
 1354            buffer: buffer.clone(),
 1355            display_map: display_map.clone(),
 1356            selections,
 1357            scroll_manager: ScrollManager::new(cx),
 1358            columnar_selection_tail: None,
 1359            add_selections_state: None,
 1360            select_next_state: None,
 1361            select_prev_state: None,
 1362            selection_history: Default::default(),
 1363            autoclose_regions: Default::default(),
 1364            snippet_stack: Default::default(),
 1365            select_larger_syntax_node_stack: Vec::new(),
 1366            ime_transaction: Default::default(),
 1367            active_diagnostics: None,
 1368            soft_wrap_mode_override,
 1369            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1370            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1371            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1372            project,
 1373            blink_manager: blink_manager.clone(),
 1374            show_local_selections: true,
 1375            show_scrollbars: true,
 1376            mode,
 1377            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1378            show_gutter: mode == EditorMode::Full,
 1379            show_line_numbers: None,
 1380            use_relative_line_numbers: None,
 1381            show_git_diff_gutter: None,
 1382            show_code_actions: None,
 1383            show_runnables: None,
 1384            show_wrap_guides: None,
 1385            show_indent_guides,
 1386            placeholder_text: None,
 1387            highlight_order: 0,
 1388            highlighted_rows: HashMap::default(),
 1389            background_highlights: Default::default(),
 1390            gutter_highlights: TreeMap::default(),
 1391            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1392            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1393            nav_history: None,
 1394            context_menu: RefCell::new(None),
 1395            mouse_context_menu: None,
 1396            completion_tasks: Default::default(),
 1397            signature_help_state: SignatureHelpState::default(),
 1398            auto_signature_help: None,
 1399            find_all_references_task_sources: Vec::new(),
 1400            next_completion_id: 0,
 1401            next_inlay_id: 0,
 1402            code_action_providers,
 1403            available_code_actions: Default::default(),
 1404            code_actions_task: Default::default(),
 1405            selection_highlight_task: Default::default(),
 1406            document_highlights_task: Default::default(),
 1407            linked_editing_range_task: Default::default(),
 1408            pending_rename: Default::default(),
 1409            searchable: true,
 1410            cursor_shape: EditorSettings::get_global(cx)
 1411                .cursor_shape
 1412                .unwrap_or_default(),
 1413            current_line_highlight: None,
 1414            autoindent_mode: Some(AutoindentMode::EachLine),
 1415            collapse_matches: false,
 1416            workspace: None,
 1417            input_enabled: true,
 1418            use_modal_editing: mode == EditorMode::Full,
 1419            read_only: false,
 1420            use_autoclose: true,
 1421            use_auto_surround: true,
 1422            auto_replace_emoji_shortcode: false,
 1423            leader_peer_id: None,
 1424            remote_id: None,
 1425            hover_state: Default::default(),
 1426            pending_mouse_down: None,
 1427            hovered_link_state: Default::default(),
 1428            edit_prediction_provider: None,
 1429            active_inline_completion: None,
 1430            stale_inline_completion_in_menu: None,
 1431            edit_prediction_preview: EditPredictionPreview::Inactive,
 1432            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1433
 1434            gutter_hovered: false,
 1435            pixel_position_of_newest_cursor: None,
 1436            last_bounds: None,
 1437            last_position_map: None,
 1438            expect_bounds_change: None,
 1439            gutter_dimensions: GutterDimensions::default(),
 1440            style: None,
 1441            show_cursor_names: false,
 1442            hovered_cursors: Default::default(),
 1443            next_editor_action_id: EditorActionId::default(),
 1444            editor_actions: Rc::default(),
 1445            inline_completions_hidden_for_vim_mode: false,
 1446            show_inline_completions_override: None,
 1447            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1448            edit_prediction_settings: EditPredictionSettings::Disabled,
 1449            edit_prediction_cursor_on_leading_whitespace: false,
 1450            edit_prediction_requires_modifier_in_leading_space: true,
 1451            custom_context_menu: None,
 1452            show_git_blame_gutter: false,
 1453            show_git_blame_inline: false,
 1454            distinguish_unstaged_diff_hunks: false,
 1455            show_selection_menu: None,
 1456            show_git_blame_inline_delay_task: None,
 1457            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1458            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1459                .session
 1460                .restore_unsaved_buffers,
 1461            blame: None,
 1462            blame_subscription: None,
 1463            tasks: Default::default(),
 1464            _subscriptions: vec![
 1465                cx.observe(&buffer, Self::on_buffer_changed),
 1466                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1467                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1468                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1469                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1470                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1471                cx.observe_window_activation(window, |editor, window, cx| {
 1472                    let active = window.is_window_active();
 1473                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1474                        if active {
 1475                            blink_manager.enable(cx);
 1476                        } else {
 1477                            blink_manager.disable(cx);
 1478                        }
 1479                    });
 1480                }),
 1481            ],
 1482            tasks_update_task: None,
 1483            linked_edit_ranges: Default::default(),
 1484            in_project_search: false,
 1485            previous_search_ranges: None,
 1486            breadcrumb_header: None,
 1487            focused_block: None,
 1488            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1489            addons: HashMap::default(),
 1490            registered_buffers: HashMap::default(),
 1491            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1492            selection_mark_mode: false,
 1493            toggle_fold_multiple_buffers: Task::ready(()),
 1494            serialize_selections: Task::ready(()),
 1495            text_style_refinement: None,
 1496            load_diff_task: load_uncommitted_diff,
 1497        };
 1498        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1499        this._subscriptions.extend(project_subscriptions);
 1500
 1501        this.end_selection(window, cx);
 1502        this.scroll_manager.show_scrollbar(window, cx);
 1503
 1504        if mode == EditorMode::Full {
 1505            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1506            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1507
 1508            if this.git_blame_inline_enabled {
 1509                this.git_blame_inline_enabled = true;
 1510                this.start_git_blame_inline(false, window, cx);
 1511            }
 1512
 1513            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1514                if let Some(project) = this.project.as_ref() {
 1515                    let handle = project.update(cx, |project, cx| {
 1516                        project.register_buffer_with_language_servers(&buffer, cx)
 1517                    });
 1518                    this.registered_buffers
 1519                        .insert(buffer.read(cx).remote_id(), handle);
 1520                }
 1521            }
 1522        }
 1523
 1524        this.report_editor_event("Editor Opened", None, cx);
 1525        this
 1526    }
 1527
 1528    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1529        self.mouse_context_menu
 1530            .as_ref()
 1531            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1532    }
 1533
 1534    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1535        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1536    }
 1537
 1538    fn key_context_internal(
 1539        &self,
 1540        has_active_edit_prediction: bool,
 1541        window: &Window,
 1542        cx: &App,
 1543    ) -> KeyContext {
 1544        let mut key_context = KeyContext::new_with_defaults();
 1545        key_context.add("Editor");
 1546        let mode = match self.mode {
 1547            EditorMode::SingleLine { .. } => "single_line",
 1548            EditorMode::AutoHeight { .. } => "auto_height",
 1549            EditorMode::Full => "full",
 1550        };
 1551
 1552        if EditorSettings::jupyter_enabled(cx) {
 1553            key_context.add("jupyter");
 1554        }
 1555
 1556        key_context.set("mode", mode);
 1557        if self.pending_rename.is_some() {
 1558            key_context.add("renaming");
 1559        }
 1560
 1561        match self.context_menu.borrow().as_ref() {
 1562            Some(CodeContextMenu::Completions(_)) => {
 1563                key_context.add("menu");
 1564                key_context.add("showing_completions");
 1565            }
 1566            Some(CodeContextMenu::CodeActions(_)) => {
 1567                key_context.add("menu");
 1568                key_context.add("showing_code_actions")
 1569            }
 1570            None => {}
 1571        }
 1572
 1573        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1574        if !self.focus_handle(cx).contains_focused(window, cx)
 1575            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1576        {
 1577            for addon in self.addons.values() {
 1578                addon.extend_key_context(&mut key_context, cx)
 1579            }
 1580        }
 1581
 1582        if let Some(extension) = self
 1583            .buffer
 1584            .read(cx)
 1585            .as_singleton()
 1586            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1587        {
 1588            key_context.set("extension", extension.to_string());
 1589        }
 1590
 1591        if has_active_edit_prediction {
 1592            if self.edit_prediction_in_conflict() {
 1593                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1594            } else {
 1595                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1596                key_context.add("copilot_suggestion");
 1597            }
 1598        }
 1599
 1600        if self.selection_mark_mode {
 1601            key_context.add("selection_mode");
 1602        }
 1603
 1604        key_context
 1605    }
 1606
 1607    pub fn edit_prediction_in_conflict(&self) -> bool {
 1608        if !self.show_edit_predictions_in_menu() {
 1609            return false;
 1610        }
 1611
 1612        let showing_completions = self
 1613            .context_menu
 1614            .borrow()
 1615            .as_ref()
 1616            .map_or(false, |context| {
 1617                matches!(context, CodeContextMenu::Completions(_))
 1618            });
 1619
 1620        showing_completions
 1621            || self.edit_prediction_requires_modifier()
 1622            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1623            // bindings to insert tab characters.
 1624            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1625    }
 1626
 1627    pub fn accept_edit_prediction_keybind(
 1628        &self,
 1629        window: &Window,
 1630        cx: &App,
 1631    ) -> AcceptEditPredictionBinding {
 1632        let key_context = self.key_context_internal(true, window, cx);
 1633        let in_conflict = self.edit_prediction_in_conflict();
 1634
 1635        AcceptEditPredictionBinding(
 1636            window
 1637                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1638                .into_iter()
 1639                .filter(|binding| {
 1640                    !in_conflict
 1641                        || binding
 1642                            .keystrokes()
 1643                            .first()
 1644                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1645                })
 1646                .rev()
 1647                .min_by_key(|binding| {
 1648                    binding
 1649                        .keystrokes()
 1650                        .first()
 1651                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1652                }),
 1653        )
 1654    }
 1655
 1656    pub fn new_file(
 1657        workspace: &mut Workspace,
 1658        _: &workspace::NewFile,
 1659        window: &mut Window,
 1660        cx: &mut Context<Workspace>,
 1661    ) {
 1662        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1663            "Failed to create buffer",
 1664            window,
 1665            cx,
 1666            |e, _, _| match e.error_code() {
 1667                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1668                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1669                e.error_tag("required").unwrap_or("the latest version")
 1670            )),
 1671                _ => None,
 1672            },
 1673        );
 1674    }
 1675
 1676    pub fn new_in_workspace(
 1677        workspace: &mut Workspace,
 1678        window: &mut Window,
 1679        cx: &mut Context<Workspace>,
 1680    ) -> Task<Result<Entity<Editor>>> {
 1681        let project = workspace.project().clone();
 1682        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1683
 1684        cx.spawn_in(window, |workspace, mut cx| async move {
 1685            let buffer = create.await?;
 1686            workspace.update_in(&mut cx, |workspace, window, cx| {
 1687                let editor =
 1688                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1689                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1690                editor
 1691            })
 1692        })
 1693    }
 1694
 1695    fn new_file_vertical(
 1696        workspace: &mut Workspace,
 1697        _: &workspace::NewFileSplitVertical,
 1698        window: &mut Window,
 1699        cx: &mut Context<Workspace>,
 1700    ) {
 1701        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1702    }
 1703
 1704    fn new_file_horizontal(
 1705        workspace: &mut Workspace,
 1706        _: &workspace::NewFileSplitHorizontal,
 1707        window: &mut Window,
 1708        cx: &mut Context<Workspace>,
 1709    ) {
 1710        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1711    }
 1712
 1713    fn new_file_in_direction(
 1714        workspace: &mut Workspace,
 1715        direction: SplitDirection,
 1716        window: &mut Window,
 1717        cx: &mut Context<Workspace>,
 1718    ) {
 1719        let project = workspace.project().clone();
 1720        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1721
 1722        cx.spawn_in(window, |workspace, mut cx| async move {
 1723            let buffer = create.await?;
 1724            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1725                workspace.split_item(
 1726                    direction,
 1727                    Box::new(
 1728                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1729                    ),
 1730                    window,
 1731                    cx,
 1732                )
 1733            })?;
 1734            anyhow::Ok(())
 1735        })
 1736        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1737            match e.error_code() {
 1738                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1739                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1740                e.error_tag("required").unwrap_or("the latest version")
 1741            )),
 1742                _ => None,
 1743            }
 1744        });
 1745    }
 1746
 1747    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1748        self.leader_peer_id
 1749    }
 1750
 1751    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1752        &self.buffer
 1753    }
 1754
 1755    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1756        self.workspace.as_ref()?.0.upgrade()
 1757    }
 1758
 1759    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1760        self.buffer().read(cx).title(cx)
 1761    }
 1762
 1763    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1764        let git_blame_gutter_max_author_length = self
 1765            .render_git_blame_gutter(cx)
 1766            .then(|| {
 1767                if let Some(blame) = self.blame.as_ref() {
 1768                    let max_author_length =
 1769                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1770                    Some(max_author_length)
 1771                } else {
 1772                    None
 1773                }
 1774            })
 1775            .flatten();
 1776
 1777        EditorSnapshot {
 1778            mode: self.mode,
 1779            show_gutter: self.show_gutter,
 1780            show_line_numbers: self.show_line_numbers,
 1781            show_git_diff_gutter: self.show_git_diff_gutter,
 1782            show_code_actions: self.show_code_actions,
 1783            show_runnables: self.show_runnables,
 1784            git_blame_gutter_max_author_length,
 1785            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1786            scroll_anchor: self.scroll_manager.anchor(),
 1787            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1788            placeholder_text: self.placeholder_text.clone(),
 1789            is_focused: self.focus_handle.is_focused(window),
 1790            current_line_highlight: self
 1791                .current_line_highlight
 1792                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1793            gutter_hovered: self.gutter_hovered,
 1794        }
 1795    }
 1796
 1797    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1798        self.buffer.read(cx).language_at(point, cx)
 1799    }
 1800
 1801    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1802        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1803    }
 1804
 1805    pub fn active_excerpt(
 1806        &self,
 1807        cx: &App,
 1808    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1809        self.buffer
 1810            .read(cx)
 1811            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1812    }
 1813
 1814    pub fn mode(&self) -> EditorMode {
 1815        self.mode
 1816    }
 1817
 1818    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1819        self.collaboration_hub.as_deref()
 1820    }
 1821
 1822    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1823        self.collaboration_hub = Some(hub);
 1824    }
 1825
 1826    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1827        self.in_project_search = in_project_search;
 1828    }
 1829
 1830    pub fn set_custom_context_menu(
 1831        &mut self,
 1832        f: impl 'static
 1833            + Fn(
 1834                &mut Self,
 1835                DisplayPoint,
 1836                &mut Window,
 1837                &mut Context<Self>,
 1838            ) -> Option<Entity<ui::ContextMenu>>,
 1839    ) {
 1840        self.custom_context_menu = Some(Box::new(f))
 1841    }
 1842
 1843    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1844        self.completion_provider = provider;
 1845    }
 1846
 1847    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1848        self.semantics_provider.clone()
 1849    }
 1850
 1851    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1852        self.semantics_provider = provider;
 1853    }
 1854
 1855    pub fn set_edit_prediction_provider<T>(
 1856        &mut self,
 1857        provider: Option<Entity<T>>,
 1858        window: &mut Window,
 1859        cx: &mut Context<Self>,
 1860    ) where
 1861        T: EditPredictionProvider,
 1862    {
 1863        self.edit_prediction_provider =
 1864            provider.map(|provider| RegisteredInlineCompletionProvider {
 1865                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1866                    if this.focus_handle.is_focused(window) {
 1867                        this.update_visible_inline_completion(window, cx);
 1868                    }
 1869                }),
 1870                provider: Arc::new(provider),
 1871            });
 1872        self.refresh_inline_completion(false, false, window, cx);
 1873    }
 1874
 1875    pub fn placeholder_text(&self) -> Option<&str> {
 1876        self.placeholder_text.as_deref()
 1877    }
 1878
 1879    pub fn set_placeholder_text(
 1880        &mut self,
 1881        placeholder_text: impl Into<Arc<str>>,
 1882        cx: &mut Context<Self>,
 1883    ) {
 1884        let placeholder_text = Some(placeholder_text.into());
 1885        if self.placeholder_text != placeholder_text {
 1886            self.placeholder_text = placeholder_text;
 1887            cx.notify();
 1888        }
 1889    }
 1890
 1891    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1892        self.cursor_shape = cursor_shape;
 1893
 1894        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1895        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1896
 1897        cx.notify();
 1898    }
 1899
 1900    pub fn set_current_line_highlight(
 1901        &mut self,
 1902        current_line_highlight: Option<CurrentLineHighlight>,
 1903    ) {
 1904        self.current_line_highlight = current_line_highlight;
 1905    }
 1906
 1907    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1908        self.collapse_matches = collapse_matches;
 1909    }
 1910
 1911    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1912        let buffers = self.buffer.read(cx).all_buffers();
 1913        let Some(project) = self.project.as_ref() else {
 1914            return;
 1915        };
 1916        project.update(cx, |project, cx| {
 1917            for buffer in buffers {
 1918                self.registered_buffers
 1919                    .entry(buffer.read(cx).remote_id())
 1920                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1921            }
 1922        })
 1923    }
 1924
 1925    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1926        if self.collapse_matches {
 1927            return range.start..range.start;
 1928        }
 1929        range.clone()
 1930    }
 1931
 1932    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1933        if self.display_map.read(cx).clip_at_line_ends != clip {
 1934            self.display_map
 1935                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1936        }
 1937    }
 1938
 1939    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1940        self.input_enabled = input_enabled;
 1941    }
 1942
 1943    pub fn set_inline_completions_hidden_for_vim_mode(
 1944        &mut self,
 1945        hidden: bool,
 1946        window: &mut Window,
 1947        cx: &mut Context<Self>,
 1948    ) {
 1949        if hidden != self.inline_completions_hidden_for_vim_mode {
 1950            self.inline_completions_hidden_for_vim_mode = hidden;
 1951            if hidden {
 1952                self.update_visible_inline_completion(window, cx);
 1953            } else {
 1954                self.refresh_inline_completion(true, false, window, cx);
 1955            }
 1956        }
 1957    }
 1958
 1959    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1960        self.menu_inline_completions_policy = value;
 1961    }
 1962
 1963    pub fn set_autoindent(&mut self, autoindent: bool) {
 1964        if autoindent {
 1965            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1966        } else {
 1967            self.autoindent_mode = None;
 1968        }
 1969    }
 1970
 1971    pub fn read_only(&self, cx: &App) -> bool {
 1972        self.read_only || self.buffer.read(cx).read_only()
 1973    }
 1974
 1975    pub fn set_read_only(&mut self, read_only: bool) {
 1976        self.read_only = read_only;
 1977    }
 1978
 1979    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1980        self.use_autoclose = autoclose;
 1981    }
 1982
 1983    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1984        self.use_auto_surround = auto_surround;
 1985    }
 1986
 1987    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1988        self.auto_replace_emoji_shortcode = auto_replace;
 1989    }
 1990
 1991    pub fn toggle_inline_completions(
 1992        &mut self,
 1993        _: &ToggleEditPrediction,
 1994        window: &mut Window,
 1995        cx: &mut Context<Self>,
 1996    ) {
 1997        if self.show_inline_completions_override.is_some() {
 1998            self.set_show_edit_predictions(None, window, cx);
 1999        } else {
 2000            let show_edit_predictions = !self.edit_predictions_enabled();
 2001            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2002        }
 2003    }
 2004
 2005    pub fn set_show_edit_predictions(
 2006        &mut self,
 2007        show_edit_predictions: Option<bool>,
 2008        window: &mut Window,
 2009        cx: &mut Context<Self>,
 2010    ) {
 2011        self.show_inline_completions_override = show_edit_predictions;
 2012        self.refresh_inline_completion(false, true, window, cx);
 2013    }
 2014
 2015    fn inline_completions_disabled_in_scope(
 2016        &self,
 2017        buffer: &Entity<Buffer>,
 2018        buffer_position: language::Anchor,
 2019        cx: &App,
 2020    ) -> bool {
 2021        let snapshot = buffer.read(cx).snapshot();
 2022        let settings = snapshot.settings_at(buffer_position, cx);
 2023
 2024        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2025            return false;
 2026        };
 2027
 2028        scope.override_name().map_or(false, |scope_name| {
 2029            settings
 2030                .edit_predictions_disabled_in
 2031                .iter()
 2032                .any(|s| s == scope_name)
 2033        })
 2034    }
 2035
 2036    pub fn set_use_modal_editing(&mut self, to: bool) {
 2037        self.use_modal_editing = to;
 2038    }
 2039
 2040    pub fn use_modal_editing(&self) -> bool {
 2041        self.use_modal_editing
 2042    }
 2043
 2044    fn selections_did_change(
 2045        &mut self,
 2046        local: bool,
 2047        old_cursor_position: &Anchor,
 2048        show_completions: bool,
 2049        window: &mut Window,
 2050        cx: &mut Context<Self>,
 2051    ) {
 2052        window.invalidate_character_coordinates();
 2053
 2054        // Copy selections to primary selection buffer
 2055        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2056        if local {
 2057            let selections = self.selections.all::<usize>(cx);
 2058            let buffer_handle = self.buffer.read(cx).read(cx);
 2059
 2060            let mut text = String::new();
 2061            for (index, selection) in selections.iter().enumerate() {
 2062                let text_for_selection = buffer_handle
 2063                    .text_for_range(selection.start..selection.end)
 2064                    .collect::<String>();
 2065
 2066                text.push_str(&text_for_selection);
 2067                if index != selections.len() - 1 {
 2068                    text.push('\n');
 2069                }
 2070            }
 2071
 2072            if !text.is_empty() {
 2073                cx.write_to_primary(ClipboardItem::new_string(text));
 2074            }
 2075        }
 2076
 2077        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2078            self.buffer.update(cx, |buffer, cx| {
 2079                buffer.set_active_selections(
 2080                    &self.selections.disjoint_anchors(),
 2081                    self.selections.line_mode,
 2082                    self.cursor_shape,
 2083                    cx,
 2084                )
 2085            });
 2086        }
 2087        let display_map = self
 2088            .display_map
 2089            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2090        let buffer = &display_map.buffer_snapshot;
 2091        self.add_selections_state = None;
 2092        self.select_next_state = None;
 2093        self.select_prev_state = None;
 2094        self.select_larger_syntax_node_stack.clear();
 2095        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2096        self.snippet_stack
 2097            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2098        self.take_rename(false, window, cx);
 2099
 2100        let new_cursor_position = self.selections.newest_anchor().head();
 2101
 2102        self.push_to_nav_history(
 2103            *old_cursor_position,
 2104            Some(new_cursor_position.to_point(buffer)),
 2105            cx,
 2106        );
 2107
 2108        if local {
 2109            let new_cursor_position = self.selections.newest_anchor().head();
 2110            let mut context_menu = self.context_menu.borrow_mut();
 2111            let completion_menu = match context_menu.as_ref() {
 2112                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2113                _ => {
 2114                    *context_menu = None;
 2115                    None
 2116                }
 2117            };
 2118            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2119                if !self.registered_buffers.contains_key(&buffer_id) {
 2120                    if let Some(project) = self.project.as_ref() {
 2121                        project.update(cx, |project, cx| {
 2122                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2123                                return;
 2124                            };
 2125                            self.registered_buffers.insert(
 2126                                buffer_id,
 2127                                project.register_buffer_with_language_servers(&buffer, cx),
 2128                            );
 2129                        })
 2130                    }
 2131                }
 2132            }
 2133
 2134            if let Some(completion_menu) = completion_menu {
 2135                let cursor_position = new_cursor_position.to_offset(buffer);
 2136                let (word_range, kind) =
 2137                    buffer.surrounding_word(completion_menu.initial_position, true);
 2138                if kind == Some(CharKind::Word)
 2139                    && word_range.to_inclusive().contains(&cursor_position)
 2140                {
 2141                    let mut completion_menu = completion_menu.clone();
 2142                    drop(context_menu);
 2143
 2144                    let query = Self::completion_query(buffer, cursor_position);
 2145                    cx.spawn(move |this, mut cx| async move {
 2146                        completion_menu
 2147                            .filter(query.as_deref(), cx.background_executor().clone())
 2148                            .await;
 2149
 2150                        this.update(&mut cx, |this, cx| {
 2151                            let mut context_menu = this.context_menu.borrow_mut();
 2152                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2153                            else {
 2154                                return;
 2155                            };
 2156
 2157                            if menu.id > completion_menu.id {
 2158                                return;
 2159                            }
 2160
 2161                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2162                            drop(context_menu);
 2163                            cx.notify();
 2164                        })
 2165                    })
 2166                    .detach();
 2167
 2168                    if show_completions {
 2169                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2170                    }
 2171                } else {
 2172                    drop(context_menu);
 2173                    self.hide_context_menu(window, cx);
 2174                }
 2175            } else {
 2176                drop(context_menu);
 2177            }
 2178
 2179            hide_hover(self, cx);
 2180
 2181            if old_cursor_position.to_display_point(&display_map).row()
 2182                != new_cursor_position.to_display_point(&display_map).row()
 2183            {
 2184                self.available_code_actions.take();
 2185            }
 2186            self.refresh_code_actions(window, cx);
 2187            self.refresh_document_highlights(cx);
 2188            self.refresh_selected_text_highlights(window, cx);
 2189            refresh_matching_bracket_highlights(self, window, cx);
 2190            self.update_visible_inline_completion(window, cx);
 2191            self.edit_prediction_requires_modifier_in_leading_space = true;
 2192            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2193            if self.git_blame_inline_enabled {
 2194                self.start_inline_blame_timer(window, cx);
 2195            }
 2196        }
 2197
 2198        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2199        cx.emit(EditorEvent::SelectionsChanged { local });
 2200
 2201        let selections = &self.selections.disjoint;
 2202        if selections.len() == 1 {
 2203            cx.emit(SearchEvent::ActiveMatchChanged)
 2204        }
 2205        if local
 2206            && self.is_singleton(cx)
 2207            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2208        {
 2209            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2210                let background_executor = cx.background_executor().clone();
 2211                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2212                let snapshot = self.buffer().read(cx).snapshot(cx);
 2213                let selections = selections.clone();
 2214                self.serialize_selections = cx.background_spawn(async move {
 2215                    background_executor.timer(Duration::from_millis(100)).await;
 2216                    let selections = selections
 2217                        .iter()
 2218                        .map(|selection| {
 2219                            (
 2220                                selection.start.to_offset(&snapshot),
 2221                                selection.end.to_offset(&snapshot),
 2222                            )
 2223                        })
 2224                        .collect();
 2225                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2226                        .await
 2227                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2228                        .log_err();
 2229                });
 2230            }
 2231        }
 2232
 2233        cx.notify();
 2234    }
 2235
 2236    pub fn change_selections<R>(
 2237        &mut self,
 2238        autoscroll: Option<Autoscroll>,
 2239        window: &mut Window,
 2240        cx: &mut Context<Self>,
 2241        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2242    ) -> R {
 2243        self.change_selections_inner(autoscroll, true, window, cx, change)
 2244    }
 2245
 2246    fn change_selections_inner<R>(
 2247        &mut self,
 2248        autoscroll: Option<Autoscroll>,
 2249        request_completions: bool,
 2250        window: &mut Window,
 2251        cx: &mut Context<Self>,
 2252        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2253    ) -> R {
 2254        let old_cursor_position = self.selections.newest_anchor().head();
 2255        self.push_to_selection_history();
 2256
 2257        let (changed, result) = self.selections.change_with(cx, change);
 2258
 2259        if changed {
 2260            if let Some(autoscroll) = autoscroll {
 2261                self.request_autoscroll(autoscroll, cx);
 2262            }
 2263            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2264
 2265            if self.should_open_signature_help_automatically(
 2266                &old_cursor_position,
 2267                self.signature_help_state.backspace_pressed(),
 2268                cx,
 2269            ) {
 2270                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2271            }
 2272            self.signature_help_state.set_backspace_pressed(false);
 2273        }
 2274
 2275        result
 2276    }
 2277
 2278    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2279    where
 2280        I: IntoIterator<Item = (Range<S>, T)>,
 2281        S: ToOffset,
 2282        T: Into<Arc<str>>,
 2283    {
 2284        if self.read_only(cx) {
 2285            return;
 2286        }
 2287
 2288        self.buffer
 2289            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2290    }
 2291
 2292    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2293    where
 2294        I: IntoIterator<Item = (Range<S>, T)>,
 2295        S: ToOffset,
 2296        T: Into<Arc<str>>,
 2297    {
 2298        if self.read_only(cx) {
 2299            return;
 2300        }
 2301
 2302        self.buffer.update(cx, |buffer, cx| {
 2303            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2304        });
 2305    }
 2306
 2307    pub fn edit_with_block_indent<I, S, T>(
 2308        &mut self,
 2309        edits: I,
 2310        original_indent_columns: Vec<u32>,
 2311        cx: &mut Context<Self>,
 2312    ) where
 2313        I: IntoIterator<Item = (Range<S>, T)>,
 2314        S: ToOffset,
 2315        T: Into<Arc<str>>,
 2316    {
 2317        if self.read_only(cx) {
 2318            return;
 2319        }
 2320
 2321        self.buffer.update(cx, |buffer, cx| {
 2322            buffer.edit(
 2323                edits,
 2324                Some(AutoindentMode::Block {
 2325                    original_indent_columns,
 2326                }),
 2327                cx,
 2328            )
 2329        });
 2330    }
 2331
 2332    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2333        self.hide_context_menu(window, cx);
 2334
 2335        match phase {
 2336            SelectPhase::Begin {
 2337                position,
 2338                add,
 2339                click_count,
 2340            } => self.begin_selection(position, add, click_count, window, cx),
 2341            SelectPhase::BeginColumnar {
 2342                position,
 2343                goal_column,
 2344                reset,
 2345            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2346            SelectPhase::Extend {
 2347                position,
 2348                click_count,
 2349            } => self.extend_selection(position, click_count, window, cx),
 2350            SelectPhase::Update {
 2351                position,
 2352                goal_column,
 2353                scroll_delta,
 2354            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2355            SelectPhase::End => self.end_selection(window, cx),
 2356        }
 2357    }
 2358
 2359    fn extend_selection(
 2360        &mut self,
 2361        position: DisplayPoint,
 2362        click_count: usize,
 2363        window: &mut Window,
 2364        cx: &mut Context<Self>,
 2365    ) {
 2366        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2367        let tail = self.selections.newest::<usize>(cx).tail();
 2368        self.begin_selection(position, false, click_count, window, cx);
 2369
 2370        let position = position.to_offset(&display_map, Bias::Left);
 2371        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2372
 2373        let mut pending_selection = self
 2374            .selections
 2375            .pending_anchor()
 2376            .expect("extend_selection not called with pending selection");
 2377        if position >= tail {
 2378            pending_selection.start = tail_anchor;
 2379        } else {
 2380            pending_selection.end = tail_anchor;
 2381            pending_selection.reversed = true;
 2382        }
 2383
 2384        let mut pending_mode = self.selections.pending_mode().unwrap();
 2385        match &mut pending_mode {
 2386            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2387            _ => {}
 2388        }
 2389
 2390        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2391            s.set_pending(pending_selection, pending_mode)
 2392        });
 2393    }
 2394
 2395    fn begin_selection(
 2396        &mut self,
 2397        position: DisplayPoint,
 2398        add: bool,
 2399        click_count: usize,
 2400        window: &mut Window,
 2401        cx: &mut Context<Self>,
 2402    ) {
 2403        if !self.focus_handle.is_focused(window) {
 2404            self.last_focused_descendant = None;
 2405            window.focus(&self.focus_handle);
 2406        }
 2407
 2408        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2409        let buffer = &display_map.buffer_snapshot;
 2410        let newest_selection = self.selections.newest_anchor().clone();
 2411        let position = display_map.clip_point(position, Bias::Left);
 2412
 2413        let start;
 2414        let end;
 2415        let mode;
 2416        let mut auto_scroll;
 2417        match click_count {
 2418            1 => {
 2419                start = buffer.anchor_before(position.to_point(&display_map));
 2420                end = start;
 2421                mode = SelectMode::Character;
 2422                auto_scroll = true;
 2423            }
 2424            2 => {
 2425                let range = movement::surrounding_word(&display_map, position);
 2426                start = buffer.anchor_before(range.start.to_point(&display_map));
 2427                end = buffer.anchor_before(range.end.to_point(&display_map));
 2428                mode = SelectMode::Word(start..end);
 2429                auto_scroll = true;
 2430            }
 2431            3 => {
 2432                let position = display_map
 2433                    .clip_point(position, Bias::Left)
 2434                    .to_point(&display_map);
 2435                let line_start = display_map.prev_line_boundary(position).0;
 2436                let next_line_start = buffer.clip_point(
 2437                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2438                    Bias::Left,
 2439                );
 2440                start = buffer.anchor_before(line_start);
 2441                end = buffer.anchor_before(next_line_start);
 2442                mode = SelectMode::Line(start..end);
 2443                auto_scroll = true;
 2444            }
 2445            _ => {
 2446                start = buffer.anchor_before(0);
 2447                end = buffer.anchor_before(buffer.len());
 2448                mode = SelectMode::All;
 2449                auto_scroll = false;
 2450            }
 2451        }
 2452        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2453
 2454        let point_to_delete: Option<usize> = {
 2455            let selected_points: Vec<Selection<Point>> =
 2456                self.selections.disjoint_in_range(start..end, cx);
 2457
 2458            if !add || click_count > 1 {
 2459                None
 2460            } else if !selected_points.is_empty() {
 2461                Some(selected_points[0].id)
 2462            } else {
 2463                let clicked_point_already_selected =
 2464                    self.selections.disjoint.iter().find(|selection| {
 2465                        selection.start.to_point(buffer) == start.to_point(buffer)
 2466                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2467                    });
 2468
 2469                clicked_point_already_selected.map(|selection| selection.id)
 2470            }
 2471        };
 2472
 2473        let selections_count = self.selections.count();
 2474
 2475        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2476            if let Some(point_to_delete) = point_to_delete {
 2477                s.delete(point_to_delete);
 2478
 2479                if selections_count == 1 {
 2480                    s.set_pending_anchor_range(start..end, mode);
 2481                }
 2482            } else {
 2483                if !add {
 2484                    s.clear_disjoint();
 2485                } else if click_count > 1 {
 2486                    s.delete(newest_selection.id)
 2487                }
 2488
 2489                s.set_pending_anchor_range(start..end, mode);
 2490            }
 2491        });
 2492    }
 2493
 2494    fn begin_columnar_selection(
 2495        &mut self,
 2496        position: DisplayPoint,
 2497        goal_column: u32,
 2498        reset: bool,
 2499        window: &mut Window,
 2500        cx: &mut Context<Self>,
 2501    ) {
 2502        if !self.focus_handle.is_focused(window) {
 2503            self.last_focused_descendant = None;
 2504            window.focus(&self.focus_handle);
 2505        }
 2506
 2507        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2508
 2509        if reset {
 2510            let pointer_position = display_map
 2511                .buffer_snapshot
 2512                .anchor_before(position.to_point(&display_map));
 2513
 2514            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2515                s.clear_disjoint();
 2516                s.set_pending_anchor_range(
 2517                    pointer_position..pointer_position,
 2518                    SelectMode::Character,
 2519                );
 2520            });
 2521        }
 2522
 2523        let tail = self.selections.newest::<Point>(cx).tail();
 2524        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2525
 2526        if !reset {
 2527            self.select_columns(
 2528                tail.to_display_point(&display_map),
 2529                position,
 2530                goal_column,
 2531                &display_map,
 2532                window,
 2533                cx,
 2534            );
 2535        }
 2536    }
 2537
 2538    fn update_selection(
 2539        &mut self,
 2540        position: DisplayPoint,
 2541        goal_column: u32,
 2542        scroll_delta: gpui::Point<f32>,
 2543        window: &mut Window,
 2544        cx: &mut Context<Self>,
 2545    ) {
 2546        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2547
 2548        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2549            let tail = tail.to_display_point(&display_map);
 2550            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2551        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2552            let buffer = self.buffer.read(cx).snapshot(cx);
 2553            let head;
 2554            let tail;
 2555            let mode = self.selections.pending_mode().unwrap();
 2556            match &mode {
 2557                SelectMode::Character => {
 2558                    head = position.to_point(&display_map);
 2559                    tail = pending.tail().to_point(&buffer);
 2560                }
 2561                SelectMode::Word(original_range) => {
 2562                    let original_display_range = original_range.start.to_display_point(&display_map)
 2563                        ..original_range.end.to_display_point(&display_map);
 2564                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2565                        ..original_display_range.end.to_point(&display_map);
 2566                    if movement::is_inside_word(&display_map, position)
 2567                        || original_display_range.contains(&position)
 2568                    {
 2569                        let word_range = movement::surrounding_word(&display_map, position);
 2570                        if word_range.start < original_display_range.start {
 2571                            head = word_range.start.to_point(&display_map);
 2572                        } else {
 2573                            head = word_range.end.to_point(&display_map);
 2574                        }
 2575                    } else {
 2576                        head = position.to_point(&display_map);
 2577                    }
 2578
 2579                    if head <= original_buffer_range.start {
 2580                        tail = original_buffer_range.end;
 2581                    } else {
 2582                        tail = original_buffer_range.start;
 2583                    }
 2584                }
 2585                SelectMode::Line(original_range) => {
 2586                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2587
 2588                    let position = display_map
 2589                        .clip_point(position, Bias::Left)
 2590                        .to_point(&display_map);
 2591                    let line_start = display_map.prev_line_boundary(position).0;
 2592                    let next_line_start = buffer.clip_point(
 2593                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2594                        Bias::Left,
 2595                    );
 2596
 2597                    if line_start < original_range.start {
 2598                        head = line_start
 2599                    } else {
 2600                        head = next_line_start
 2601                    }
 2602
 2603                    if head <= original_range.start {
 2604                        tail = original_range.end;
 2605                    } else {
 2606                        tail = original_range.start;
 2607                    }
 2608                }
 2609                SelectMode::All => {
 2610                    return;
 2611                }
 2612            };
 2613
 2614            if head < tail {
 2615                pending.start = buffer.anchor_before(head);
 2616                pending.end = buffer.anchor_before(tail);
 2617                pending.reversed = true;
 2618            } else {
 2619                pending.start = buffer.anchor_before(tail);
 2620                pending.end = buffer.anchor_before(head);
 2621                pending.reversed = false;
 2622            }
 2623
 2624            self.change_selections(None, window, cx, |s| {
 2625                s.set_pending(pending, mode);
 2626            });
 2627        } else {
 2628            log::error!("update_selection dispatched with no pending selection");
 2629            return;
 2630        }
 2631
 2632        self.apply_scroll_delta(scroll_delta, window, cx);
 2633        cx.notify();
 2634    }
 2635
 2636    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2637        self.columnar_selection_tail.take();
 2638        if self.selections.pending_anchor().is_some() {
 2639            let selections = self.selections.all::<usize>(cx);
 2640            self.change_selections(None, window, cx, |s| {
 2641                s.select(selections);
 2642                s.clear_pending();
 2643            });
 2644        }
 2645    }
 2646
 2647    fn select_columns(
 2648        &mut self,
 2649        tail: DisplayPoint,
 2650        head: DisplayPoint,
 2651        goal_column: u32,
 2652        display_map: &DisplaySnapshot,
 2653        window: &mut Window,
 2654        cx: &mut Context<Self>,
 2655    ) {
 2656        let start_row = cmp::min(tail.row(), head.row());
 2657        let end_row = cmp::max(tail.row(), head.row());
 2658        let start_column = cmp::min(tail.column(), goal_column);
 2659        let end_column = cmp::max(tail.column(), goal_column);
 2660        let reversed = start_column < tail.column();
 2661
 2662        let selection_ranges = (start_row.0..=end_row.0)
 2663            .map(DisplayRow)
 2664            .filter_map(|row| {
 2665                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2666                    let start = display_map
 2667                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2668                        .to_point(display_map);
 2669                    let end = display_map
 2670                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2671                        .to_point(display_map);
 2672                    if reversed {
 2673                        Some(end..start)
 2674                    } else {
 2675                        Some(start..end)
 2676                    }
 2677                } else {
 2678                    None
 2679                }
 2680            })
 2681            .collect::<Vec<_>>();
 2682
 2683        self.change_selections(None, window, cx, |s| {
 2684            s.select_ranges(selection_ranges);
 2685        });
 2686        cx.notify();
 2687    }
 2688
 2689    pub fn has_pending_nonempty_selection(&self) -> bool {
 2690        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2691            Some(Selection { start, end, .. }) => start != end,
 2692            None => false,
 2693        };
 2694
 2695        pending_nonempty_selection
 2696            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2697    }
 2698
 2699    pub fn has_pending_selection(&self) -> bool {
 2700        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2701    }
 2702
 2703    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2704        self.selection_mark_mode = false;
 2705
 2706        if self.clear_expanded_diff_hunks(cx) {
 2707            cx.notify();
 2708            return;
 2709        }
 2710        if self.dismiss_menus_and_popups(true, window, cx) {
 2711            return;
 2712        }
 2713
 2714        if self.mode == EditorMode::Full
 2715            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2716        {
 2717            return;
 2718        }
 2719
 2720        cx.propagate();
 2721    }
 2722
 2723    pub fn dismiss_menus_and_popups(
 2724        &mut self,
 2725        is_user_requested: bool,
 2726        window: &mut Window,
 2727        cx: &mut Context<Self>,
 2728    ) -> bool {
 2729        if self.take_rename(false, window, cx).is_some() {
 2730            return true;
 2731        }
 2732
 2733        if hide_hover(self, cx) {
 2734            return true;
 2735        }
 2736
 2737        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2738            return true;
 2739        }
 2740
 2741        if self.hide_context_menu(window, cx).is_some() {
 2742            return true;
 2743        }
 2744
 2745        if self.mouse_context_menu.take().is_some() {
 2746            return true;
 2747        }
 2748
 2749        if is_user_requested && self.discard_inline_completion(true, cx) {
 2750            return true;
 2751        }
 2752
 2753        if self.snippet_stack.pop().is_some() {
 2754            return true;
 2755        }
 2756
 2757        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2758            self.dismiss_diagnostics(cx);
 2759            return true;
 2760        }
 2761
 2762        false
 2763    }
 2764
 2765    fn linked_editing_ranges_for(
 2766        &self,
 2767        selection: Range<text::Anchor>,
 2768        cx: &App,
 2769    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2770        if self.linked_edit_ranges.is_empty() {
 2771            return None;
 2772        }
 2773        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2774            selection.end.buffer_id.and_then(|end_buffer_id| {
 2775                if selection.start.buffer_id != Some(end_buffer_id) {
 2776                    return None;
 2777                }
 2778                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2779                let snapshot = buffer.read(cx).snapshot();
 2780                self.linked_edit_ranges
 2781                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2782                    .map(|ranges| (ranges, snapshot, buffer))
 2783            })?;
 2784        use text::ToOffset as TO;
 2785        // find offset from the start of current range to current cursor position
 2786        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2787
 2788        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2789        let start_difference = start_offset - start_byte_offset;
 2790        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2791        let end_difference = end_offset - start_byte_offset;
 2792        // Current range has associated linked ranges.
 2793        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2794        for range in linked_ranges.iter() {
 2795            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2796            let end_offset = start_offset + end_difference;
 2797            let start_offset = start_offset + start_difference;
 2798            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2799                continue;
 2800            }
 2801            if self.selections.disjoint_anchor_ranges().any(|s| {
 2802                if s.start.buffer_id != selection.start.buffer_id
 2803                    || s.end.buffer_id != selection.end.buffer_id
 2804                {
 2805                    return false;
 2806                }
 2807                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2808                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2809            }) {
 2810                continue;
 2811            }
 2812            let start = buffer_snapshot.anchor_after(start_offset);
 2813            let end = buffer_snapshot.anchor_after(end_offset);
 2814            linked_edits
 2815                .entry(buffer.clone())
 2816                .or_default()
 2817                .push(start..end);
 2818        }
 2819        Some(linked_edits)
 2820    }
 2821
 2822    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2823        let text: Arc<str> = text.into();
 2824
 2825        if self.read_only(cx) {
 2826            return;
 2827        }
 2828
 2829        let selections = self.selections.all_adjusted(cx);
 2830        let mut bracket_inserted = false;
 2831        let mut edits = Vec::new();
 2832        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2833        let mut new_selections = Vec::with_capacity(selections.len());
 2834        let mut new_autoclose_regions = Vec::new();
 2835        let snapshot = self.buffer.read(cx).read(cx);
 2836
 2837        for (selection, autoclose_region) in
 2838            self.selections_with_autoclose_regions(selections, &snapshot)
 2839        {
 2840            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2841                // Determine if the inserted text matches the opening or closing
 2842                // bracket of any of this language's bracket pairs.
 2843                let mut bracket_pair = None;
 2844                let mut is_bracket_pair_start = false;
 2845                let mut is_bracket_pair_end = false;
 2846                if !text.is_empty() {
 2847                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2848                    //  and they are removing the character that triggered IME popup.
 2849                    for (pair, enabled) in scope.brackets() {
 2850                        if !pair.close && !pair.surround {
 2851                            continue;
 2852                        }
 2853
 2854                        if enabled && pair.start.ends_with(text.as_ref()) {
 2855                            let prefix_len = pair.start.len() - text.len();
 2856                            let preceding_text_matches_prefix = prefix_len == 0
 2857                                || (selection.start.column >= (prefix_len as u32)
 2858                                    && snapshot.contains_str_at(
 2859                                        Point::new(
 2860                                            selection.start.row,
 2861                                            selection.start.column - (prefix_len as u32),
 2862                                        ),
 2863                                        &pair.start[..prefix_len],
 2864                                    ));
 2865                            if preceding_text_matches_prefix {
 2866                                bracket_pair = Some(pair.clone());
 2867                                is_bracket_pair_start = true;
 2868                                break;
 2869                            }
 2870                        }
 2871                        if pair.end.as_str() == text.as_ref() {
 2872                            bracket_pair = Some(pair.clone());
 2873                            is_bracket_pair_end = true;
 2874                            break;
 2875                        }
 2876                    }
 2877                }
 2878
 2879                if let Some(bracket_pair) = bracket_pair {
 2880                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2881                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2882                    let auto_surround =
 2883                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2884                    if selection.is_empty() {
 2885                        if is_bracket_pair_start {
 2886                            // If the inserted text is a suffix of an opening bracket and the
 2887                            // selection is preceded by the rest of the opening bracket, then
 2888                            // insert the closing bracket.
 2889                            let following_text_allows_autoclose = snapshot
 2890                                .chars_at(selection.start)
 2891                                .next()
 2892                                .map_or(true, |c| scope.should_autoclose_before(c));
 2893
 2894                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2895                                && bracket_pair.start.len() == 1
 2896                            {
 2897                                let target = bracket_pair.start.chars().next().unwrap();
 2898                                let current_line_count = snapshot
 2899                                    .reversed_chars_at(selection.start)
 2900                                    .take_while(|&c| c != '\n')
 2901                                    .filter(|&c| c == target)
 2902                                    .count();
 2903                                current_line_count % 2 == 1
 2904                            } else {
 2905                                false
 2906                            };
 2907
 2908                            if autoclose
 2909                                && bracket_pair.close
 2910                                && following_text_allows_autoclose
 2911                                && !is_closing_quote
 2912                            {
 2913                                let anchor = snapshot.anchor_before(selection.end);
 2914                                new_selections.push((selection.map(|_| anchor), text.len()));
 2915                                new_autoclose_regions.push((
 2916                                    anchor,
 2917                                    text.len(),
 2918                                    selection.id,
 2919                                    bracket_pair.clone(),
 2920                                ));
 2921                                edits.push((
 2922                                    selection.range(),
 2923                                    format!("{}{}", text, bracket_pair.end).into(),
 2924                                ));
 2925                                bracket_inserted = true;
 2926                                continue;
 2927                            }
 2928                        }
 2929
 2930                        if let Some(region) = autoclose_region {
 2931                            // If the selection is followed by an auto-inserted closing bracket,
 2932                            // then don't insert that closing bracket again; just move the selection
 2933                            // past the closing bracket.
 2934                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2935                                && text.as_ref() == region.pair.end.as_str();
 2936                            if should_skip {
 2937                                let anchor = snapshot.anchor_after(selection.end);
 2938                                new_selections
 2939                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2940                                continue;
 2941                            }
 2942                        }
 2943
 2944                        let always_treat_brackets_as_autoclosed = snapshot
 2945                            .settings_at(selection.start, cx)
 2946                            .always_treat_brackets_as_autoclosed;
 2947                        if always_treat_brackets_as_autoclosed
 2948                            && is_bracket_pair_end
 2949                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2950                        {
 2951                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2952                            // and the inserted text is a closing bracket and the selection is followed
 2953                            // by the closing bracket then move the selection past the closing bracket.
 2954                            let anchor = snapshot.anchor_after(selection.end);
 2955                            new_selections.push((selection.map(|_| anchor), text.len()));
 2956                            continue;
 2957                        }
 2958                    }
 2959                    // If an opening bracket is 1 character long and is typed while
 2960                    // text is selected, then surround that text with the bracket pair.
 2961                    else if auto_surround
 2962                        && bracket_pair.surround
 2963                        && is_bracket_pair_start
 2964                        && bracket_pair.start.chars().count() == 1
 2965                    {
 2966                        edits.push((selection.start..selection.start, text.clone()));
 2967                        edits.push((
 2968                            selection.end..selection.end,
 2969                            bracket_pair.end.as_str().into(),
 2970                        ));
 2971                        bracket_inserted = true;
 2972                        new_selections.push((
 2973                            Selection {
 2974                                id: selection.id,
 2975                                start: snapshot.anchor_after(selection.start),
 2976                                end: snapshot.anchor_before(selection.end),
 2977                                reversed: selection.reversed,
 2978                                goal: selection.goal,
 2979                            },
 2980                            0,
 2981                        ));
 2982                        continue;
 2983                    }
 2984                }
 2985            }
 2986
 2987            if self.auto_replace_emoji_shortcode
 2988                && selection.is_empty()
 2989                && text.as_ref().ends_with(':')
 2990            {
 2991                if let Some(possible_emoji_short_code) =
 2992                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2993                {
 2994                    if !possible_emoji_short_code.is_empty() {
 2995                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2996                            let emoji_shortcode_start = Point::new(
 2997                                selection.start.row,
 2998                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2999                            );
 3000
 3001                            // Remove shortcode from buffer
 3002                            edits.push((
 3003                                emoji_shortcode_start..selection.start,
 3004                                "".to_string().into(),
 3005                            ));
 3006                            new_selections.push((
 3007                                Selection {
 3008                                    id: selection.id,
 3009                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3010                                    end: snapshot.anchor_before(selection.start),
 3011                                    reversed: selection.reversed,
 3012                                    goal: selection.goal,
 3013                                },
 3014                                0,
 3015                            ));
 3016
 3017                            // Insert emoji
 3018                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3019                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3020                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3021
 3022                            continue;
 3023                        }
 3024                    }
 3025                }
 3026            }
 3027
 3028            // If not handling any auto-close operation, then just replace the selected
 3029            // text with the given input and move the selection to the end of the
 3030            // newly inserted text.
 3031            let anchor = snapshot.anchor_after(selection.end);
 3032            if !self.linked_edit_ranges.is_empty() {
 3033                let start_anchor = snapshot.anchor_before(selection.start);
 3034
 3035                let is_word_char = text.chars().next().map_or(true, |char| {
 3036                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3037                    classifier.is_word(char)
 3038                });
 3039
 3040                if is_word_char {
 3041                    if let Some(ranges) = self
 3042                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3043                    {
 3044                        for (buffer, edits) in ranges {
 3045                            linked_edits
 3046                                .entry(buffer.clone())
 3047                                .or_default()
 3048                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3049                        }
 3050                    }
 3051                }
 3052            }
 3053
 3054            new_selections.push((selection.map(|_| anchor), 0));
 3055            edits.push((selection.start..selection.end, text.clone()));
 3056        }
 3057
 3058        drop(snapshot);
 3059
 3060        self.transact(window, cx, |this, window, cx| {
 3061            this.buffer.update(cx, |buffer, cx| {
 3062                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3063            });
 3064            for (buffer, edits) in linked_edits {
 3065                buffer.update(cx, |buffer, cx| {
 3066                    let snapshot = buffer.snapshot();
 3067                    let edits = edits
 3068                        .into_iter()
 3069                        .map(|(range, text)| {
 3070                            use text::ToPoint as TP;
 3071                            let end_point = TP::to_point(&range.end, &snapshot);
 3072                            let start_point = TP::to_point(&range.start, &snapshot);
 3073                            (start_point..end_point, text)
 3074                        })
 3075                        .sorted_by_key(|(range, _)| range.start)
 3076                        .collect::<Vec<_>>();
 3077                    buffer.edit(edits, None, cx);
 3078                })
 3079            }
 3080            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3081            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3082            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3083            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3084                .zip(new_selection_deltas)
 3085                .map(|(selection, delta)| Selection {
 3086                    id: selection.id,
 3087                    start: selection.start + delta,
 3088                    end: selection.end + delta,
 3089                    reversed: selection.reversed,
 3090                    goal: SelectionGoal::None,
 3091                })
 3092                .collect::<Vec<_>>();
 3093
 3094            let mut i = 0;
 3095            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3096                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3097                let start = map.buffer_snapshot.anchor_before(position);
 3098                let end = map.buffer_snapshot.anchor_after(position);
 3099                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3100                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3101                        Ordering::Less => i += 1,
 3102                        Ordering::Greater => break,
 3103                        Ordering::Equal => {
 3104                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3105                                Ordering::Less => i += 1,
 3106                                Ordering::Equal => break,
 3107                                Ordering::Greater => break,
 3108                            }
 3109                        }
 3110                    }
 3111                }
 3112                this.autoclose_regions.insert(
 3113                    i,
 3114                    AutocloseRegion {
 3115                        selection_id,
 3116                        range: start..end,
 3117                        pair,
 3118                    },
 3119                );
 3120            }
 3121
 3122            let had_active_inline_completion = this.has_active_inline_completion();
 3123            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3124                s.select(new_selections)
 3125            });
 3126
 3127            if !bracket_inserted {
 3128                if let Some(on_type_format_task) =
 3129                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3130                {
 3131                    on_type_format_task.detach_and_log_err(cx);
 3132                }
 3133            }
 3134
 3135            let editor_settings = EditorSettings::get_global(cx);
 3136            if bracket_inserted
 3137                && (editor_settings.auto_signature_help
 3138                    || editor_settings.show_signature_help_after_edits)
 3139            {
 3140                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3141            }
 3142
 3143            let trigger_in_words =
 3144                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3145            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3146            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3147            this.refresh_inline_completion(true, false, window, cx);
 3148        });
 3149    }
 3150
 3151    fn find_possible_emoji_shortcode_at_position(
 3152        snapshot: &MultiBufferSnapshot,
 3153        position: Point,
 3154    ) -> Option<String> {
 3155        let mut chars = Vec::new();
 3156        let mut found_colon = false;
 3157        for char in snapshot.reversed_chars_at(position).take(100) {
 3158            // Found a possible emoji shortcode in the middle of the buffer
 3159            if found_colon {
 3160                if char.is_whitespace() {
 3161                    chars.reverse();
 3162                    return Some(chars.iter().collect());
 3163                }
 3164                // If the previous character is not a whitespace, we are in the middle of a word
 3165                // and we only want to complete the shortcode if the word is made up of other emojis
 3166                let mut containing_word = String::new();
 3167                for ch in snapshot
 3168                    .reversed_chars_at(position)
 3169                    .skip(chars.len() + 1)
 3170                    .take(100)
 3171                {
 3172                    if ch.is_whitespace() {
 3173                        break;
 3174                    }
 3175                    containing_word.push(ch);
 3176                }
 3177                let containing_word = containing_word.chars().rev().collect::<String>();
 3178                if util::word_consists_of_emojis(containing_word.as_str()) {
 3179                    chars.reverse();
 3180                    return Some(chars.iter().collect());
 3181                }
 3182            }
 3183
 3184            if char.is_whitespace() || !char.is_ascii() {
 3185                return None;
 3186            }
 3187            if char == ':' {
 3188                found_colon = true;
 3189            } else {
 3190                chars.push(char);
 3191            }
 3192        }
 3193        // Found a possible emoji shortcode at the beginning of the buffer
 3194        chars.reverse();
 3195        Some(chars.iter().collect())
 3196    }
 3197
 3198    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3199        self.transact(window, cx, |this, window, cx| {
 3200            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3201                let selections = this.selections.all::<usize>(cx);
 3202                let multi_buffer = this.buffer.read(cx);
 3203                let buffer = multi_buffer.snapshot(cx);
 3204                selections
 3205                    .iter()
 3206                    .map(|selection| {
 3207                        let start_point = selection.start.to_point(&buffer);
 3208                        let mut indent =
 3209                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3210                        indent.len = cmp::min(indent.len, start_point.column);
 3211                        let start = selection.start;
 3212                        let end = selection.end;
 3213                        let selection_is_empty = start == end;
 3214                        let language_scope = buffer.language_scope_at(start);
 3215                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3216                            &language_scope
 3217                        {
 3218                            let leading_whitespace_len = buffer
 3219                                .reversed_chars_at(start)
 3220                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3221                                .map(|c| c.len_utf8())
 3222                                .sum::<usize>();
 3223
 3224                            let trailing_whitespace_len = buffer
 3225                                .chars_at(end)
 3226                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3227                                .map(|c| c.len_utf8())
 3228                                .sum::<usize>();
 3229
 3230                            let insert_extra_newline =
 3231                                language.brackets().any(|(pair, enabled)| {
 3232                                    let pair_start = pair.start.trim_end();
 3233                                    let pair_end = pair.end.trim_start();
 3234
 3235                                    enabled
 3236                                        && pair.newline
 3237                                        && buffer.contains_str_at(
 3238                                            end + trailing_whitespace_len,
 3239                                            pair_end,
 3240                                        )
 3241                                        && buffer.contains_str_at(
 3242                                            (start - leading_whitespace_len)
 3243                                                .saturating_sub(pair_start.len()),
 3244                                            pair_start,
 3245                                        )
 3246                                });
 3247
 3248                            // Comment extension on newline is allowed only for cursor selections
 3249                            let comment_delimiter = maybe!({
 3250                                if !selection_is_empty {
 3251                                    return None;
 3252                                }
 3253
 3254                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3255                                    return None;
 3256                                }
 3257
 3258                                let delimiters = language.line_comment_prefixes();
 3259                                let max_len_of_delimiter =
 3260                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3261                                let (snapshot, range) =
 3262                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3263
 3264                                let mut index_of_first_non_whitespace = 0;
 3265                                let comment_candidate = snapshot
 3266                                    .chars_for_range(range)
 3267                                    .skip_while(|c| {
 3268                                        let should_skip = c.is_whitespace();
 3269                                        if should_skip {
 3270                                            index_of_first_non_whitespace += 1;
 3271                                        }
 3272                                        should_skip
 3273                                    })
 3274                                    .take(max_len_of_delimiter)
 3275                                    .collect::<String>();
 3276                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3277                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3278                                })?;
 3279                                let cursor_is_placed_after_comment_marker =
 3280                                    index_of_first_non_whitespace + comment_prefix.len()
 3281                                        <= start_point.column as usize;
 3282                                if cursor_is_placed_after_comment_marker {
 3283                                    Some(comment_prefix.clone())
 3284                                } else {
 3285                                    None
 3286                                }
 3287                            });
 3288                            (comment_delimiter, insert_extra_newline)
 3289                        } else {
 3290                            (None, false)
 3291                        };
 3292
 3293                        let capacity_for_delimiter = comment_delimiter
 3294                            .as_deref()
 3295                            .map(str::len)
 3296                            .unwrap_or_default();
 3297                        let mut new_text =
 3298                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3299                        new_text.push('\n');
 3300                        new_text.extend(indent.chars());
 3301                        if let Some(delimiter) = &comment_delimiter {
 3302                            new_text.push_str(delimiter);
 3303                        }
 3304                        if insert_extra_newline {
 3305                            new_text = new_text.repeat(2);
 3306                        }
 3307
 3308                        let anchor = buffer.anchor_after(end);
 3309                        let new_selection = selection.map(|_| anchor);
 3310                        (
 3311                            (start..end, new_text),
 3312                            (insert_extra_newline, new_selection),
 3313                        )
 3314                    })
 3315                    .unzip()
 3316            };
 3317
 3318            this.edit_with_autoindent(edits, cx);
 3319            let buffer = this.buffer.read(cx).snapshot(cx);
 3320            let new_selections = selection_fixup_info
 3321                .into_iter()
 3322                .map(|(extra_newline_inserted, new_selection)| {
 3323                    let mut cursor = new_selection.end.to_point(&buffer);
 3324                    if extra_newline_inserted {
 3325                        cursor.row -= 1;
 3326                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3327                    }
 3328                    new_selection.map(|_| cursor)
 3329                })
 3330                .collect();
 3331
 3332            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3333                s.select(new_selections)
 3334            });
 3335            this.refresh_inline_completion(true, false, window, cx);
 3336        });
 3337    }
 3338
 3339    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3340        let buffer = self.buffer.read(cx);
 3341        let snapshot = buffer.snapshot(cx);
 3342
 3343        let mut edits = Vec::new();
 3344        let mut rows = Vec::new();
 3345
 3346        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3347            let cursor = selection.head();
 3348            let row = cursor.row;
 3349
 3350            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3351
 3352            let newline = "\n".to_string();
 3353            edits.push((start_of_line..start_of_line, newline));
 3354
 3355            rows.push(row + rows_inserted as u32);
 3356        }
 3357
 3358        self.transact(window, cx, |editor, window, cx| {
 3359            editor.edit(edits, cx);
 3360
 3361            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3362                let mut index = 0;
 3363                s.move_cursors_with(|map, _, _| {
 3364                    let row = rows[index];
 3365                    index += 1;
 3366
 3367                    let point = Point::new(row, 0);
 3368                    let boundary = map.next_line_boundary(point).1;
 3369                    let clipped = map.clip_point(boundary, Bias::Left);
 3370
 3371                    (clipped, SelectionGoal::None)
 3372                });
 3373            });
 3374
 3375            let mut indent_edits = Vec::new();
 3376            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3377            for row in rows {
 3378                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3379                for (row, indent) in indents {
 3380                    if indent.len == 0 {
 3381                        continue;
 3382                    }
 3383
 3384                    let text = match indent.kind {
 3385                        IndentKind::Space => " ".repeat(indent.len as usize),
 3386                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3387                    };
 3388                    let point = Point::new(row.0, 0);
 3389                    indent_edits.push((point..point, text));
 3390                }
 3391            }
 3392            editor.edit(indent_edits, cx);
 3393        });
 3394    }
 3395
 3396    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3397        let buffer = self.buffer.read(cx);
 3398        let snapshot = buffer.snapshot(cx);
 3399
 3400        let mut edits = Vec::new();
 3401        let mut rows = Vec::new();
 3402        let mut rows_inserted = 0;
 3403
 3404        for selection in self.selections.all_adjusted(cx) {
 3405            let cursor = selection.head();
 3406            let row = cursor.row;
 3407
 3408            let point = Point::new(row + 1, 0);
 3409            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3410
 3411            let newline = "\n".to_string();
 3412            edits.push((start_of_line..start_of_line, newline));
 3413
 3414            rows_inserted += 1;
 3415            rows.push(row + rows_inserted);
 3416        }
 3417
 3418        self.transact(window, cx, |editor, window, cx| {
 3419            editor.edit(edits, cx);
 3420
 3421            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3422                let mut index = 0;
 3423                s.move_cursors_with(|map, _, _| {
 3424                    let row = rows[index];
 3425                    index += 1;
 3426
 3427                    let point = Point::new(row, 0);
 3428                    let boundary = map.next_line_boundary(point).1;
 3429                    let clipped = map.clip_point(boundary, Bias::Left);
 3430
 3431                    (clipped, SelectionGoal::None)
 3432                });
 3433            });
 3434
 3435            let mut indent_edits = Vec::new();
 3436            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3437            for row in rows {
 3438                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3439                for (row, indent) in indents {
 3440                    if indent.len == 0 {
 3441                        continue;
 3442                    }
 3443
 3444                    let text = match indent.kind {
 3445                        IndentKind::Space => " ".repeat(indent.len as usize),
 3446                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3447                    };
 3448                    let point = Point::new(row.0, 0);
 3449                    indent_edits.push((point..point, text));
 3450                }
 3451            }
 3452            editor.edit(indent_edits, cx);
 3453        });
 3454    }
 3455
 3456    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3457        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3458            original_indent_columns: Vec::new(),
 3459        });
 3460        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3461    }
 3462
 3463    fn insert_with_autoindent_mode(
 3464        &mut self,
 3465        text: &str,
 3466        autoindent_mode: Option<AutoindentMode>,
 3467        window: &mut Window,
 3468        cx: &mut Context<Self>,
 3469    ) {
 3470        if self.read_only(cx) {
 3471            return;
 3472        }
 3473
 3474        let text: Arc<str> = text.into();
 3475        self.transact(window, cx, |this, window, cx| {
 3476            let old_selections = this.selections.all_adjusted(cx);
 3477            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3478                let anchors = {
 3479                    let snapshot = buffer.read(cx);
 3480                    old_selections
 3481                        .iter()
 3482                        .map(|s| {
 3483                            let anchor = snapshot.anchor_after(s.head());
 3484                            s.map(|_| anchor)
 3485                        })
 3486                        .collect::<Vec<_>>()
 3487                };
 3488                buffer.edit(
 3489                    old_selections
 3490                        .iter()
 3491                        .map(|s| (s.start..s.end, text.clone())),
 3492                    autoindent_mode,
 3493                    cx,
 3494                );
 3495                anchors
 3496            });
 3497
 3498            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3499                s.select_anchors(selection_anchors);
 3500            });
 3501
 3502            cx.notify();
 3503        });
 3504    }
 3505
 3506    fn trigger_completion_on_input(
 3507        &mut self,
 3508        text: &str,
 3509        trigger_in_words: bool,
 3510        window: &mut Window,
 3511        cx: &mut Context<Self>,
 3512    ) {
 3513        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3514            self.show_completions(
 3515                &ShowCompletions {
 3516                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3517                },
 3518                window,
 3519                cx,
 3520            );
 3521        } else {
 3522            self.hide_context_menu(window, cx);
 3523        }
 3524    }
 3525
 3526    fn is_completion_trigger(
 3527        &self,
 3528        text: &str,
 3529        trigger_in_words: bool,
 3530        cx: &mut Context<Self>,
 3531    ) -> bool {
 3532        let position = self.selections.newest_anchor().head();
 3533        let multibuffer = self.buffer.read(cx);
 3534        let Some(buffer) = position
 3535            .buffer_id
 3536            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3537        else {
 3538            return false;
 3539        };
 3540
 3541        if let Some(completion_provider) = &self.completion_provider {
 3542            completion_provider.is_completion_trigger(
 3543                &buffer,
 3544                position.text_anchor,
 3545                text,
 3546                trigger_in_words,
 3547                cx,
 3548            )
 3549        } else {
 3550            false
 3551        }
 3552    }
 3553
 3554    /// If any empty selections is touching the start of its innermost containing autoclose
 3555    /// region, expand it to select the brackets.
 3556    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3557        let selections = self.selections.all::<usize>(cx);
 3558        let buffer = self.buffer.read(cx).read(cx);
 3559        let new_selections = self
 3560            .selections_with_autoclose_regions(selections, &buffer)
 3561            .map(|(mut selection, region)| {
 3562                if !selection.is_empty() {
 3563                    return selection;
 3564                }
 3565
 3566                if let Some(region) = region {
 3567                    let mut range = region.range.to_offset(&buffer);
 3568                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3569                        range.start -= region.pair.start.len();
 3570                        if buffer.contains_str_at(range.start, &region.pair.start)
 3571                            && buffer.contains_str_at(range.end, &region.pair.end)
 3572                        {
 3573                            range.end += region.pair.end.len();
 3574                            selection.start = range.start;
 3575                            selection.end = range.end;
 3576
 3577                            return selection;
 3578                        }
 3579                    }
 3580                }
 3581
 3582                let always_treat_brackets_as_autoclosed = buffer
 3583                    .settings_at(selection.start, cx)
 3584                    .always_treat_brackets_as_autoclosed;
 3585
 3586                if !always_treat_brackets_as_autoclosed {
 3587                    return selection;
 3588                }
 3589
 3590                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3591                    for (pair, enabled) in scope.brackets() {
 3592                        if !enabled || !pair.close {
 3593                            continue;
 3594                        }
 3595
 3596                        if buffer.contains_str_at(selection.start, &pair.end) {
 3597                            let pair_start_len = pair.start.len();
 3598                            if buffer.contains_str_at(
 3599                                selection.start.saturating_sub(pair_start_len),
 3600                                &pair.start,
 3601                            ) {
 3602                                selection.start -= pair_start_len;
 3603                                selection.end += pair.end.len();
 3604
 3605                                return selection;
 3606                            }
 3607                        }
 3608                    }
 3609                }
 3610
 3611                selection
 3612            })
 3613            .collect();
 3614
 3615        drop(buffer);
 3616        self.change_selections(None, window, cx, |selections| {
 3617            selections.select(new_selections)
 3618        });
 3619    }
 3620
 3621    /// Iterate the given selections, and for each one, find the smallest surrounding
 3622    /// autoclose region. This uses the ordering of the selections and the autoclose
 3623    /// regions to avoid repeated comparisons.
 3624    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3625        &'a self,
 3626        selections: impl IntoIterator<Item = Selection<D>>,
 3627        buffer: &'a MultiBufferSnapshot,
 3628    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3629        let mut i = 0;
 3630        let mut regions = self.autoclose_regions.as_slice();
 3631        selections.into_iter().map(move |selection| {
 3632            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3633
 3634            let mut enclosing = None;
 3635            while let Some(pair_state) = regions.get(i) {
 3636                if pair_state.range.end.to_offset(buffer) < range.start {
 3637                    regions = &regions[i + 1..];
 3638                    i = 0;
 3639                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3640                    break;
 3641                } else {
 3642                    if pair_state.selection_id == selection.id {
 3643                        enclosing = Some(pair_state);
 3644                    }
 3645                    i += 1;
 3646                }
 3647            }
 3648
 3649            (selection, enclosing)
 3650        })
 3651    }
 3652
 3653    /// Remove any autoclose regions that no longer contain their selection.
 3654    fn invalidate_autoclose_regions(
 3655        &mut self,
 3656        mut selections: &[Selection<Anchor>],
 3657        buffer: &MultiBufferSnapshot,
 3658    ) {
 3659        self.autoclose_regions.retain(|state| {
 3660            let mut i = 0;
 3661            while let Some(selection) = selections.get(i) {
 3662                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3663                    selections = &selections[1..];
 3664                    continue;
 3665                }
 3666                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3667                    break;
 3668                }
 3669                if selection.id == state.selection_id {
 3670                    return true;
 3671                } else {
 3672                    i += 1;
 3673                }
 3674            }
 3675            false
 3676        });
 3677    }
 3678
 3679    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3680        let offset = position.to_offset(buffer);
 3681        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3682        if offset > word_range.start && kind == Some(CharKind::Word) {
 3683            Some(
 3684                buffer
 3685                    .text_for_range(word_range.start..offset)
 3686                    .collect::<String>(),
 3687            )
 3688        } else {
 3689            None
 3690        }
 3691    }
 3692
 3693    pub fn toggle_inlay_hints(
 3694        &mut self,
 3695        _: &ToggleInlayHints,
 3696        _: &mut Window,
 3697        cx: &mut Context<Self>,
 3698    ) {
 3699        self.refresh_inlay_hints(
 3700            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3701            cx,
 3702        );
 3703    }
 3704
 3705    pub fn inlay_hints_enabled(&self) -> bool {
 3706        self.inlay_hint_cache.enabled
 3707    }
 3708
 3709    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3710        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3711            return;
 3712        }
 3713
 3714        let reason_description = reason.description();
 3715        let ignore_debounce = matches!(
 3716            reason,
 3717            InlayHintRefreshReason::SettingsChange(_)
 3718                | InlayHintRefreshReason::Toggle(_)
 3719                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3720        );
 3721        let (invalidate_cache, required_languages) = match reason {
 3722            InlayHintRefreshReason::Toggle(enabled) => {
 3723                self.inlay_hint_cache.enabled = enabled;
 3724                if enabled {
 3725                    (InvalidationStrategy::RefreshRequested, None)
 3726                } else {
 3727                    self.inlay_hint_cache.clear();
 3728                    self.splice_inlays(
 3729                        &self
 3730                            .visible_inlay_hints(cx)
 3731                            .iter()
 3732                            .map(|inlay| inlay.id)
 3733                            .collect::<Vec<InlayId>>(),
 3734                        Vec::new(),
 3735                        cx,
 3736                    );
 3737                    return;
 3738                }
 3739            }
 3740            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3741                match self.inlay_hint_cache.update_settings(
 3742                    &self.buffer,
 3743                    new_settings,
 3744                    self.visible_inlay_hints(cx),
 3745                    cx,
 3746                ) {
 3747                    ControlFlow::Break(Some(InlaySplice {
 3748                        to_remove,
 3749                        to_insert,
 3750                    })) => {
 3751                        self.splice_inlays(&to_remove, to_insert, cx);
 3752                        return;
 3753                    }
 3754                    ControlFlow::Break(None) => return,
 3755                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3756                }
 3757            }
 3758            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3759                if let Some(InlaySplice {
 3760                    to_remove,
 3761                    to_insert,
 3762                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3763                {
 3764                    self.splice_inlays(&to_remove, to_insert, cx);
 3765                }
 3766                return;
 3767            }
 3768            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3769            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3770                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3771            }
 3772            InlayHintRefreshReason::RefreshRequested => {
 3773                (InvalidationStrategy::RefreshRequested, None)
 3774            }
 3775        };
 3776
 3777        if let Some(InlaySplice {
 3778            to_remove,
 3779            to_insert,
 3780        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3781            reason_description,
 3782            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3783            invalidate_cache,
 3784            ignore_debounce,
 3785            cx,
 3786        ) {
 3787            self.splice_inlays(&to_remove, to_insert, cx);
 3788        }
 3789    }
 3790
 3791    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3792        self.display_map
 3793            .read(cx)
 3794            .current_inlays()
 3795            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3796            .cloned()
 3797            .collect()
 3798    }
 3799
 3800    pub fn excerpts_for_inlay_hints_query(
 3801        &self,
 3802        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3803        cx: &mut Context<Editor>,
 3804    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3805        let Some(project) = self.project.as_ref() else {
 3806            return HashMap::default();
 3807        };
 3808        let project = project.read(cx);
 3809        let multi_buffer = self.buffer().read(cx);
 3810        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3811        let multi_buffer_visible_start = self
 3812            .scroll_manager
 3813            .anchor()
 3814            .anchor
 3815            .to_point(&multi_buffer_snapshot);
 3816        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3817            multi_buffer_visible_start
 3818                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3819            Bias::Left,
 3820        );
 3821        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3822        multi_buffer_snapshot
 3823            .range_to_buffer_ranges(multi_buffer_visible_range)
 3824            .into_iter()
 3825            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3826            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3827                let buffer_file = project::File::from_dyn(buffer.file())?;
 3828                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3829                let worktree_entry = buffer_worktree
 3830                    .read(cx)
 3831                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3832                if worktree_entry.is_ignored {
 3833                    return None;
 3834                }
 3835
 3836                let language = buffer.language()?;
 3837                if let Some(restrict_to_languages) = restrict_to_languages {
 3838                    if !restrict_to_languages.contains(language) {
 3839                        return None;
 3840                    }
 3841                }
 3842                Some((
 3843                    excerpt_id,
 3844                    (
 3845                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3846                        buffer.version().clone(),
 3847                        excerpt_visible_range,
 3848                    ),
 3849                ))
 3850            })
 3851            .collect()
 3852    }
 3853
 3854    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3855        TextLayoutDetails {
 3856            text_system: window.text_system().clone(),
 3857            editor_style: self.style.clone().unwrap(),
 3858            rem_size: window.rem_size(),
 3859            scroll_anchor: self.scroll_manager.anchor(),
 3860            visible_rows: self.visible_line_count(),
 3861            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3862        }
 3863    }
 3864
 3865    pub fn splice_inlays(
 3866        &self,
 3867        to_remove: &[InlayId],
 3868        to_insert: Vec<Inlay>,
 3869        cx: &mut Context<Self>,
 3870    ) {
 3871        self.display_map.update(cx, |display_map, cx| {
 3872            display_map.splice_inlays(to_remove, to_insert, cx)
 3873        });
 3874        cx.notify();
 3875    }
 3876
 3877    fn trigger_on_type_formatting(
 3878        &self,
 3879        input: String,
 3880        window: &mut Window,
 3881        cx: &mut Context<Self>,
 3882    ) -> Option<Task<Result<()>>> {
 3883        if input.len() != 1 {
 3884            return None;
 3885        }
 3886
 3887        let project = self.project.as_ref()?;
 3888        let position = self.selections.newest_anchor().head();
 3889        let (buffer, buffer_position) = self
 3890            .buffer
 3891            .read(cx)
 3892            .text_anchor_for_position(position, cx)?;
 3893
 3894        let settings = language_settings::language_settings(
 3895            buffer
 3896                .read(cx)
 3897                .language_at(buffer_position)
 3898                .map(|l| l.name()),
 3899            buffer.read(cx).file(),
 3900            cx,
 3901        );
 3902        if !settings.use_on_type_format {
 3903            return None;
 3904        }
 3905
 3906        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3907        // hence we do LSP request & edit on host side only — add formats to host's history.
 3908        let push_to_lsp_host_history = true;
 3909        // If this is not the host, append its history with new edits.
 3910        let push_to_client_history = project.read(cx).is_via_collab();
 3911
 3912        let on_type_formatting = project.update(cx, |project, cx| {
 3913            project.on_type_format(
 3914                buffer.clone(),
 3915                buffer_position,
 3916                input,
 3917                push_to_lsp_host_history,
 3918                cx,
 3919            )
 3920        });
 3921        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3922            if let Some(transaction) = on_type_formatting.await? {
 3923                if push_to_client_history {
 3924                    buffer
 3925                        .update(&mut cx, |buffer, _| {
 3926                            buffer.push_transaction(transaction, Instant::now());
 3927                        })
 3928                        .ok();
 3929                }
 3930                editor.update(&mut cx, |editor, cx| {
 3931                    editor.refresh_document_highlights(cx);
 3932                })?;
 3933            }
 3934            Ok(())
 3935        }))
 3936    }
 3937
 3938    pub fn show_completions(
 3939        &mut self,
 3940        options: &ShowCompletions,
 3941        window: &mut Window,
 3942        cx: &mut Context<Self>,
 3943    ) {
 3944        if self.pending_rename.is_some() {
 3945            return;
 3946        }
 3947
 3948        let Some(provider) = self.completion_provider.as_ref() else {
 3949            return;
 3950        };
 3951
 3952        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3953            return;
 3954        }
 3955
 3956        let position = self.selections.newest_anchor().head();
 3957        if position.diff_base_anchor.is_some() {
 3958            return;
 3959        }
 3960        let (buffer, buffer_position) =
 3961            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3962                output
 3963            } else {
 3964                return;
 3965            };
 3966        let show_completion_documentation = buffer
 3967            .read(cx)
 3968            .snapshot()
 3969            .settings_at(buffer_position, cx)
 3970            .show_completion_documentation;
 3971
 3972        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3973
 3974        let trigger_kind = match &options.trigger {
 3975            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3976                CompletionTriggerKind::TRIGGER_CHARACTER
 3977            }
 3978            _ => CompletionTriggerKind::INVOKED,
 3979        };
 3980        let completion_context = CompletionContext {
 3981            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3982                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3983                    Some(String::from(trigger))
 3984                } else {
 3985                    None
 3986                }
 3987            }),
 3988            trigger_kind,
 3989        };
 3990        let completions =
 3991            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3992        let sort_completions = provider.sort_completions();
 3993
 3994        let id = post_inc(&mut self.next_completion_id);
 3995        let task = cx.spawn_in(window, |editor, mut cx| {
 3996            async move {
 3997                editor.update(&mut cx, |this, _| {
 3998                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3999                })?;
 4000                let completions = completions.await.log_err();
 4001                let menu = if let Some(completions) = completions {
 4002                    let mut menu = CompletionsMenu::new(
 4003                        id,
 4004                        sort_completions,
 4005                        show_completion_documentation,
 4006                        position,
 4007                        buffer.clone(),
 4008                        completions.into(),
 4009                    );
 4010
 4011                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4012                        .await;
 4013
 4014                    menu.visible().then_some(menu)
 4015                } else {
 4016                    None
 4017                };
 4018
 4019                editor.update_in(&mut cx, |editor, window, cx| {
 4020                    match editor.context_menu.borrow().as_ref() {
 4021                        None => {}
 4022                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4023                            if prev_menu.id > id {
 4024                                return;
 4025                            }
 4026                        }
 4027                        _ => return,
 4028                    }
 4029
 4030                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4031                        let mut menu = menu.unwrap();
 4032                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4033
 4034                        *editor.context_menu.borrow_mut() =
 4035                            Some(CodeContextMenu::Completions(menu));
 4036
 4037                        if editor.show_edit_predictions_in_menu() {
 4038                            editor.update_visible_inline_completion(window, cx);
 4039                        } else {
 4040                            editor.discard_inline_completion(false, cx);
 4041                        }
 4042
 4043                        cx.notify();
 4044                    } else if editor.completion_tasks.len() <= 1 {
 4045                        // If there are no more completion tasks and the last menu was
 4046                        // empty, we should hide it.
 4047                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4048                        // If it was already hidden and we don't show inline
 4049                        // completions in the menu, we should also show the
 4050                        // inline-completion when available.
 4051                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4052                            editor.update_visible_inline_completion(window, cx);
 4053                        }
 4054                    }
 4055                })?;
 4056
 4057                Ok::<_, anyhow::Error>(())
 4058            }
 4059            .log_err()
 4060        });
 4061
 4062        self.completion_tasks.push((id, task));
 4063    }
 4064
 4065    pub fn confirm_completion(
 4066        &mut self,
 4067        action: &ConfirmCompletion,
 4068        window: &mut Window,
 4069        cx: &mut Context<Self>,
 4070    ) -> Option<Task<Result<()>>> {
 4071        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4072    }
 4073
 4074    pub fn compose_completion(
 4075        &mut self,
 4076        action: &ComposeCompletion,
 4077        window: &mut Window,
 4078        cx: &mut Context<Self>,
 4079    ) -> Option<Task<Result<()>>> {
 4080        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4081    }
 4082
 4083    fn do_completion(
 4084        &mut self,
 4085        item_ix: Option<usize>,
 4086        intent: CompletionIntent,
 4087        window: &mut Window,
 4088        cx: &mut Context<Editor>,
 4089    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4090        use language::ToOffset as _;
 4091
 4092        let completions_menu =
 4093            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4094                menu
 4095            } else {
 4096                return None;
 4097            };
 4098
 4099        let entries = completions_menu.entries.borrow();
 4100        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4101        if self.show_edit_predictions_in_menu() {
 4102            self.discard_inline_completion(true, cx);
 4103        }
 4104        let candidate_id = mat.candidate_id;
 4105        drop(entries);
 4106
 4107        let buffer_handle = completions_menu.buffer;
 4108        let completion = completions_menu
 4109            .completions
 4110            .borrow()
 4111            .get(candidate_id)?
 4112            .clone();
 4113        cx.stop_propagation();
 4114
 4115        let snippet;
 4116        let text;
 4117
 4118        if completion.is_snippet() {
 4119            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4120            text = snippet.as_ref().unwrap().text.clone();
 4121        } else {
 4122            snippet = None;
 4123            text = completion.new_text.clone();
 4124        };
 4125        let selections = self.selections.all::<usize>(cx);
 4126        let buffer = buffer_handle.read(cx);
 4127        let old_range = completion.old_range.to_offset(buffer);
 4128        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4129
 4130        let newest_selection = self.selections.newest_anchor();
 4131        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4132            return None;
 4133        }
 4134
 4135        let lookbehind = newest_selection
 4136            .start
 4137            .text_anchor
 4138            .to_offset(buffer)
 4139            .saturating_sub(old_range.start);
 4140        let lookahead = old_range
 4141            .end
 4142            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4143        let mut common_prefix_len = old_text
 4144            .bytes()
 4145            .zip(text.bytes())
 4146            .take_while(|(a, b)| a == b)
 4147            .count();
 4148
 4149        let snapshot = self.buffer.read(cx).snapshot(cx);
 4150        let mut range_to_replace: Option<Range<isize>> = None;
 4151        let mut ranges = Vec::new();
 4152        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4153        for selection in &selections {
 4154            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4155                let start = selection.start.saturating_sub(lookbehind);
 4156                let end = selection.end + lookahead;
 4157                if selection.id == newest_selection.id {
 4158                    range_to_replace = Some(
 4159                        ((start + common_prefix_len) as isize - selection.start as isize)
 4160                            ..(end as isize - selection.start as isize),
 4161                    );
 4162                }
 4163                ranges.push(start + common_prefix_len..end);
 4164            } else {
 4165                common_prefix_len = 0;
 4166                ranges.clear();
 4167                ranges.extend(selections.iter().map(|s| {
 4168                    if s.id == newest_selection.id {
 4169                        range_to_replace = Some(
 4170                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4171                                - selection.start as isize
 4172                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4173                                    - selection.start as isize,
 4174                        );
 4175                        old_range.clone()
 4176                    } else {
 4177                        s.start..s.end
 4178                    }
 4179                }));
 4180                break;
 4181            }
 4182            if !self.linked_edit_ranges.is_empty() {
 4183                let start_anchor = snapshot.anchor_before(selection.head());
 4184                let end_anchor = snapshot.anchor_after(selection.tail());
 4185                if let Some(ranges) = self
 4186                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4187                {
 4188                    for (buffer, edits) in ranges {
 4189                        linked_edits.entry(buffer.clone()).or_default().extend(
 4190                            edits
 4191                                .into_iter()
 4192                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4193                        );
 4194                    }
 4195                }
 4196            }
 4197        }
 4198        let text = &text[common_prefix_len..];
 4199
 4200        cx.emit(EditorEvent::InputHandled {
 4201            utf16_range_to_replace: range_to_replace,
 4202            text: text.into(),
 4203        });
 4204
 4205        self.transact(window, cx, |this, window, cx| {
 4206            if let Some(mut snippet) = snippet {
 4207                snippet.text = text.to_string();
 4208                for tabstop in snippet
 4209                    .tabstops
 4210                    .iter_mut()
 4211                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4212                {
 4213                    tabstop.start -= common_prefix_len as isize;
 4214                    tabstop.end -= common_prefix_len as isize;
 4215                }
 4216
 4217                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4218            } else {
 4219                this.buffer.update(cx, |buffer, cx| {
 4220                    buffer.edit(
 4221                        ranges.iter().map(|range| (range.clone(), text)),
 4222                        this.autoindent_mode.clone(),
 4223                        cx,
 4224                    );
 4225                });
 4226            }
 4227            for (buffer, edits) in linked_edits {
 4228                buffer.update(cx, |buffer, cx| {
 4229                    let snapshot = buffer.snapshot();
 4230                    let edits = edits
 4231                        .into_iter()
 4232                        .map(|(range, text)| {
 4233                            use text::ToPoint as TP;
 4234                            let end_point = TP::to_point(&range.end, &snapshot);
 4235                            let start_point = TP::to_point(&range.start, &snapshot);
 4236                            (start_point..end_point, text)
 4237                        })
 4238                        .sorted_by_key(|(range, _)| range.start)
 4239                        .collect::<Vec<_>>();
 4240                    buffer.edit(edits, None, cx);
 4241                })
 4242            }
 4243
 4244            this.refresh_inline_completion(true, false, window, cx);
 4245        });
 4246
 4247        let show_new_completions_on_confirm = completion
 4248            .confirm
 4249            .as_ref()
 4250            .map_or(false, |confirm| confirm(intent, window, cx));
 4251        if show_new_completions_on_confirm {
 4252            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4253        }
 4254
 4255        let provider = self.completion_provider.as_ref()?;
 4256        drop(completion);
 4257        let apply_edits = provider.apply_additional_edits_for_completion(
 4258            buffer_handle,
 4259            completions_menu.completions.clone(),
 4260            candidate_id,
 4261            true,
 4262            cx,
 4263        );
 4264
 4265        let editor_settings = EditorSettings::get_global(cx);
 4266        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4267            // After the code completion is finished, users often want to know what signatures are needed.
 4268            // so we should automatically call signature_help
 4269            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4270        }
 4271
 4272        Some(cx.foreground_executor().spawn(async move {
 4273            apply_edits.await?;
 4274            Ok(())
 4275        }))
 4276    }
 4277
 4278    pub fn toggle_code_actions(
 4279        &mut self,
 4280        action: &ToggleCodeActions,
 4281        window: &mut Window,
 4282        cx: &mut Context<Self>,
 4283    ) {
 4284        let mut context_menu = self.context_menu.borrow_mut();
 4285        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4286            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4287                // Toggle if we're selecting the same one
 4288                *context_menu = None;
 4289                cx.notify();
 4290                return;
 4291            } else {
 4292                // Otherwise, clear it and start a new one
 4293                *context_menu = None;
 4294                cx.notify();
 4295            }
 4296        }
 4297        drop(context_menu);
 4298        let snapshot = self.snapshot(window, cx);
 4299        let deployed_from_indicator = action.deployed_from_indicator;
 4300        let mut task = self.code_actions_task.take();
 4301        let action = action.clone();
 4302        cx.spawn_in(window, |editor, mut cx| async move {
 4303            while let Some(prev_task) = task {
 4304                prev_task.await.log_err();
 4305                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4306            }
 4307
 4308            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4309                if editor.focus_handle.is_focused(window) {
 4310                    let multibuffer_point = action
 4311                        .deployed_from_indicator
 4312                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4313                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4314                    let (buffer, buffer_row) = snapshot
 4315                        .buffer_snapshot
 4316                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4317                        .and_then(|(buffer_snapshot, range)| {
 4318                            editor
 4319                                .buffer
 4320                                .read(cx)
 4321                                .buffer(buffer_snapshot.remote_id())
 4322                                .map(|buffer| (buffer, range.start.row))
 4323                        })?;
 4324                    let (_, code_actions) = editor
 4325                        .available_code_actions
 4326                        .clone()
 4327                        .and_then(|(location, code_actions)| {
 4328                            let snapshot = location.buffer.read(cx).snapshot();
 4329                            let point_range = location.range.to_point(&snapshot);
 4330                            let point_range = point_range.start.row..=point_range.end.row;
 4331                            if point_range.contains(&buffer_row) {
 4332                                Some((location, code_actions))
 4333                            } else {
 4334                                None
 4335                            }
 4336                        })
 4337                        .unzip();
 4338                    let buffer_id = buffer.read(cx).remote_id();
 4339                    let tasks = editor
 4340                        .tasks
 4341                        .get(&(buffer_id, buffer_row))
 4342                        .map(|t| Arc::new(t.to_owned()));
 4343                    if tasks.is_none() && code_actions.is_none() {
 4344                        return None;
 4345                    }
 4346
 4347                    editor.completion_tasks.clear();
 4348                    editor.discard_inline_completion(false, cx);
 4349                    let task_context =
 4350                        tasks
 4351                            .as_ref()
 4352                            .zip(editor.project.clone())
 4353                            .map(|(tasks, project)| {
 4354                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4355                            });
 4356
 4357                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4358                        let task_context = match task_context {
 4359                            Some(task_context) => task_context.await,
 4360                            None => None,
 4361                        };
 4362                        let resolved_tasks =
 4363                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4364                                Rc::new(ResolvedTasks {
 4365                                    templates: tasks.resolve(&task_context).collect(),
 4366                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4367                                        multibuffer_point.row,
 4368                                        tasks.column,
 4369                                    )),
 4370                                })
 4371                            });
 4372                        let spawn_straight_away = resolved_tasks
 4373                            .as_ref()
 4374                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4375                            && code_actions
 4376                                .as_ref()
 4377                                .map_or(true, |actions| actions.is_empty());
 4378                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4379                            *editor.context_menu.borrow_mut() =
 4380                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4381                                    buffer,
 4382                                    actions: CodeActionContents {
 4383                                        tasks: resolved_tasks,
 4384                                        actions: code_actions,
 4385                                    },
 4386                                    selected_item: Default::default(),
 4387                                    scroll_handle: UniformListScrollHandle::default(),
 4388                                    deployed_from_indicator,
 4389                                }));
 4390                            if spawn_straight_away {
 4391                                if let Some(task) = editor.confirm_code_action(
 4392                                    &ConfirmCodeAction { item_ix: Some(0) },
 4393                                    window,
 4394                                    cx,
 4395                                ) {
 4396                                    cx.notify();
 4397                                    return task;
 4398                                }
 4399                            }
 4400                            cx.notify();
 4401                            Task::ready(Ok(()))
 4402                        }) {
 4403                            task.await
 4404                        } else {
 4405                            Ok(())
 4406                        }
 4407                    }))
 4408                } else {
 4409                    Some(Task::ready(Ok(())))
 4410                }
 4411            })?;
 4412            if let Some(task) = spawned_test_task {
 4413                task.await?;
 4414            }
 4415
 4416            Ok::<_, anyhow::Error>(())
 4417        })
 4418        .detach_and_log_err(cx);
 4419    }
 4420
 4421    pub fn confirm_code_action(
 4422        &mut self,
 4423        action: &ConfirmCodeAction,
 4424        window: &mut Window,
 4425        cx: &mut Context<Self>,
 4426    ) -> Option<Task<Result<()>>> {
 4427        let actions_menu =
 4428            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4429                menu
 4430            } else {
 4431                return None;
 4432            };
 4433        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4434        let action = actions_menu.actions.get(action_ix)?;
 4435        let title = action.label();
 4436        let buffer = actions_menu.buffer;
 4437        let workspace = self.workspace()?;
 4438
 4439        match action {
 4440            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4441                workspace.update(cx, |workspace, cx| {
 4442                    workspace::tasks::schedule_resolved_task(
 4443                        workspace,
 4444                        task_source_kind,
 4445                        resolved_task,
 4446                        false,
 4447                        cx,
 4448                    );
 4449
 4450                    Some(Task::ready(Ok(())))
 4451                })
 4452            }
 4453            CodeActionsItem::CodeAction {
 4454                excerpt_id,
 4455                action,
 4456                provider,
 4457            } => {
 4458                let apply_code_action =
 4459                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4460                let workspace = workspace.downgrade();
 4461                Some(cx.spawn_in(window, |editor, cx| async move {
 4462                    let project_transaction = apply_code_action.await?;
 4463                    Self::open_project_transaction(
 4464                        &editor,
 4465                        workspace,
 4466                        project_transaction,
 4467                        title,
 4468                        cx,
 4469                    )
 4470                    .await
 4471                }))
 4472            }
 4473        }
 4474    }
 4475
 4476    pub async fn open_project_transaction(
 4477        this: &WeakEntity<Editor>,
 4478        workspace: WeakEntity<Workspace>,
 4479        transaction: ProjectTransaction,
 4480        title: String,
 4481        mut cx: AsyncWindowContext,
 4482    ) -> Result<()> {
 4483        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4484        cx.update(|_, cx| {
 4485            entries.sort_unstable_by_key(|(buffer, _)| {
 4486                buffer.read(cx).file().map(|f| f.path().clone())
 4487            });
 4488        })?;
 4489
 4490        // If the project transaction's edits are all contained within this editor, then
 4491        // avoid opening a new editor to display them.
 4492
 4493        if let Some((buffer, transaction)) = entries.first() {
 4494            if entries.len() == 1 {
 4495                let excerpt = this.update(&mut cx, |editor, cx| {
 4496                    editor
 4497                        .buffer()
 4498                        .read(cx)
 4499                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4500                })?;
 4501                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4502                    if excerpted_buffer == *buffer {
 4503                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4504                            let excerpt_range = excerpt_range.to_offset(buffer);
 4505                            buffer
 4506                                .edited_ranges_for_transaction::<usize>(transaction)
 4507                                .all(|range| {
 4508                                    excerpt_range.start <= range.start
 4509                                        && excerpt_range.end >= range.end
 4510                                })
 4511                        })?;
 4512
 4513                        if all_edits_within_excerpt {
 4514                            return Ok(());
 4515                        }
 4516                    }
 4517                }
 4518            }
 4519        } else {
 4520            return Ok(());
 4521        }
 4522
 4523        let mut ranges_to_highlight = Vec::new();
 4524        let excerpt_buffer = cx.new(|cx| {
 4525            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4526            for (buffer_handle, transaction) in &entries {
 4527                let buffer = buffer_handle.read(cx);
 4528                ranges_to_highlight.extend(
 4529                    multibuffer.push_excerpts_with_context_lines(
 4530                        buffer_handle.clone(),
 4531                        buffer
 4532                            .edited_ranges_for_transaction::<usize>(transaction)
 4533                            .collect(),
 4534                        DEFAULT_MULTIBUFFER_CONTEXT,
 4535                        cx,
 4536                    ),
 4537                );
 4538            }
 4539            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4540            multibuffer
 4541        })?;
 4542
 4543        workspace.update_in(&mut cx, |workspace, window, cx| {
 4544            let project = workspace.project().clone();
 4545            let editor = cx
 4546                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4547            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4548            editor.update(cx, |editor, cx| {
 4549                editor.highlight_background::<Self>(
 4550                    &ranges_to_highlight,
 4551                    |theme| theme.editor_highlighted_line_background,
 4552                    cx,
 4553                );
 4554            });
 4555        })?;
 4556
 4557        Ok(())
 4558    }
 4559
 4560    pub fn clear_code_action_providers(&mut self) {
 4561        self.code_action_providers.clear();
 4562        self.available_code_actions.take();
 4563    }
 4564
 4565    pub fn add_code_action_provider(
 4566        &mut self,
 4567        provider: Rc<dyn CodeActionProvider>,
 4568        window: &mut Window,
 4569        cx: &mut Context<Self>,
 4570    ) {
 4571        if self
 4572            .code_action_providers
 4573            .iter()
 4574            .any(|existing_provider| existing_provider.id() == provider.id())
 4575        {
 4576            return;
 4577        }
 4578
 4579        self.code_action_providers.push(provider);
 4580        self.refresh_code_actions(window, cx);
 4581    }
 4582
 4583    pub fn remove_code_action_provider(
 4584        &mut self,
 4585        id: Arc<str>,
 4586        window: &mut Window,
 4587        cx: &mut Context<Self>,
 4588    ) {
 4589        self.code_action_providers
 4590            .retain(|provider| provider.id() != id);
 4591        self.refresh_code_actions(window, cx);
 4592    }
 4593
 4594    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4595        let buffer = self.buffer.read(cx);
 4596        let newest_selection = self.selections.newest_anchor().clone();
 4597        if newest_selection.head().diff_base_anchor.is_some() {
 4598            return None;
 4599        }
 4600        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4601        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4602        if start_buffer != end_buffer {
 4603            return None;
 4604        }
 4605
 4606        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4607            cx.background_executor()
 4608                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4609                .await;
 4610
 4611            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4612                let providers = this.code_action_providers.clone();
 4613                let tasks = this
 4614                    .code_action_providers
 4615                    .iter()
 4616                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4617                    .collect::<Vec<_>>();
 4618                (providers, tasks)
 4619            })?;
 4620
 4621            let mut actions = Vec::new();
 4622            for (provider, provider_actions) in
 4623                providers.into_iter().zip(future::join_all(tasks).await)
 4624            {
 4625                if let Some(provider_actions) = provider_actions.log_err() {
 4626                    actions.extend(provider_actions.into_iter().map(|action| {
 4627                        AvailableCodeAction {
 4628                            excerpt_id: newest_selection.start.excerpt_id,
 4629                            action,
 4630                            provider: provider.clone(),
 4631                        }
 4632                    }));
 4633                }
 4634            }
 4635
 4636            this.update(&mut cx, |this, cx| {
 4637                this.available_code_actions = if actions.is_empty() {
 4638                    None
 4639                } else {
 4640                    Some((
 4641                        Location {
 4642                            buffer: start_buffer,
 4643                            range: start..end,
 4644                        },
 4645                        actions.into(),
 4646                    ))
 4647                };
 4648                cx.notify();
 4649            })
 4650        }));
 4651        None
 4652    }
 4653
 4654    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4655        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4656            self.show_git_blame_inline = false;
 4657
 4658            self.show_git_blame_inline_delay_task =
 4659                Some(cx.spawn_in(window, |this, mut cx| async move {
 4660                    cx.background_executor().timer(delay).await;
 4661
 4662                    this.update(&mut cx, |this, cx| {
 4663                        this.show_git_blame_inline = true;
 4664                        cx.notify();
 4665                    })
 4666                    .log_err();
 4667                }));
 4668        }
 4669    }
 4670
 4671    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4672        if self.pending_rename.is_some() {
 4673            return None;
 4674        }
 4675
 4676        let provider = self.semantics_provider.clone()?;
 4677        let buffer = self.buffer.read(cx);
 4678        let newest_selection = self.selections.newest_anchor().clone();
 4679        let cursor_position = newest_selection.head();
 4680        let (cursor_buffer, cursor_buffer_position) =
 4681            buffer.text_anchor_for_position(cursor_position, cx)?;
 4682        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4683        if cursor_buffer != tail_buffer {
 4684            return None;
 4685        }
 4686        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4687        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4688            cx.background_executor()
 4689                .timer(Duration::from_millis(debounce))
 4690                .await;
 4691
 4692            let highlights = if let Some(highlights) = cx
 4693                .update(|cx| {
 4694                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4695                })
 4696                .ok()
 4697                .flatten()
 4698            {
 4699                highlights.await.log_err()
 4700            } else {
 4701                None
 4702            };
 4703
 4704            if let Some(highlights) = highlights {
 4705                this.update(&mut cx, |this, cx| {
 4706                    if this.pending_rename.is_some() {
 4707                        return;
 4708                    }
 4709
 4710                    let buffer_id = cursor_position.buffer_id;
 4711                    let buffer = this.buffer.read(cx);
 4712                    if !buffer
 4713                        .text_anchor_for_position(cursor_position, cx)
 4714                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4715                    {
 4716                        return;
 4717                    }
 4718
 4719                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4720                    let mut write_ranges = Vec::new();
 4721                    let mut read_ranges = Vec::new();
 4722                    for highlight in highlights {
 4723                        for (excerpt_id, excerpt_range) in
 4724                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4725                        {
 4726                            let start = highlight
 4727                                .range
 4728                                .start
 4729                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4730                            let end = highlight
 4731                                .range
 4732                                .end
 4733                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4734                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4735                                continue;
 4736                            }
 4737
 4738                            let range = Anchor {
 4739                                buffer_id,
 4740                                excerpt_id,
 4741                                text_anchor: start,
 4742                                diff_base_anchor: None,
 4743                            }..Anchor {
 4744                                buffer_id,
 4745                                excerpt_id,
 4746                                text_anchor: end,
 4747                                diff_base_anchor: None,
 4748                            };
 4749                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4750                                write_ranges.push(range);
 4751                            } else {
 4752                                read_ranges.push(range);
 4753                            }
 4754                        }
 4755                    }
 4756
 4757                    this.highlight_background::<DocumentHighlightRead>(
 4758                        &read_ranges,
 4759                        |theme| theme.editor_document_highlight_read_background,
 4760                        cx,
 4761                    );
 4762                    this.highlight_background::<DocumentHighlightWrite>(
 4763                        &write_ranges,
 4764                        |theme| theme.editor_document_highlight_write_background,
 4765                        cx,
 4766                    );
 4767                    cx.notify();
 4768                })
 4769                .log_err();
 4770            }
 4771        }));
 4772        None
 4773    }
 4774
 4775    pub fn refresh_selected_text_highlights(
 4776        &mut self,
 4777        window: &mut Window,
 4778        cx: &mut Context<Editor>,
 4779    ) {
 4780        self.selection_highlight_task.take();
 4781        if !EditorSettings::get_global(cx).selection_highlight {
 4782            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4783            return;
 4784        }
 4785        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4786        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4787            cx.background_executor()
 4788                .timer(Duration::from_millis(debounce))
 4789                .await;
 4790            let Some(Some(matches_task)) = editor
 4791                .update_in(&mut cx, |editor, _, cx| {
 4792                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4793                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4794                        return None;
 4795                    }
 4796                    let selection = editor.selections.newest::<Point>(cx);
 4797                    if selection.is_empty() || selection.start.row != selection.end.row {
 4798                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4799                        return None;
 4800                    }
 4801                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4802                    Some(cx.background_spawn(async move {
 4803                        let mut ranges = Vec::new();
 4804                        let query = buffer.text_for_range(selection.range()).collect::<String>();
 4805                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4806                            for (search_buffer, search_range, excerpt_id) in
 4807                                buffer.range_to_buffer_ranges(range)
 4808                            {
 4809                                ranges.extend(
 4810                                    project::search::SearchQuery::text(
 4811                                        query.clone(),
 4812                                        false,
 4813                                        false,
 4814                                        false,
 4815                                        Default::default(),
 4816                                        Default::default(),
 4817                                        None,
 4818                                    )
 4819                                    .unwrap()
 4820                                    .search(search_buffer, Some(search_range.clone()))
 4821                                    .await
 4822                                    .into_iter()
 4823                                    .map(|match_range| {
 4824                                        let start = search_buffer
 4825                                            .anchor_after(search_range.start + match_range.start);
 4826                                        let end = search_buffer
 4827                                            .anchor_before(search_range.start + match_range.end);
 4828                                        Anchor::range_in_buffer(
 4829                                            excerpt_id,
 4830                                            search_buffer.remote_id(),
 4831                                            start..end,
 4832                                        )
 4833                                    }),
 4834                                );
 4835                            }
 4836                        }
 4837                        ranges
 4838                    }))
 4839                })
 4840                .log_err()
 4841            else {
 4842                return;
 4843            };
 4844            let matches = matches_task.await;
 4845            editor
 4846                .update_in(&mut cx, |editor, _, cx| {
 4847                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4848                    if !matches.is_empty() {
 4849                        editor.highlight_background::<SelectedTextHighlight>(
 4850                            &matches,
 4851                            |theme| theme.editor_document_highlight_bracket_background,
 4852                            cx,
 4853                        )
 4854                    }
 4855                })
 4856                .log_err();
 4857        }));
 4858    }
 4859
 4860    pub fn refresh_inline_completion(
 4861        &mut self,
 4862        debounce: bool,
 4863        user_requested: bool,
 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
 4872        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4873            self.discard_inline_completion(false, cx);
 4874            return None;
 4875        }
 4876
 4877        if !user_requested
 4878            && (!self.should_show_edit_predictions()
 4879                || !self.is_focused(window)
 4880                || buffer.read(cx).is_empty())
 4881        {
 4882            self.discard_inline_completion(false, cx);
 4883            return None;
 4884        }
 4885
 4886        self.update_visible_inline_completion(window, cx);
 4887        provider.refresh(
 4888            self.project.clone(),
 4889            buffer,
 4890            cursor_buffer_position,
 4891            debounce,
 4892            cx,
 4893        );
 4894        Some(())
 4895    }
 4896
 4897    fn show_edit_predictions_in_menu(&self) -> bool {
 4898        match self.edit_prediction_settings {
 4899            EditPredictionSettings::Disabled => false,
 4900            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4901        }
 4902    }
 4903
 4904    pub fn edit_predictions_enabled(&self) -> bool {
 4905        match self.edit_prediction_settings {
 4906            EditPredictionSettings::Disabled => false,
 4907            EditPredictionSettings::Enabled { .. } => true,
 4908        }
 4909    }
 4910
 4911    fn edit_prediction_requires_modifier(&self) -> bool {
 4912        match self.edit_prediction_settings {
 4913            EditPredictionSettings::Disabled => false,
 4914            EditPredictionSettings::Enabled {
 4915                preview_requires_modifier,
 4916                ..
 4917            } => preview_requires_modifier,
 4918        }
 4919    }
 4920
 4921    fn edit_prediction_settings_at_position(
 4922        &self,
 4923        buffer: &Entity<Buffer>,
 4924        buffer_position: language::Anchor,
 4925        cx: &App,
 4926    ) -> EditPredictionSettings {
 4927        if self.mode != EditorMode::Full
 4928            || !self.show_inline_completions_override.unwrap_or(true)
 4929            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4930        {
 4931            return EditPredictionSettings::Disabled;
 4932        }
 4933
 4934        let buffer = buffer.read(cx);
 4935
 4936        let file = buffer.file();
 4937
 4938        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4939            return EditPredictionSettings::Disabled;
 4940        };
 4941
 4942        let by_provider = matches!(
 4943            self.menu_inline_completions_policy,
 4944            MenuInlineCompletionsPolicy::ByProvider
 4945        );
 4946
 4947        let show_in_menu = by_provider
 4948            && self
 4949                .edit_prediction_provider
 4950                .as_ref()
 4951                .map_or(false, |provider| {
 4952                    provider.provider.show_completions_in_menu()
 4953                });
 4954
 4955        let preview_requires_modifier =
 4956            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4957
 4958        EditPredictionSettings::Enabled {
 4959            show_in_menu,
 4960            preview_requires_modifier,
 4961        }
 4962    }
 4963
 4964    fn should_show_edit_predictions(&self) -> bool {
 4965        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4966    }
 4967
 4968    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4969        matches!(
 4970            self.edit_prediction_preview,
 4971            EditPredictionPreview::Active { .. }
 4972        )
 4973    }
 4974
 4975    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4976        let cursor = self.selections.newest_anchor().head();
 4977        if let Some((buffer, cursor_position)) =
 4978            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4979        {
 4980            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4981        } else {
 4982            false
 4983        }
 4984    }
 4985
 4986    fn inline_completions_enabled_in_buffer(
 4987        &self,
 4988        buffer: &Entity<Buffer>,
 4989        buffer_position: language::Anchor,
 4990        cx: &App,
 4991    ) -> bool {
 4992        maybe!({
 4993            let provider = self.edit_prediction_provider()?;
 4994            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4995                return Some(false);
 4996            }
 4997            let buffer = buffer.read(cx);
 4998            let Some(file) = buffer.file() else {
 4999                return Some(true);
 5000            };
 5001            let settings = all_language_settings(Some(file), cx);
 5002            Some(settings.inline_completions_enabled_for_path(file.path()))
 5003        })
 5004        .unwrap_or(false)
 5005    }
 5006
 5007    fn cycle_inline_completion(
 5008        &mut self,
 5009        direction: Direction,
 5010        window: &mut Window,
 5011        cx: &mut Context<Self>,
 5012    ) -> Option<()> {
 5013        let provider = self.edit_prediction_provider()?;
 5014        let cursor = self.selections.newest_anchor().head();
 5015        let (buffer, cursor_buffer_position) =
 5016            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5017        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5018            return None;
 5019        }
 5020
 5021        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5022        self.update_visible_inline_completion(window, cx);
 5023
 5024        Some(())
 5025    }
 5026
 5027    pub fn show_inline_completion(
 5028        &mut self,
 5029        _: &ShowEditPrediction,
 5030        window: &mut Window,
 5031        cx: &mut Context<Self>,
 5032    ) {
 5033        if !self.has_active_inline_completion() {
 5034            self.refresh_inline_completion(false, true, window, cx);
 5035            return;
 5036        }
 5037
 5038        self.update_visible_inline_completion(window, cx);
 5039    }
 5040
 5041    pub fn display_cursor_names(
 5042        &mut self,
 5043        _: &DisplayCursorNames,
 5044        window: &mut Window,
 5045        cx: &mut Context<Self>,
 5046    ) {
 5047        self.show_cursor_names(window, cx);
 5048    }
 5049
 5050    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5051        self.show_cursor_names = true;
 5052        cx.notify();
 5053        cx.spawn_in(window, |this, mut cx| async move {
 5054            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5055            this.update(&mut cx, |this, cx| {
 5056                this.show_cursor_names = false;
 5057                cx.notify()
 5058            })
 5059            .ok()
 5060        })
 5061        .detach();
 5062    }
 5063
 5064    pub fn next_edit_prediction(
 5065        &mut self,
 5066        _: &NextEditPrediction,
 5067        window: &mut Window,
 5068        cx: &mut Context<Self>,
 5069    ) {
 5070        if self.has_active_inline_completion() {
 5071            self.cycle_inline_completion(Direction::Next, window, cx);
 5072        } else {
 5073            let is_copilot_disabled = self
 5074                .refresh_inline_completion(false, true, window, cx)
 5075                .is_none();
 5076            if is_copilot_disabled {
 5077                cx.propagate();
 5078            }
 5079        }
 5080    }
 5081
 5082    pub fn previous_edit_prediction(
 5083        &mut self,
 5084        _: &PreviousEditPrediction,
 5085        window: &mut Window,
 5086        cx: &mut Context<Self>,
 5087    ) {
 5088        if self.has_active_inline_completion() {
 5089            self.cycle_inline_completion(Direction::Prev, window, cx);
 5090        } else {
 5091            let is_copilot_disabled = self
 5092                .refresh_inline_completion(false, true, window, cx)
 5093                .is_none();
 5094            if is_copilot_disabled {
 5095                cx.propagate();
 5096            }
 5097        }
 5098    }
 5099
 5100    pub fn accept_edit_prediction(
 5101        &mut self,
 5102        _: &AcceptEditPrediction,
 5103        window: &mut Window,
 5104        cx: &mut Context<Self>,
 5105    ) {
 5106        if self.show_edit_predictions_in_menu() {
 5107            self.hide_context_menu(window, cx);
 5108        }
 5109
 5110        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5111            return;
 5112        };
 5113
 5114        self.report_inline_completion_event(
 5115            active_inline_completion.completion_id.clone(),
 5116            true,
 5117            cx,
 5118        );
 5119
 5120        match &active_inline_completion.completion {
 5121            InlineCompletion::Move { target, .. } => {
 5122                let target = *target;
 5123
 5124                if let Some(position_map) = &self.last_position_map {
 5125                    if position_map
 5126                        .visible_row_range
 5127                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5128                        || !self.edit_prediction_requires_modifier()
 5129                    {
 5130                        self.unfold_ranges(&[target..target], true, false, cx);
 5131                        // Note that this is also done in vim's handler of the Tab action.
 5132                        self.change_selections(
 5133                            Some(Autoscroll::newest()),
 5134                            window,
 5135                            cx,
 5136                            |selections| {
 5137                                selections.select_anchor_ranges([target..target]);
 5138                            },
 5139                        );
 5140                        self.clear_row_highlights::<EditPredictionPreview>();
 5141
 5142                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5143                            previous_scroll_position: None,
 5144                        };
 5145                    } else {
 5146                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5147                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5148                        };
 5149                        self.highlight_rows::<EditPredictionPreview>(
 5150                            target..target,
 5151                            cx.theme().colors().editor_highlighted_line_background,
 5152                            true,
 5153                            cx,
 5154                        );
 5155                        self.request_autoscroll(Autoscroll::fit(), cx);
 5156                    }
 5157                }
 5158            }
 5159            InlineCompletion::Edit { edits, .. } => {
 5160                if let Some(provider) = self.edit_prediction_provider() {
 5161                    provider.accept(cx);
 5162                }
 5163
 5164                let snapshot = self.buffer.read(cx).snapshot(cx);
 5165                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5166
 5167                self.buffer.update(cx, |buffer, cx| {
 5168                    buffer.edit(edits.iter().cloned(), None, cx)
 5169                });
 5170
 5171                self.change_selections(None, window, cx, |s| {
 5172                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5173                });
 5174
 5175                self.update_visible_inline_completion(window, cx);
 5176                if self.active_inline_completion.is_none() {
 5177                    self.refresh_inline_completion(true, true, window, cx);
 5178                }
 5179
 5180                cx.notify();
 5181            }
 5182        }
 5183
 5184        self.edit_prediction_requires_modifier_in_leading_space = false;
 5185    }
 5186
 5187    pub fn accept_partial_inline_completion(
 5188        &mut self,
 5189        _: &AcceptPartialEditPrediction,
 5190        window: &mut Window,
 5191        cx: &mut Context<Self>,
 5192    ) {
 5193        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5194            return;
 5195        };
 5196        if self.selections.count() != 1 {
 5197            return;
 5198        }
 5199
 5200        self.report_inline_completion_event(
 5201            active_inline_completion.completion_id.clone(),
 5202            true,
 5203            cx,
 5204        );
 5205
 5206        match &active_inline_completion.completion {
 5207            InlineCompletion::Move { target, .. } => {
 5208                let target = *target;
 5209                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5210                    selections.select_anchor_ranges([target..target]);
 5211                });
 5212            }
 5213            InlineCompletion::Edit { edits, .. } => {
 5214                // Find an insertion that starts at the cursor position.
 5215                let snapshot = self.buffer.read(cx).snapshot(cx);
 5216                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5217                let insertion = edits.iter().find_map(|(range, text)| {
 5218                    let range = range.to_offset(&snapshot);
 5219                    if range.is_empty() && range.start == cursor_offset {
 5220                        Some(text)
 5221                    } else {
 5222                        None
 5223                    }
 5224                });
 5225
 5226                if let Some(text) = insertion {
 5227                    let mut partial_completion = text
 5228                        .chars()
 5229                        .by_ref()
 5230                        .take_while(|c| c.is_alphabetic())
 5231                        .collect::<String>();
 5232                    if partial_completion.is_empty() {
 5233                        partial_completion = text
 5234                            .chars()
 5235                            .by_ref()
 5236                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5237                            .collect::<String>();
 5238                    }
 5239
 5240                    cx.emit(EditorEvent::InputHandled {
 5241                        utf16_range_to_replace: None,
 5242                        text: partial_completion.clone().into(),
 5243                    });
 5244
 5245                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5246
 5247                    self.refresh_inline_completion(true, true, window, cx);
 5248                    cx.notify();
 5249                } else {
 5250                    self.accept_edit_prediction(&Default::default(), window, cx);
 5251                }
 5252            }
 5253        }
 5254    }
 5255
 5256    fn discard_inline_completion(
 5257        &mut self,
 5258        should_report_inline_completion_event: bool,
 5259        cx: &mut Context<Self>,
 5260    ) -> bool {
 5261        if should_report_inline_completion_event {
 5262            let completion_id = self
 5263                .active_inline_completion
 5264                .as_ref()
 5265                .and_then(|active_completion| active_completion.completion_id.clone());
 5266
 5267            self.report_inline_completion_event(completion_id, false, cx);
 5268        }
 5269
 5270        if let Some(provider) = self.edit_prediction_provider() {
 5271            provider.discard(cx);
 5272        }
 5273
 5274        self.take_active_inline_completion(cx)
 5275    }
 5276
 5277    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5278        let Some(provider) = self.edit_prediction_provider() else {
 5279            return;
 5280        };
 5281
 5282        let Some((_, buffer, _)) = self
 5283            .buffer
 5284            .read(cx)
 5285            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5286        else {
 5287            return;
 5288        };
 5289
 5290        let extension = buffer
 5291            .read(cx)
 5292            .file()
 5293            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5294
 5295        let event_type = match accepted {
 5296            true => "Edit Prediction Accepted",
 5297            false => "Edit Prediction Discarded",
 5298        };
 5299        telemetry::event!(
 5300            event_type,
 5301            provider = provider.name(),
 5302            prediction_id = id,
 5303            suggestion_accepted = accepted,
 5304            file_extension = extension,
 5305        );
 5306    }
 5307
 5308    pub fn has_active_inline_completion(&self) -> bool {
 5309        self.active_inline_completion.is_some()
 5310    }
 5311
 5312    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5313        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5314            return false;
 5315        };
 5316
 5317        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5318        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5319        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5320        true
 5321    }
 5322
 5323    /// Returns true when we're displaying the edit prediction popover below the cursor
 5324    /// like we are not previewing and the LSP autocomplete menu is visible
 5325    /// or we are in `when_holding_modifier` mode.
 5326    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5327        if self.edit_prediction_preview_is_active()
 5328            || !self.show_edit_predictions_in_menu()
 5329            || !self.edit_predictions_enabled()
 5330        {
 5331            return false;
 5332        }
 5333
 5334        if self.has_visible_completions_menu() {
 5335            return true;
 5336        }
 5337
 5338        has_completion && self.edit_prediction_requires_modifier()
 5339    }
 5340
 5341    fn handle_modifiers_changed(
 5342        &mut self,
 5343        modifiers: Modifiers,
 5344        position_map: &PositionMap,
 5345        window: &mut Window,
 5346        cx: &mut Context<Self>,
 5347    ) {
 5348        if self.show_edit_predictions_in_menu() {
 5349            self.update_edit_prediction_preview(&modifiers, window, cx);
 5350        }
 5351
 5352        self.update_selection_mode(&modifiers, position_map, window, cx);
 5353
 5354        let mouse_position = window.mouse_position();
 5355        if !position_map.text_hitbox.is_hovered(window) {
 5356            return;
 5357        }
 5358
 5359        self.update_hovered_link(
 5360            position_map.point_for_position(mouse_position),
 5361            &position_map.snapshot,
 5362            modifiers,
 5363            window,
 5364            cx,
 5365        )
 5366    }
 5367
 5368    fn update_selection_mode(
 5369        &mut self,
 5370        modifiers: &Modifiers,
 5371        position_map: &PositionMap,
 5372        window: &mut Window,
 5373        cx: &mut Context<Self>,
 5374    ) {
 5375        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5376            return;
 5377        }
 5378
 5379        let mouse_position = window.mouse_position();
 5380        let point_for_position = position_map.point_for_position(mouse_position);
 5381        let position = point_for_position.previous_valid;
 5382
 5383        self.select(
 5384            SelectPhase::BeginColumnar {
 5385                position,
 5386                reset: false,
 5387                goal_column: point_for_position.exact_unclipped.column(),
 5388            },
 5389            window,
 5390            cx,
 5391        );
 5392    }
 5393
 5394    fn update_edit_prediction_preview(
 5395        &mut self,
 5396        modifiers: &Modifiers,
 5397        window: &mut Window,
 5398        cx: &mut Context<Self>,
 5399    ) {
 5400        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5401        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5402            return;
 5403        };
 5404
 5405        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5406            if matches!(
 5407                self.edit_prediction_preview,
 5408                EditPredictionPreview::Inactive
 5409            ) {
 5410                self.edit_prediction_preview = EditPredictionPreview::Active {
 5411                    previous_scroll_position: None,
 5412                };
 5413
 5414                self.update_visible_inline_completion(window, cx);
 5415                cx.notify();
 5416            }
 5417        } else if let EditPredictionPreview::Active {
 5418            previous_scroll_position,
 5419        } = self.edit_prediction_preview
 5420        {
 5421            if let (Some(previous_scroll_position), Some(position_map)) =
 5422                (previous_scroll_position, self.last_position_map.as_ref())
 5423            {
 5424                self.set_scroll_position(
 5425                    previous_scroll_position
 5426                        .scroll_position(&position_map.snapshot.display_snapshot),
 5427                    window,
 5428                    cx,
 5429                );
 5430            }
 5431
 5432            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5433            self.clear_row_highlights::<EditPredictionPreview>();
 5434            self.update_visible_inline_completion(window, cx);
 5435            cx.notify();
 5436        }
 5437    }
 5438
 5439    fn update_visible_inline_completion(
 5440        &mut self,
 5441        _window: &mut Window,
 5442        cx: &mut Context<Self>,
 5443    ) -> Option<()> {
 5444        let selection = self.selections.newest_anchor();
 5445        let cursor = selection.head();
 5446        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5447        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5448        let excerpt_id = cursor.excerpt_id;
 5449
 5450        let show_in_menu = self.show_edit_predictions_in_menu();
 5451        let completions_menu_has_precedence = !show_in_menu
 5452            && (self.context_menu.borrow().is_some()
 5453                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5454
 5455        if completions_menu_has_precedence
 5456            || !offset_selection.is_empty()
 5457            || self
 5458                .active_inline_completion
 5459                .as_ref()
 5460                .map_or(false, |completion| {
 5461                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5462                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5463                    !invalidation_range.contains(&offset_selection.head())
 5464                })
 5465        {
 5466            self.discard_inline_completion(false, cx);
 5467            return None;
 5468        }
 5469
 5470        self.take_active_inline_completion(cx);
 5471        let Some(provider) = self.edit_prediction_provider() else {
 5472            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5473            return None;
 5474        };
 5475
 5476        let (buffer, cursor_buffer_position) =
 5477            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5478
 5479        self.edit_prediction_settings =
 5480            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5481
 5482        self.edit_prediction_cursor_on_leading_whitespace =
 5483            multibuffer.is_line_whitespace_upto(cursor);
 5484
 5485        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5486        let edits = inline_completion
 5487            .edits
 5488            .into_iter()
 5489            .flat_map(|(range, new_text)| {
 5490                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5491                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5492                Some((start..end, new_text))
 5493            })
 5494            .collect::<Vec<_>>();
 5495        if edits.is_empty() {
 5496            return None;
 5497        }
 5498
 5499        let first_edit_start = edits.first().unwrap().0.start;
 5500        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5501        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5502
 5503        let last_edit_end = edits.last().unwrap().0.end;
 5504        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5505        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5506
 5507        let cursor_row = cursor.to_point(&multibuffer).row;
 5508
 5509        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5510
 5511        let mut inlay_ids = Vec::new();
 5512        let invalidation_row_range;
 5513        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5514            Some(cursor_row..edit_end_row)
 5515        } else if cursor_row > edit_end_row {
 5516            Some(edit_start_row..cursor_row)
 5517        } else {
 5518            None
 5519        };
 5520        let is_move =
 5521            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5522        let completion = if is_move {
 5523            invalidation_row_range =
 5524                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5525            let target = first_edit_start;
 5526            InlineCompletion::Move { target, snapshot }
 5527        } else {
 5528            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5529                && !self.inline_completions_hidden_for_vim_mode;
 5530
 5531            if show_completions_in_buffer {
 5532                if edits
 5533                    .iter()
 5534                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5535                {
 5536                    let mut inlays = Vec::new();
 5537                    for (range, new_text) in &edits {
 5538                        let inlay = Inlay::inline_completion(
 5539                            post_inc(&mut self.next_inlay_id),
 5540                            range.start,
 5541                            new_text.as_str(),
 5542                        );
 5543                        inlay_ids.push(inlay.id);
 5544                        inlays.push(inlay);
 5545                    }
 5546
 5547                    self.splice_inlays(&[], inlays, cx);
 5548                } else {
 5549                    let background_color = cx.theme().status().deleted_background;
 5550                    self.highlight_text::<InlineCompletionHighlight>(
 5551                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5552                        HighlightStyle {
 5553                            background_color: Some(background_color),
 5554                            ..Default::default()
 5555                        },
 5556                        cx,
 5557                    );
 5558                }
 5559            }
 5560
 5561            invalidation_row_range = edit_start_row..edit_end_row;
 5562
 5563            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5564                if provider.show_tab_accept_marker() {
 5565                    EditDisplayMode::TabAccept
 5566                } else {
 5567                    EditDisplayMode::Inline
 5568                }
 5569            } else {
 5570                EditDisplayMode::DiffPopover
 5571            };
 5572
 5573            InlineCompletion::Edit {
 5574                edits,
 5575                edit_preview: inline_completion.edit_preview,
 5576                display_mode,
 5577                snapshot,
 5578            }
 5579        };
 5580
 5581        let invalidation_range = multibuffer
 5582            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5583            ..multibuffer.anchor_after(Point::new(
 5584                invalidation_row_range.end,
 5585                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5586            ));
 5587
 5588        self.stale_inline_completion_in_menu = None;
 5589        self.active_inline_completion = Some(InlineCompletionState {
 5590            inlay_ids,
 5591            completion,
 5592            completion_id: inline_completion.id,
 5593            invalidation_range,
 5594        });
 5595
 5596        cx.notify();
 5597
 5598        Some(())
 5599    }
 5600
 5601    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5602        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5603    }
 5604
 5605    fn render_code_actions_indicator(
 5606        &self,
 5607        _style: &EditorStyle,
 5608        row: DisplayRow,
 5609        is_active: bool,
 5610        cx: &mut Context<Self>,
 5611    ) -> Option<IconButton> {
 5612        if self.available_code_actions.is_some() {
 5613            Some(
 5614                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5615                    .shape(ui::IconButtonShape::Square)
 5616                    .icon_size(IconSize::XSmall)
 5617                    .icon_color(Color::Muted)
 5618                    .toggle_state(is_active)
 5619                    .tooltip({
 5620                        let focus_handle = self.focus_handle.clone();
 5621                        move |window, cx| {
 5622                            Tooltip::for_action_in(
 5623                                "Toggle Code Actions",
 5624                                &ToggleCodeActions {
 5625                                    deployed_from_indicator: None,
 5626                                },
 5627                                &focus_handle,
 5628                                window,
 5629                                cx,
 5630                            )
 5631                        }
 5632                    })
 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        } else {
 5645            None
 5646        }
 5647    }
 5648
 5649    fn clear_tasks(&mut self) {
 5650        self.tasks.clear()
 5651    }
 5652
 5653    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5654        if self.tasks.insert(key, value).is_some() {
 5655            // This case should hopefully be rare, but just in case...
 5656            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5657        }
 5658    }
 5659
 5660    fn build_tasks_context(
 5661        project: &Entity<Project>,
 5662        buffer: &Entity<Buffer>,
 5663        buffer_row: u32,
 5664        tasks: &Arc<RunnableTasks>,
 5665        cx: &mut Context<Self>,
 5666    ) -> Task<Option<task::TaskContext>> {
 5667        let position = Point::new(buffer_row, tasks.column);
 5668        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5669        let location = Location {
 5670            buffer: buffer.clone(),
 5671            range: range_start..range_start,
 5672        };
 5673        // Fill in the environmental variables from the tree-sitter captures
 5674        let mut captured_task_variables = TaskVariables::default();
 5675        for (capture_name, value) in tasks.extra_variables.clone() {
 5676            captured_task_variables.insert(
 5677                task::VariableName::Custom(capture_name.into()),
 5678                value.clone(),
 5679            );
 5680        }
 5681        project.update(cx, |project, cx| {
 5682            project.task_store().update(cx, |task_store, cx| {
 5683                task_store.task_context_for_location(captured_task_variables, location, cx)
 5684            })
 5685        })
 5686    }
 5687
 5688    pub fn spawn_nearest_task(
 5689        &mut self,
 5690        action: &SpawnNearestTask,
 5691        window: &mut Window,
 5692        cx: &mut Context<Self>,
 5693    ) {
 5694        let Some((workspace, _)) = self.workspace.clone() else {
 5695            return;
 5696        };
 5697        let Some(project) = self.project.clone() else {
 5698            return;
 5699        };
 5700
 5701        // Try to find a closest, enclosing node using tree-sitter that has a
 5702        // task
 5703        let Some((buffer, buffer_row, tasks)) = self
 5704            .find_enclosing_node_task(cx)
 5705            // Or find the task that's closest in row-distance.
 5706            .or_else(|| self.find_closest_task(cx))
 5707        else {
 5708            return;
 5709        };
 5710
 5711        let reveal_strategy = action.reveal;
 5712        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5713        cx.spawn_in(window, |_, mut cx| async move {
 5714            let context = task_context.await?;
 5715            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5716
 5717            let resolved = resolved_task.resolved.as_mut()?;
 5718            resolved.reveal = reveal_strategy;
 5719
 5720            workspace
 5721                .update(&mut cx, |workspace, cx| {
 5722                    workspace::tasks::schedule_resolved_task(
 5723                        workspace,
 5724                        task_source_kind,
 5725                        resolved_task,
 5726                        false,
 5727                        cx,
 5728                    );
 5729                })
 5730                .ok()
 5731        })
 5732        .detach();
 5733    }
 5734
 5735    fn find_closest_task(
 5736        &mut self,
 5737        cx: &mut Context<Self>,
 5738    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5739        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5740
 5741        let ((buffer_id, row), tasks) = self
 5742            .tasks
 5743            .iter()
 5744            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5745
 5746        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5747        let tasks = Arc::new(tasks.to_owned());
 5748        Some((buffer, *row, tasks))
 5749    }
 5750
 5751    fn find_enclosing_node_task(
 5752        &mut self,
 5753        cx: &mut Context<Self>,
 5754    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5755        let snapshot = self.buffer.read(cx).snapshot(cx);
 5756        let offset = self.selections.newest::<usize>(cx).head();
 5757        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5758        let buffer_id = excerpt.buffer().remote_id();
 5759
 5760        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5761        let mut cursor = layer.node().walk();
 5762
 5763        while cursor.goto_first_child_for_byte(offset).is_some() {
 5764            if cursor.node().end_byte() == offset {
 5765                cursor.goto_next_sibling();
 5766            }
 5767        }
 5768
 5769        // Ascend to the smallest ancestor that contains the range and has a task.
 5770        loop {
 5771            let node = cursor.node();
 5772            let node_range = node.byte_range();
 5773            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5774
 5775            // Check if this node contains our offset
 5776            if node_range.start <= offset && node_range.end >= offset {
 5777                // If it contains offset, check for task
 5778                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5779                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5780                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5781                }
 5782            }
 5783
 5784            if !cursor.goto_parent() {
 5785                break;
 5786            }
 5787        }
 5788        None
 5789    }
 5790
 5791    fn render_run_indicator(
 5792        &self,
 5793        _style: &EditorStyle,
 5794        is_active: bool,
 5795        row: DisplayRow,
 5796        cx: &mut Context<Self>,
 5797    ) -> IconButton {
 5798        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5799            .shape(ui::IconButtonShape::Square)
 5800            .icon_size(IconSize::XSmall)
 5801            .icon_color(Color::Muted)
 5802            .toggle_state(is_active)
 5803            .on_click(cx.listener(move |editor, _e, window, cx| {
 5804                window.focus(&editor.focus_handle(cx));
 5805                editor.toggle_code_actions(
 5806                    &ToggleCodeActions {
 5807                        deployed_from_indicator: Some(row),
 5808                    },
 5809                    window,
 5810                    cx,
 5811                );
 5812            }))
 5813    }
 5814
 5815    pub fn context_menu_visible(&self) -> bool {
 5816        !self.edit_prediction_preview_is_active()
 5817            && self
 5818                .context_menu
 5819                .borrow()
 5820                .as_ref()
 5821                .map_or(false, |menu| menu.visible())
 5822    }
 5823
 5824    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5825        self.context_menu
 5826            .borrow()
 5827            .as_ref()
 5828            .map(|menu| menu.origin())
 5829    }
 5830
 5831    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5832        px(30.)
 5833    }
 5834
 5835    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5836        if self.read_only(cx) {
 5837            cx.theme().players().read_only()
 5838        } else {
 5839            self.style.as_ref().unwrap().local_player
 5840        }
 5841    }
 5842
 5843    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5844        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5845        let accept_keystroke = accept_binding.keystroke()?;
 5846
 5847        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5848
 5849        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5850            Color::Accent
 5851        } else {
 5852            Color::Muted
 5853        };
 5854
 5855        h_flex()
 5856            .px_0p5()
 5857            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5858            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5859            .text_size(TextSize::XSmall.rems(cx))
 5860            .child(h_flex().children(ui::render_modifiers(
 5861                &accept_keystroke.modifiers,
 5862                PlatformStyle::platform(),
 5863                Some(modifiers_color),
 5864                Some(IconSize::XSmall.rems().into()),
 5865                true,
 5866            )))
 5867            .when(is_platform_style_mac, |parent| {
 5868                parent.child(accept_keystroke.key.clone())
 5869            })
 5870            .when(!is_platform_style_mac, |parent| {
 5871                parent.child(
 5872                    Key::new(
 5873                        util::capitalize(&accept_keystroke.key),
 5874                        Some(Color::Default),
 5875                    )
 5876                    .size(Some(IconSize::XSmall.rems().into())),
 5877                )
 5878            })
 5879            .into()
 5880    }
 5881
 5882    fn render_edit_prediction_line_popover(
 5883        &self,
 5884        label: impl Into<SharedString>,
 5885        icon: Option<IconName>,
 5886        window: &mut Window,
 5887        cx: &App,
 5888    ) -> Option<Div> {
 5889        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5890
 5891        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5892
 5893        let result = h_flex()
 5894            .gap_1()
 5895            .border_1()
 5896            .rounded_lg()
 5897            .shadow_sm()
 5898            .bg(bg_color)
 5899            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5900            .py_0p5()
 5901            .pl_1()
 5902            .pr(padding_right)
 5903            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5904            .child(Label::new(label).size(LabelSize::Small))
 5905            .when_some(icon, |element, icon| {
 5906                element.child(
 5907                    div()
 5908                        .mt(px(1.5))
 5909                        .child(Icon::new(icon).size(IconSize::Small)),
 5910                )
 5911            });
 5912
 5913        Some(result)
 5914    }
 5915
 5916    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5917        let accent_color = cx.theme().colors().text_accent;
 5918        let editor_bg_color = cx.theme().colors().editor_background;
 5919        editor_bg_color.blend(accent_color.opacity(0.1))
 5920    }
 5921
 5922    fn render_edit_prediction_cursor_popover(
 5923        &self,
 5924        min_width: Pixels,
 5925        max_width: Pixels,
 5926        cursor_point: Point,
 5927        style: &EditorStyle,
 5928        accept_keystroke: Option<&gpui::Keystroke>,
 5929        _window: &Window,
 5930        cx: &mut Context<Editor>,
 5931    ) -> Option<AnyElement> {
 5932        let provider = self.edit_prediction_provider.as_ref()?;
 5933
 5934        if provider.provider.needs_terms_acceptance(cx) {
 5935            return Some(
 5936                h_flex()
 5937                    .min_w(min_width)
 5938                    .flex_1()
 5939                    .px_2()
 5940                    .py_1()
 5941                    .gap_3()
 5942                    .elevation_2(cx)
 5943                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5944                    .id("accept-terms")
 5945                    .cursor_pointer()
 5946                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5947                    .on_click(cx.listener(|this, _event, window, cx| {
 5948                        cx.stop_propagation();
 5949                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5950                        window.dispatch_action(
 5951                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5952                            cx,
 5953                        );
 5954                    }))
 5955                    .child(
 5956                        h_flex()
 5957                            .flex_1()
 5958                            .gap_2()
 5959                            .child(Icon::new(IconName::ZedPredict))
 5960                            .child(Label::new("Accept Terms of Service"))
 5961                            .child(div().w_full())
 5962                            .child(
 5963                                Icon::new(IconName::ArrowUpRight)
 5964                                    .color(Color::Muted)
 5965                                    .size(IconSize::Small),
 5966                            )
 5967                            .into_any_element(),
 5968                    )
 5969                    .into_any(),
 5970            );
 5971        }
 5972
 5973        let is_refreshing = provider.provider.is_refreshing(cx);
 5974
 5975        fn pending_completion_container() -> Div {
 5976            h_flex()
 5977                .h_full()
 5978                .flex_1()
 5979                .gap_2()
 5980                .child(Icon::new(IconName::ZedPredict))
 5981        }
 5982
 5983        let completion = match &self.active_inline_completion {
 5984            Some(completion) => match &completion.completion {
 5985                InlineCompletion::Move {
 5986                    target, snapshot, ..
 5987                } if !self.has_visible_completions_menu() => {
 5988                    use text::ToPoint as _;
 5989
 5990                    return Some(
 5991                        h_flex()
 5992                            .px_2()
 5993                            .py_1()
 5994                            .elevation_2(cx)
 5995                            .border_color(cx.theme().colors().border)
 5996                            .rounded_tl(px(0.))
 5997                            .gap_2()
 5998                            .child(
 5999                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6000                                    Icon::new(IconName::ZedPredictDown)
 6001                                } else {
 6002                                    Icon::new(IconName::ZedPredictUp)
 6003                                },
 6004                            )
 6005                            .child(Label::new("Hold").size(LabelSize::Small))
 6006                            .child(h_flex().children(ui::render_modifiers(
 6007                                &accept_keystroke?.modifiers,
 6008                                PlatformStyle::platform(),
 6009                                Some(Color::Default),
 6010                                Some(IconSize::Small.rems().into()),
 6011                                false,
 6012                            )))
 6013                            .into_any(),
 6014                    );
 6015                }
 6016                _ => self.render_edit_prediction_cursor_popover_preview(
 6017                    completion,
 6018                    cursor_point,
 6019                    style,
 6020                    cx,
 6021                )?,
 6022            },
 6023
 6024            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6025                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6026                    stale_completion,
 6027                    cursor_point,
 6028                    style,
 6029                    cx,
 6030                )?,
 6031
 6032                None => {
 6033                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6034                }
 6035            },
 6036
 6037            None => pending_completion_container().child(Label::new("No Prediction")),
 6038        };
 6039
 6040        let completion = if is_refreshing {
 6041            completion
 6042                .with_animation(
 6043                    "loading-completion",
 6044                    Animation::new(Duration::from_secs(2))
 6045                        .repeat()
 6046                        .with_easing(pulsating_between(0.4, 0.8)),
 6047                    |label, delta| label.opacity(delta),
 6048                )
 6049                .into_any_element()
 6050        } else {
 6051            completion.into_any_element()
 6052        };
 6053
 6054        let has_completion = self.active_inline_completion.is_some();
 6055
 6056        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6057        Some(
 6058            h_flex()
 6059                .min_w(min_width)
 6060                .max_w(max_width)
 6061                .flex_1()
 6062                .elevation_2(cx)
 6063                .border_color(cx.theme().colors().border)
 6064                .child(
 6065                    div()
 6066                        .flex_1()
 6067                        .py_1()
 6068                        .px_2()
 6069                        .overflow_hidden()
 6070                        .child(completion),
 6071                )
 6072                .when_some(accept_keystroke, |el, accept_keystroke| {
 6073                    if !accept_keystroke.modifiers.modified() {
 6074                        return el;
 6075                    }
 6076
 6077                    el.child(
 6078                        h_flex()
 6079                            .h_full()
 6080                            .border_l_1()
 6081                            .rounded_r_lg()
 6082                            .border_color(cx.theme().colors().border)
 6083                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6084                            .gap_1()
 6085                            .py_1()
 6086                            .px_2()
 6087                            .child(
 6088                                h_flex()
 6089                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6090                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6091                                    .child(h_flex().children(ui::render_modifiers(
 6092                                        &accept_keystroke.modifiers,
 6093                                        PlatformStyle::platform(),
 6094                                        Some(if !has_completion {
 6095                                            Color::Muted
 6096                                        } else {
 6097                                            Color::Default
 6098                                        }),
 6099                                        None,
 6100                                        false,
 6101                                    ))),
 6102                            )
 6103                            .child(Label::new("Preview").into_any_element())
 6104                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6105                    )
 6106                })
 6107                .into_any(),
 6108        )
 6109    }
 6110
 6111    fn render_edit_prediction_cursor_popover_preview(
 6112        &self,
 6113        completion: &InlineCompletionState,
 6114        cursor_point: Point,
 6115        style: &EditorStyle,
 6116        cx: &mut Context<Editor>,
 6117    ) -> Option<Div> {
 6118        use text::ToPoint as _;
 6119
 6120        fn render_relative_row_jump(
 6121            prefix: impl Into<String>,
 6122            current_row: u32,
 6123            target_row: u32,
 6124        ) -> Div {
 6125            let (row_diff, arrow) = if target_row < current_row {
 6126                (current_row - target_row, IconName::ArrowUp)
 6127            } else {
 6128                (target_row - current_row, IconName::ArrowDown)
 6129            };
 6130
 6131            h_flex()
 6132                .child(
 6133                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6134                        .color(Color::Muted)
 6135                        .size(LabelSize::Small),
 6136                )
 6137                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6138        }
 6139
 6140        match &completion.completion {
 6141            InlineCompletion::Move {
 6142                target, snapshot, ..
 6143            } => Some(
 6144                h_flex()
 6145                    .px_2()
 6146                    .gap_2()
 6147                    .flex_1()
 6148                    .child(
 6149                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6150                            Icon::new(IconName::ZedPredictDown)
 6151                        } else {
 6152                            Icon::new(IconName::ZedPredictUp)
 6153                        },
 6154                    )
 6155                    .child(Label::new("Jump to Edit")),
 6156            ),
 6157
 6158            InlineCompletion::Edit {
 6159                edits,
 6160                edit_preview,
 6161                snapshot,
 6162                display_mode: _,
 6163            } => {
 6164                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6165
 6166                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6167                    &snapshot,
 6168                    &edits,
 6169                    edit_preview.as_ref()?,
 6170                    true,
 6171                    cx,
 6172                )
 6173                .first_line_preview();
 6174
 6175                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6176                    .with_highlights(&style.text, highlighted_edits.highlights);
 6177
 6178                let preview = h_flex()
 6179                    .gap_1()
 6180                    .min_w_16()
 6181                    .child(styled_text)
 6182                    .when(has_more_lines, |parent| parent.child(""));
 6183
 6184                let left = if first_edit_row != cursor_point.row {
 6185                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6186                        .into_any_element()
 6187                } else {
 6188                    Icon::new(IconName::ZedPredict).into_any_element()
 6189                };
 6190
 6191                Some(
 6192                    h_flex()
 6193                        .h_full()
 6194                        .flex_1()
 6195                        .gap_2()
 6196                        .pr_1()
 6197                        .overflow_x_hidden()
 6198                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6199                        .child(left)
 6200                        .child(preview),
 6201                )
 6202            }
 6203        }
 6204    }
 6205
 6206    fn render_context_menu(
 6207        &self,
 6208        style: &EditorStyle,
 6209        max_height_in_lines: u32,
 6210        y_flipped: bool,
 6211        window: &mut Window,
 6212        cx: &mut Context<Editor>,
 6213    ) -> Option<AnyElement> {
 6214        let menu = self.context_menu.borrow();
 6215        let menu = menu.as_ref()?;
 6216        if !menu.visible() {
 6217            return None;
 6218        };
 6219        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6220    }
 6221
 6222    fn render_context_menu_aside(
 6223        &mut self,
 6224        max_size: Size<Pixels>,
 6225        window: &mut Window,
 6226        cx: &mut Context<Editor>,
 6227    ) -> Option<AnyElement> {
 6228        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6229            if menu.visible() {
 6230                menu.render_aside(self, max_size, window, cx)
 6231            } else {
 6232                None
 6233            }
 6234        })
 6235    }
 6236
 6237    fn hide_context_menu(
 6238        &mut self,
 6239        window: &mut Window,
 6240        cx: &mut Context<Self>,
 6241    ) -> Option<CodeContextMenu> {
 6242        cx.notify();
 6243        self.completion_tasks.clear();
 6244        let context_menu = self.context_menu.borrow_mut().take();
 6245        self.stale_inline_completion_in_menu.take();
 6246        self.update_visible_inline_completion(window, cx);
 6247        context_menu
 6248    }
 6249
 6250    fn show_snippet_choices(
 6251        &mut self,
 6252        choices: &Vec<String>,
 6253        selection: Range<Anchor>,
 6254        cx: &mut Context<Self>,
 6255    ) {
 6256        if selection.start.buffer_id.is_none() {
 6257            return;
 6258        }
 6259        let buffer_id = selection.start.buffer_id.unwrap();
 6260        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6261        let id = post_inc(&mut self.next_completion_id);
 6262
 6263        if let Some(buffer) = buffer {
 6264            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6265                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6266            ));
 6267        }
 6268    }
 6269
 6270    pub fn insert_snippet(
 6271        &mut self,
 6272        insertion_ranges: &[Range<usize>],
 6273        snippet: Snippet,
 6274        window: &mut Window,
 6275        cx: &mut Context<Self>,
 6276    ) -> Result<()> {
 6277        struct Tabstop<T> {
 6278            is_end_tabstop: bool,
 6279            ranges: Vec<Range<T>>,
 6280            choices: Option<Vec<String>>,
 6281        }
 6282
 6283        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6284            let snippet_text: Arc<str> = snippet.text.clone().into();
 6285            buffer.edit(
 6286                insertion_ranges
 6287                    .iter()
 6288                    .cloned()
 6289                    .map(|range| (range, snippet_text.clone())),
 6290                Some(AutoindentMode::EachLine),
 6291                cx,
 6292            );
 6293
 6294            let snapshot = &*buffer.read(cx);
 6295            let snippet = &snippet;
 6296            snippet
 6297                .tabstops
 6298                .iter()
 6299                .map(|tabstop| {
 6300                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6301                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6302                    });
 6303                    let mut tabstop_ranges = tabstop
 6304                        .ranges
 6305                        .iter()
 6306                        .flat_map(|tabstop_range| {
 6307                            let mut delta = 0_isize;
 6308                            insertion_ranges.iter().map(move |insertion_range| {
 6309                                let insertion_start = insertion_range.start as isize + delta;
 6310                                delta +=
 6311                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6312
 6313                                let start = ((insertion_start + tabstop_range.start) as usize)
 6314                                    .min(snapshot.len());
 6315                                let end = ((insertion_start + tabstop_range.end) as usize)
 6316                                    .min(snapshot.len());
 6317                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6318                            })
 6319                        })
 6320                        .collect::<Vec<_>>();
 6321                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6322
 6323                    Tabstop {
 6324                        is_end_tabstop,
 6325                        ranges: tabstop_ranges,
 6326                        choices: tabstop.choices.clone(),
 6327                    }
 6328                })
 6329                .collect::<Vec<_>>()
 6330        });
 6331        if let Some(tabstop) = tabstops.first() {
 6332            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6333                s.select_ranges(tabstop.ranges.iter().cloned());
 6334            });
 6335
 6336            if let Some(choices) = &tabstop.choices {
 6337                if let Some(selection) = tabstop.ranges.first() {
 6338                    self.show_snippet_choices(choices, selection.clone(), cx)
 6339                }
 6340            }
 6341
 6342            // If we're already at the last tabstop and it's at the end of the snippet,
 6343            // we're done, we don't need to keep the state around.
 6344            if !tabstop.is_end_tabstop {
 6345                let choices = tabstops
 6346                    .iter()
 6347                    .map(|tabstop| tabstop.choices.clone())
 6348                    .collect();
 6349
 6350                let ranges = tabstops
 6351                    .into_iter()
 6352                    .map(|tabstop| tabstop.ranges)
 6353                    .collect::<Vec<_>>();
 6354
 6355                self.snippet_stack.push(SnippetState {
 6356                    active_index: 0,
 6357                    ranges,
 6358                    choices,
 6359                });
 6360            }
 6361
 6362            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6363            if self.autoclose_regions.is_empty() {
 6364                let snapshot = self.buffer.read(cx).snapshot(cx);
 6365                for selection in &mut self.selections.all::<Point>(cx) {
 6366                    let selection_head = selection.head();
 6367                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6368                        continue;
 6369                    };
 6370
 6371                    let mut bracket_pair = None;
 6372                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6373                    let prev_chars = snapshot
 6374                        .reversed_chars_at(selection_head)
 6375                        .collect::<String>();
 6376                    for (pair, enabled) in scope.brackets() {
 6377                        if enabled
 6378                            && pair.close
 6379                            && prev_chars.starts_with(pair.start.as_str())
 6380                            && next_chars.starts_with(pair.end.as_str())
 6381                        {
 6382                            bracket_pair = Some(pair.clone());
 6383                            break;
 6384                        }
 6385                    }
 6386                    if let Some(pair) = bracket_pair {
 6387                        let start = snapshot.anchor_after(selection_head);
 6388                        let end = snapshot.anchor_after(selection_head);
 6389                        self.autoclose_regions.push(AutocloseRegion {
 6390                            selection_id: selection.id,
 6391                            range: start..end,
 6392                            pair,
 6393                        });
 6394                    }
 6395                }
 6396            }
 6397        }
 6398        Ok(())
 6399    }
 6400
 6401    pub fn move_to_next_snippet_tabstop(
 6402        &mut self,
 6403        window: &mut Window,
 6404        cx: &mut Context<Self>,
 6405    ) -> bool {
 6406        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6407    }
 6408
 6409    pub fn move_to_prev_snippet_tabstop(
 6410        &mut self,
 6411        window: &mut Window,
 6412        cx: &mut Context<Self>,
 6413    ) -> bool {
 6414        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6415    }
 6416
 6417    pub fn move_to_snippet_tabstop(
 6418        &mut self,
 6419        bias: Bias,
 6420        window: &mut Window,
 6421        cx: &mut Context<Self>,
 6422    ) -> bool {
 6423        if let Some(mut snippet) = self.snippet_stack.pop() {
 6424            match bias {
 6425                Bias::Left => {
 6426                    if snippet.active_index > 0 {
 6427                        snippet.active_index -= 1;
 6428                    } else {
 6429                        self.snippet_stack.push(snippet);
 6430                        return false;
 6431                    }
 6432                }
 6433                Bias::Right => {
 6434                    if snippet.active_index + 1 < snippet.ranges.len() {
 6435                        snippet.active_index += 1;
 6436                    } else {
 6437                        self.snippet_stack.push(snippet);
 6438                        return false;
 6439                    }
 6440                }
 6441            }
 6442            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6443                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6444                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6445                });
 6446
 6447                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6448                    if let Some(selection) = current_ranges.first() {
 6449                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6450                    }
 6451                }
 6452
 6453                // If snippet state is not at the last tabstop, push it back on the stack
 6454                if snippet.active_index + 1 < snippet.ranges.len() {
 6455                    self.snippet_stack.push(snippet);
 6456                }
 6457                return true;
 6458            }
 6459        }
 6460
 6461        false
 6462    }
 6463
 6464    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6465        self.transact(window, cx, |this, window, cx| {
 6466            this.select_all(&SelectAll, window, cx);
 6467            this.insert("", window, cx);
 6468        });
 6469    }
 6470
 6471    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6472        self.transact(window, cx, |this, window, cx| {
 6473            this.select_autoclose_pair(window, cx);
 6474            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6475            if !this.linked_edit_ranges.is_empty() {
 6476                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6477                let snapshot = this.buffer.read(cx).snapshot(cx);
 6478
 6479                for selection in selections.iter() {
 6480                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6481                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6482                    if selection_start.buffer_id != selection_end.buffer_id {
 6483                        continue;
 6484                    }
 6485                    if let Some(ranges) =
 6486                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6487                    {
 6488                        for (buffer, entries) in ranges {
 6489                            linked_ranges.entry(buffer).or_default().extend(entries);
 6490                        }
 6491                    }
 6492                }
 6493            }
 6494
 6495            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6496            if !this.selections.line_mode {
 6497                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6498                for selection in &mut selections {
 6499                    if selection.is_empty() {
 6500                        let old_head = selection.head();
 6501                        let mut new_head =
 6502                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6503                                .to_point(&display_map);
 6504                        if let Some((buffer, line_buffer_range)) = display_map
 6505                            .buffer_snapshot
 6506                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6507                        {
 6508                            let indent_size =
 6509                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6510                            let indent_len = match indent_size.kind {
 6511                                IndentKind::Space => {
 6512                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6513                                }
 6514                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6515                            };
 6516                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6517                                let indent_len = indent_len.get();
 6518                                new_head = cmp::min(
 6519                                    new_head,
 6520                                    MultiBufferPoint::new(
 6521                                        old_head.row,
 6522                                        ((old_head.column - 1) / indent_len) * indent_len,
 6523                                    ),
 6524                                );
 6525                            }
 6526                        }
 6527
 6528                        selection.set_head(new_head, SelectionGoal::None);
 6529                    }
 6530                }
 6531            }
 6532
 6533            this.signature_help_state.set_backspace_pressed(true);
 6534            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6535                s.select(selections)
 6536            });
 6537            this.insert("", window, cx);
 6538            let empty_str: Arc<str> = Arc::from("");
 6539            for (buffer, edits) in linked_ranges {
 6540                let snapshot = buffer.read(cx).snapshot();
 6541                use text::ToPoint as TP;
 6542
 6543                let edits = edits
 6544                    .into_iter()
 6545                    .map(|range| {
 6546                        let end_point = TP::to_point(&range.end, &snapshot);
 6547                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6548
 6549                        if end_point == start_point {
 6550                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6551                                .saturating_sub(1);
 6552                            start_point =
 6553                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6554                        };
 6555
 6556                        (start_point..end_point, empty_str.clone())
 6557                    })
 6558                    .sorted_by_key(|(range, _)| range.start)
 6559                    .collect::<Vec<_>>();
 6560                buffer.update(cx, |this, cx| {
 6561                    this.edit(edits, None, cx);
 6562                })
 6563            }
 6564            this.refresh_inline_completion(true, false, window, cx);
 6565            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6566        });
 6567    }
 6568
 6569    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6570        self.transact(window, cx, |this, window, cx| {
 6571            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6572                let line_mode = s.line_mode;
 6573                s.move_with(|map, selection| {
 6574                    if selection.is_empty() && !line_mode {
 6575                        let cursor = movement::right(map, selection.head());
 6576                        selection.end = cursor;
 6577                        selection.reversed = true;
 6578                        selection.goal = SelectionGoal::None;
 6579                    }
 6580                })
 6581            });
 6582            this.insert("", window, cx);
 6583            this.refresh_inline_completion(true, false, window, cx);
 6584        });
 6585    }
 6586
 6587    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6588        if self.move_to_prev_snippet_tabstop(window, cx) {
 6589            return;
 6590        }
 6591
 6592        self.outdent(&Outdent, window, cx);
 6593    }
 6594
 6595    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6596        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6597            return;
 6598        }
 6599
 6600        let mut selections = self.selections.all_adjusted(cx);
 6601        let buffer = self.buffer.read(cx);
 6602        let snapshot = buffer.snapshot(cx);
 6603        let rows_iter = selections.iter().map(|s| s.head().row);
 6604        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6605
 6606        let mut edits = Vec::new();
 6607        let mut prev_edited_row = 0;
 6608        let mut row_delta = 0;
 6609        for selection in &mut selections {
 6610            if selection.start.row != prev_edited_row {
 6611                row_delta = 0;
 6612            }
 6613            prev_edited_row = selection.end.row;
 6614
 6615            // If the selection is non-empty, then increase the indentation of the selected lines.
 6616            if !selection.is_empty() {
 6617                row_delta =
 6618                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6619                continue;
 6620            }
 6621
 6622            // If the selection is empty and the cursor is in the leading whitespace before the
 6623            // suggested indentation, then auto-indent the line.
 6624            let cursor = selection.head();
 6625            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6626            if let Some(suggested_indent) =
 6627                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6628            {
 6629                if cursor.column < suggested_indent.len
 6630                    && cursor.column <= current_indent.len
 6631                    && current_indent.len <= suggested_indent.len
 6632                {
 6633                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6634                    selection.end = selection.start;
 6635                    if row_delta == 0 {
 6636                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6637                            cursor.row,
 6638                            current_indent,
 6639                            suggested_indent,
 6640                        ));
 6641                        row_delta = suggested_indent.len - current_indent.len;
 6642                    }
 6643                    continue;
 6644                }
 6645            }
 6646
 6647            // Otherwise, insert a hard or soft tab.
 6648            let settings = buffer.settings_at(cursor, cx);
 6649            let tab_size = if settings.hard_tabs {
 6650                IndentSize::tab()
 6651            } else {
 6652                let tab_size = settings.tab_size.get();
 6653                let char_column = snapshot
 6654                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6655                    .flat_map(str::chars)
 6656                    .count()
 6657                    + row_delta as usize;
 6658                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6659                IndentSize::spaces(chars_to_next_tab_stop)
 6660            };
 6661            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6662            selection.end = selection.start;
 6663            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6664            row_delta += tab_size.len;
 6665        }
 6666
 6667        self.transact(window, cx, |this, window, cx| {
 6668            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6669            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6670                s.select(selections)
 6671            });
 6672            this.refresh_inline_completion(true, false, window, cx);
 6673        });
 6674    }
 6675
 6676    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6677        if self.read_only(cx) {
 6678            return;
 6679        }
 6680        let mut selections = self.selections.all::<Point>(cx);
 6681        let mut prev_edited_row = 0;
 6682        let mut row_delta = 0;
 6683        let mut edits = Vec::new();
 6684        let buffer = self.buffer.read(cx);
 6685        let snapshot = buffer.snapshot(cx);
 6686        for selection in &mut selections {
 6687            if selection.start.row != prev_edited_row {
 6688                row_delta = 0;
 6689            }
 6690            prev_edited_row = selection.end.row;
 6691
 6692            row_delta =
 6693                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6694        }
 6695
 6696        self.transact(window, cx, |this, window, cx| {
 6697            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6698            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6699                s.select(selections)
 6700            });
 6701        });
 6702    }
 6703
 6704    fn indent_selection(
 6705        buffer: &MultiBuffer,
 6706        snapshot: &MultiBufferSnapshot,
 6707        selection: &mut Selection<Point>,
 6708        edits: &mut Vec<(Range<Point>, String)>,
 6709        delta_for_start_row: u32,
 6710        cx: &App,
 6711    ) -> u32 {
 6712        let settings = buffer.settings_at(selection.start, cx);
 6713        let tab_size = settings.tab_size.get();
 6714        let indent_kind = if settings.hard_tabs {
 6715            IndentKind::Tab
 6716        } else {
 6717            IndentKind::Space
 6718        };
 6719        let mut start_row = selection.start.row;
 6720        let mut end_row = selection.end.row + 1;
 6721
 6722        // If a selection ends at the beginning of a line, don't indent
 6723        // that last line.
 6724        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6725            end_row -= 1;
 6726        }
 6727
 6728        // Avoid re-indenting a row that has already been indented by a
 6729        // previous selection, but still update this selection's column
 6730        // to reflect that indentation.
 6731        if delta_for_start_row > 0 {
 6732            start_row += 1;
 6733            selection.start.column += delta_for_start_row;
 6734            if selection.end.row == selection.start.row {
 6735                selection.end.column += delta_for_start_row;
 6736            }
 6737        }
 6738
 6739        let mut delta_for_end_row = 0;
 6740        let has_multiple_rows = start_row + 1 != end_row;
 6741        for row in start_row..end_row {
 6742            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6743            let indent_delta = match (current_indent.kind, indent_kind) {
 6744                (IndentKind::Space, IndentKind::Space) => {
 6745                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6746                    IndentSize::spaces(columns_to_next_tab_stop)
 6747                }
 6748                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6749                (_, IndentKind::Tab) => IndentSize::tab(),
 6750            };
 6751
 6752            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6753                0
 6754            } else {
 6755                selection.start.column
 6756            };
 6757            let row_start = Point::new(row, start);
 6758            edits.push((
 6759                row_start..row_start,
 6760                indent_delta.chars().collect::<String>(),
 6761            ));
 6762
 6763            // Update this selection's endpoints to reflect the indentation.
 6764            if row == selection.start.row {
 6765                selection.start.column += indent_delta.len;
 6766            }
 6767            if row == selection.end.row {
 6768                selection.end.column += indent_delta.len;
 6769                delta_for_end_row = indent_delta.len;
 6770            }
 6771        }
 6772
 6773        if selection.start.row == selection.end.row {
 6774            delta_for_start_row + delta_for_end_row
 6775        } else {
 6776            delta_for_end_row
 6777        }
 6778    }
 6779
 6780    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6781        if self.read_only(cx) {
 6782            return;
 6783        }
 6784        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6785        let selections = self.selections.all::<Point>(cx);
 6786        let mut deletion_ranges = Vec::new();
 6787        let mut last_outdent = None;
 6788        {
 6789            let buffer = self.buffer.read(cx);
 6790            let snapshot = buffer.snapshot(cx);
 6791            for selection in &selections {
 6792                let settings = buffer.settings_at(selection.start, cx);
 6793                let tab_size = settings.tab_size.get();
 6794                let mut rows = selection.spanned_rows(false, &display_map);
 6795
 6796                // Avoid re-outdenting a row that has already been outdented by a
 6797                // previous selection.
 6798                if let Some(last_row) = last_outdent {
 6799                    if last_row == rows.start {
 6800                        rows.start = rows.start.next_row();
 6801                    }
 6802                }
 6803                let has_multiple_rows = rows.len() > 1;
 6804                for row in rows.iter_rows() {
 6805                    let indent_size = snapshot.indent_size_for_line(row);
 6806                    if indent_size.len > 0 {
 6807                        let deletion_len = match indent_size.kind {
 6808                            IndentKind::Space => {
 6809                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6810                                if columns_to_prev_tab_stop == 0 {
 6811                                    tab_size
 6812                                } else {
 6813                                    columns_to_prev_tab_stop
 6814                                }
 6815                            }
 6816                            IndentKind::Tab => 1,
 6817                        };
 6818                        let start = if has_multiple_rows
 6819                            || deletion_len > selection.start.column
 6820                            || indent_size.len < selection.start.column
 6821                        {
 6822                            0
 6823                        } else {
 6824                            selection.start.column - deletion_len
 6825                        };
 6826                        deletion_ranges.push(
 6827                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6828                        );
 6829                        last_outdent = Some(row);
 6830                    }
 6831                }
 6832            }
 6833        }
 6834
 6835        self.transact(window, cx, |this, window, cx| {
 6836            this.buffer.update(cx, |buffer, cx| {
 6837                let empty_str: Arc<str> = Arc::default();
 6838                buffer.edit(
 6839                    deletion_ranges
 6840                        .into_iter()
 6841                        .map(|range| (range, empty_str.clone())),
 6842                    None,
 6843                    cx,
 6844                );
 6845            });
 6846            let selections = this.selections.all::<usize>(cx);
 6847            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6848                s.select(selections)
 6849            });
 6850        });
 6851    }
 6852
 6853    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6854        if self.read_only(cx) {
 6855            return;
 6856        }
 6857        let selections = self
 6858            .selections
 6859            .all::<usize>(cx)
 6860            .into_iter()
 6861            .map(|s| s.range());
 6862
 6863        self.transact(window, cx, |this, window, cx| {
 6864            this.buffer.update(cx, |buffer, cx| {
 6865                buffer.autoindent_ranges(selections, cx);
 6866            });
 6867            let selections = this.selections.all::<usize>(cx);
 6868            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6869                s.select(selections)
 6870            });
 6871        });
 6872    }
 6873
 6874    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6875        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6876        let selections = self.selections.all::<Point>(cx);
 6877
 6878        let mut new_cursors = Vec::new();
 6879        let mut edit_ranges = Vec::new();
 6880        let mut selections = selections.iter().peekable();
 6881        while let Some(selection) = selections.next() {
 6882            let mut rows = selection.spanned_rows(false, &display_map);
 6883            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6884
 6885            // Accumulate contiguous regions of rows that we want to delete.
 6886            while let Some(next_selection) = selections.peek() {
 6887                let next_rows = next_selection.spanned_rows(false, &display_map);
 6888                if next_rows.start <= rows.end {
 6889                    rows.end = next_rows.end;
 6890                    selections.next().unwrap();
 6891                } else {
 6892                    break;
 6893                }
 6894            }
 6895
 6896            let buffer = &display_map.buffer_snapshot;
 6897            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6898            let edit_end;
 6899            let cursor_buffer_row;
 6900            if buffer.max_point().row >= rows.end.0 {
 6901                // If there's a line after the range, delete the \n from the end of the row range
 6902                // and position the cursor on the next line.
 6903                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6904                cursor_buffer_row = rows.end;
 6905            } else {
 6906                // If there isn't a line after the range, delete the \n from the line before the
 6907                // start of the row range and position the cursor there.
 6908                edit_start = edit_start.saturating_sub(1);
 6909                edit_end = buffer.len();
 6910                cursor_buffer_row = rows.start.previous_row();
 6911            }
 6912
 6913            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6914            *cursor.column_mut() =
 6915                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6916
 6917            new_cursors.push((
 6918                selection.id,
 6919                buffer.anchor_after(cursor.to_point(&display_map)),
 6920            ));
 6921            edit_ranges.push(edit_start..edit_end);
 6922        }
 6923
 6924        self.transact(window, cx, |this, window, cx| {
 6925            let buffer = this.buffer.update(cx, |buffer, cx| {
 6926                let empty_str: Arc<str> = Arc::default();
 6927                buffer.edit(
 6928                    edit_ranges
 6929                        .into_iter()
 6930                        .map(|range| (range, empty_str.clone())),
 6931                    None,
 6932                    cx,
 6933                );
 6934                buffer.snapshot(cx)
 6935            });
 6936            let new_selections = new_cursors
 6937                .into_iter()
 6938                .map(|(id, cursor)| {
 6939                    let cursor = cursor.to_point(&buffer);
 6940                    Selection {
 6941                        id,
 6942                        start: cursor,
 6943                        end: cursor,
 6944                        reversed: false,
 6945                        goal: SelectionGoal::None,
 6946                    }
 6947                })
 6948                .collect();
 6949
 6950            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6951                s.select(new_selections);
 6952            });
 6953        });
 6954    }
 6955
 6956    pub fn join_lines_impl(
 6957        &mut self,
 6958        insert_whitespace: bool,
 6959        window: &mut Window,
 6960        cx: &mut Context<Self>,
 6961    ) {
 6962        if self.read_only(cx) {
 6963            return;
 6964        }
 6965        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6966        for selection in self.selections.all::<Point>(cx) {
 6967            let start = MultiBufferRow(selection.start.row);
 6968            // Treat single line selections as if they include the next line. Otherwise this action
 6969            // would do nothing for single line selections individual cursors.
 6970            let end = if selection.start.row == selection.end.row {
 6971                MultiBufferRow(selection.start.row + 1)
 6972            } else {
 6973                MultiBufferRow(selection.end.row)
 6974            };
 6975
 6976            if let Some(last_row_range) = row_ranges.last_mut() {
 6977                if start <= last_row_range.end {
 6978                    last_row_range.end = end;
 6979                    continue;
 6980                }
 6981            }
 6982            row_ranges.push(start..end);
 6983        }
 6984
 6985        let snapshot = self.buffer.read(cx).snapshot(cx);
 6986        let mut cursor_positions = Vec::new();
 6987        for row_range in &row_ranges {
 6988            let anchor = snapshot.anchor_before(Point::new(
 6989                row_range.end.previous_row().0,
 6990                snapshot.line_len(row_range.end.previous_row()),
 6991            ));
 6992            cursor_positions.push(anchor..anchor);
 6993        }
 6994
 6995        self.transact(window, cx, |this, window, cx| {
 6996            for row_range in row_ranges.into_iter().rev() {
 6997                for row in row_range.iter_rows().rev() {
 6998                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6999                    let next_line_row = row.next_row();
 7000                    let indent = snapshot.indent_size_for_line(next_line_row);
 7001                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7002
 7003                    let replace =
 7004                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7005                            " "
 7006                        } else {
 7007                            ""
 7008                        };
 7009
 7010                    this.buffer.update(cx, |buffer, cx| {
 7011                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7012                    });
 7013                }
 7014            }
 7015
 7016            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7017                s.select_anchor_ranges(cursor_positions)
 7018            });
 7019        });
 7020    }
 7021
 7022    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7023        self.join_lines_impl(true, window, cx);
 7024    }
 7025
 7026    pub fn sort_lines_case_sensitive(
 7027        &mut self,
 7028        _: &SortLinesCaseSensitive,
 7029        window: &mut Window,
 7030        cx: &mut Context<Self>,
 7031    ) {
 7032        self.manipulate_lines(window, cx, |lines| lines.sort())
 7033    }
 7034
 7035    pub fn sort_lines_case_insensitive(
 7036        &mut self,
 7037        _: &SortLinesCaseInsensitive,
 7038        window: &mut Window,
 7039        cx: &mut Context<Self>,
 7040    ) {
 7041        self.manipulate_lines(window, cx, |lines| {
 7042            lines.sort_by_key(|line| line.to_lowercase())
 7043        })
 7044    }
 7045
 7046    pub fn unique_lines_case_insensitive(
 7047        &mut self,
 7048        _: &UniqueLinesCaseInsensitive,
 7049        window: &mut Window,
 7050        cx: &mut Context<Self>,
 7051    ) {
 7052        self.manipulate_lines(window, cx, |lines| {
 7053            let mut seen = HashSet::default();
 7054            lines.retain(|line| seen.insert(line.to_lowercase()));
 7055        })
 7056    }
 7057
 7058    pub fn unique_lines_case_sensitive(
 7059        &mut self,
 7060        _: &UniqueLinesCaseSensitive,
 7061        window: &mut Window,
 7062        cx: &mut Context<Self>,
 7063    ) {
 7064        self.manipulate_lines(window, cx, |lines| {
 7065            let mut seen = HashSet::default();
 7066            lines.retain(|line| seen.insert(*line));
 7067        })
 7068    }
 7069
 7070    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 7071        let mut revert_changes = HashMap::default();
 7072        let snapshot = self.snapshot(window, cx);
 7073        for hunk in snapshot
 7074            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 7075        {
 7076            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7077        }
 7078        if !revert_changes.is_empty() {
 7079            self.transact(window, cx, |editor, window, cx| {
 7080                editor.revert(revert_changes, window, cx);
 7081            });
 7082        }
 7083    }
 7084
 7085    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7086        let Some(project) = self.project.clone() else {
 7087            return;
 7088        };
 7089        self.reload(project, window, cx)
 7090            .detach_and_notify_err(window, cx);
 7091    }
 7092
 7093    pub fn revert_selected_hunks(
 7094        &mut self,
 7095        _: &RevertSelectedHunks,
 7096        window: &mut Window,
 7097        cx: &mut Context<Self>,
 7098    ) {
 7099        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 7100        self.discard_hunks_in_ranges(selections, window, cx);
 7101    }
 7102
 7103    fn discard_hunks_in_ranges(
 7104        &mut self,
 7105        ranges: impl Iterator<Item = Range<Point>>,
 7106        window: &mut Window,
 7107        cx: &mut Context<Editor>,
 7108    ) {
 7109        let mut revert_changes = HashMap::default();
 7110        let snapshot = self.snapshot(window, cx);
 7111        for hunk in &snapshot.hunks_for_ranges(ranges) {
 7112            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7113        }
 7114        if !revert_changes.is_empty() {
 7115            self.transact(window, cx, |editor, window, cx| {
 7116                editor.revert(revert_changes, window, cx);
 7117            });
 7118        }
 7119    }
 7120
 7121    pub fn open_active_item_in_terminal(
 7122        &mut self,
 7123        _: &OpenInTerminal,
 7124        window: &mut Window,
 7125        cx: &mut Context<Self>,
 7126    ) {
 7127        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7128            let project_path = buffer.read(cx).project_path(cx)?;
 7129            let project = self.project.as_ref()?.read(cx);
 7130            let entry = project.entry_for_path(&project_path, cx)?;
 7131            let parent = match &entry.canonical_path {
 7132                Some(canonical_path) => canonical_path.to_path_buf(),
 7133                None => project.absolute_path(&project_path, cx)?,
 7134            }
 7135            .parent()?
 7136            .to_path_buf();
 7137            Some(parent)
 7138        }) {
 7139            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7140        }
 7141    }
 7142
 7143    pub fn prepare_revert_change(
 7144        &self,
 7145        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7146        hunk: &MultiBufferDiffHunk,
 7147        cx: &mut App,
 7148    ) -> Option<()> {
 7149        let buffer = self.buffer.read(cx);
 7150        let diff = buffer.diff_for(hunk.buffer_id)?;
 7151        let buffer = buffer.buffer(hunk.buffer_id)?;
 7152        let buffer = buffer.read(cx);
 7153        let original_text = diff
 7154            .read(cx)
 7155            .base_text()
 7156            .as_ref()?
 7157            .as_rope()
 7158            .slice(hunk.diff_base_byte_range.clone());
 7159        let buffer_snapshot = buffer.snapshot();
 7160        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7161        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7162            probe
 7163                .0
 7164                .start
 7165                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7166                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7167        }) {
 7168            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7169            Some(())
 7170        } else {
 7171            None
 7172        }
 7173    }
 7174
 7175    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7176        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7177    }
 7178
 7179    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7180        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7181    }
 7182
 7183    fn manipulate_lines<Fn>(
 7184        &mut self,
 7185        window: &mut Window,
 7186        cx: &mut Context<Self>,
 7187        mut callback: Fn,
 7188    ) where
 7189        Fn: FnMut(&mut Vec<&str>),
 7190    {
 7191        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7192        let buffer = self.buffer.read(cx).snapshot(cx);
 7193
 7194        let mut edits = Vec::new();
 7195
 7196        let selections = self.selections.all::<Point>(cx);
 7197        let mut selections = selections.iter().peekable();
 7198        let mut contiguous_row_selections = Vec::new();
 7199        let mut new_selections = Vec::new();
 7200        let mut added_lines = 0;
 7201        let mut removed_lines = 0;
 7202
 7203        while let Some(selection) = selections.next() {
 7204            let (start_row, end_row) = consume_contiguous_rows(
 7205                &mut contiguous_row_selections,
 7206                selection,
 7207                &display_map,
 7208                &mut selections,
 7209            );
 7210
 7211            let start_point = Point::new(start_row.0, 0);
 7212            let end_point = Point::new(
 7213                end_row.previous_row().0,
 7214                buffer.line_len(end_row.previous_row()),
 7215            );
 7216            let text = buffer
 7217                .text_for_range(start_point..end_point)
 7218                .collect::<String>();
 7219
 7220            let mut lines = text.split('\n').collect_vec();
 7221
 7222            let lines_before = lines.len();
 7223            callback(&mut lines);
 7224            let lines_after = lines.len();
 7225
 7226            edits.push((start_point..end_point, lines.join("\n")));
 7227
 7228            // Selections must change based on added and removed line count
 7229            let start_row =
 7230                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7231            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7232            new_selections.push(Selection {
 7233                id: selection.id,
 7234                start: start_row,
 7235                end: end_row,
 7236                goal: SelectionGoal::None,
 7237                reversed: selection.reversed,
 7238            });
 7239
 7240            if lines_after > lines_before {
 7241                added_lines += lines_after - lines_before;
 7242            } else if lines_before > lines_after {
 7243                removed_lines += lines_before - lines_after;
 7244            }
 7245        }
 7246
 7247        self.transact(window, cx, |this, window, cx| {
 7248            let buffer = this.buffer.update(cx, |buffer, cx| {
 7249                buffer.edit(edits, None, cx);
 7250                buffer.snapshot(cx)
 7251            });
 7252
 7253            // Recalculate offsets on newly edited buffer
 7254            let new_selections = new_selections
 7255                .iter()
 7256                .map(|s| {
 7257                    let start_point = Point::new(s.start.0, 0);
 7258                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7259                    Selection {
 7260                        id: s.id,
 7261                        start: buffer.point_to_offset(start_point),
 7262                        end: buffer.point_to_offset(end_point),
 7263                        goal: s.goal,
 7264                        reversed: s.reversed,
 7265                    }
 7266                })
 7267                .collect();
 7268
 7269            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7270                s.select(new_selections);
 7271            });
 7272
 7273            this.request_autoscroll(Autoscroll::fit(), cx);
 7274        });
 7275    }
 7276
 7277    pub fn convert_to_upper_case(
 7278        &mut self,
 7279        _: &ConvertToUpperCase,
 7280        window: &mut Window,
 7281        cx: &mut Context<Self>,
 7282    ) {
 7283        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7284    }
 7285
 7286    pub fn convert_to_lower_case(
 7287        &mut self,
 7288        _: &ConvertToLowerCase,
 7289        window: &mut Window,
 7290        cx: &mut Context<Self>,
 7291    ) {
 7292        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7293    }
 7294
 7295    pub fn convert_to_title_case(
 7296        &mut self,
 7297        _: &ConvertToTitleCase,
 7298        window: &mut Window,
 7299        cx: &mut Context<Self>,
 7300    ) {
 7301        self.manipulate_text(window, cx, |text| {
 7302            text.split('\n')
 7303                .map(|line| line.to_case(Case::Title))
 7304                .join("\n")
 7305        })
 7306    }
 7307
 7308    pub fn convert_to_snake_case(
 7309        &mut self,
 7310        _: &ConvertToSnakeCase,
 7311        window: &mut Window,
 7312        cx: &mut Context<Self>,
 7313    ) {
 7314        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7315    }
 7316
 7317    pub fn convert_to_kebab_case(
 7318        &mut self,
 7319        _: &ConvertToKebabCase,
 7320        window: &mut Window,
 7321        cx: &mut Context<Self>,
 7322    ) {
 7323        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7324    }
 7325
 7326    pub fn convert_to_upper_camel_case(
 7327        &mut self,
 7328        _: &ConvertToUpperCamelCase,
 7329        window: &mut Window,
 7330        cx: &mut Context<Self>,
 7331    ) {
 7332        self.manipulate_text(window, cx, |text| {
 7333            text.split('\n')
 7334                .map(|line| line.to_case(Case::UpperCamel))
 7335                .join("\n")
 7336        })
 7337    }
 7338
 7339    pub fn convert_to_lower_camel_case(
 7340        &mut self,
 7341        _: &ConvertToLowerCamelCase,
 7342        window: &mut Window,
 7343        cx: &mut Context<Self>,
 7344    ) {
 7345        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7346    }
 7347
 7348    pub fn convert_to_opposite_case(
 7349        &mut self,
 7350        _: &ConvertToOppositeCase,
 7351        window: &mut Window,
 7352        cx: &mut Context<Self>,
 7353    ) {
 7354        self.manipulate_text(window, cx, |text| {
 7355            text.chars()
 7356                .fold(String::with_capacity(text.len()), |mut t, c| {
 7357                    if c.is_uppercase() {
 7358                        t.extend(c.to_lowercase());
 7359                    } else {
 7360                        t.extend(c.to_uppercase());
 7361                    }
 7362                    t
 7363                })
 7364        })
 7365    }
 7366
 7367    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7368    where
 7369        Fn: FnMut(&str) -> String,
 7370    {
 7371        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7372        let buffer = self.buffer.read(cx).snapshot(cx);
 7373
 7374        let mut new_selections = Vec::new();
 7375        let mut edits = Vec::new();
 7376        let mut selection_adjustment = 0i32;
 7377
 7378        for selection in self.selections.all::<usize>(cx) {
 7379            let selection_is_empty = selection.is_empty();
 7380
 7381            let (start, end) = if selection_is_empty {
 7382                let word_range = movement::surrounding_word(
 7383                    &display_map,
 7384                    selection.start.to_display_point(&display_map),
 7385                );
 7386                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7387                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7388                (start, end)
 7389            } else {
 7390                (selection.start, selection.end)
 7391            };
 7392
 7393            let text = buffer.text_for_range(start..end).collect::<String>();
 7394            let old_length = text.len() as i32;
 7395            let text = callback(&text);
 7396
 7397            new_selections.push(Selection {
 7398                start: (start as i32 - selection_adjustment) as usize,
 7399                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7400                goal: SelectionGoal::None,
 7401                ..selection
 7402            });
 7403
 7404            selection_adjustment += old_length - text.len() as i32;
 7405
 7406            edits.push((start..end, text));
 7407        }
 7408
 7409        self.transact(window, cx, |this, window, cx| {
 7410            this.buffer.update(cx, |buffer, cx| {
 7411                buffer.edit(edits, None, cx);
 7412            });
 7413
 7414            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7415                s.select(new_selections);
 7416            });
 7417
 7418            this.request_autoscroll(Autoscroll::fit(), cx);
 7419        });
 7420    }
 7421
 7422    pub fn duplicate(
 7423        &mut self,
 7424        upwards: bool,
 7425        whole_lines: bool,
 7426        window: &mut Window,
 7427        cx: &mut Context<Self>,
 7428    ) {
 7429        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7430        let buffer = &display_map.buffer_snapshot;
 7431        let selections = self.selections.all::<Point>(cx);
 7432
 7433        let mut edits = Vec::new();
 7434        let mut selections_iter = selections.iter().peekable();
 7435        while let Some(selection) = selections_iter.next() {
 7436            let mut rows = selection.spanned_rows(false, &display_map);
 7437            // duplicate line-wise
 7438            if whole_lines || selection.start == selection.end {
 7439                // Avoid duplicating the same lines twice.
 7440                while let Some(next_selection) = selections_iter.peek() {
 7441                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7442                    if next_rows.start < rows.end {
 7443                        rows.end = next_rows.end;
 7444                        selections_iter.next().unwrap();
 7445                    } else {
 7446                        break;
 7447                    }
 7448                }
 7449
 7450                // Copy the text from the selected row region and splice it either at the start
 7451                // or end of the region.
 7452                let start = Point::new(rows.start.0, 0);
 7453                let end = Point::new(
 7454                    rows.end.previous_row().0,
 7455                    buffer.line_len(rows.end.previous_row()),
 7456                );
 7457                let text = buffer
 7458                    .text_for_range(start..end)
 7459                    .chain(Some("\n"))
 7460                    .collect::<String>();
 7461                let insert_location = if upwards {
 7462                    Point::new(rows.end.0, 0)
 7463                } else {
 7464                    start
 7465                };
 7466                edits.push((insert_location..insert_location, text));
 7467            } else {
 7468                // duplicate character-wise
 7469                let start = selection.start;
 7470                let end = selection.end;
 7471                let text = buffer.text_for_range(start..end).collect::<String>();
 7472                edits.push((selection.end..selection.end, text));
 7473            }
 7474        }
 7475
 7476        self.transact(window, cx, |this, _, cx| {
 7477            this.buffer.update(cx, |buffer, cx| {
 7478                buffer.edit(edits, None, cx);
 7479            });
 7480
 7481            this.request_autoscroll(Autoscroll::fit(), cx);
 7482        });
 7483    }
 7484
 7485    pub fn duplicate_line_up(
 7486        &mut self,
 7487        _: &DuplicateLineUp,
 7488        window: &mut Window,
 7489        cx: &mut Context<Self>,
 7490    ) {
 7491        self.duplicate(true, true, window, cx);
 7492    }
 7493
 7494    pub fn duplicate_line_down(
 7495        &mut self,
 7496        _: &DuplicateLineDown,
 7497        window: &mut Window,
 7498        cx: &mut Context<Self>,
 7499    ) {
 7500        self.duplicate(false, true, window, cx);
 7501    }
 7502
 7503    pub fn duplicate_selection(
 7504        &mut self,
 7505        _: &DuplicateSelection,
 7506        window: &mut Window,
 7507        cx: &mut Context<Self>,
 7508    ) {
 7509        self.duplicate(false, false, window, cx);
 7510    }
 7511
 7512    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7513        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7514        let buffer = self.buffer.read(cx).snapshot(cx);
 7515
 7516        let mut edits = Vec::new();
 7517        let mut unfold_ranges = Vec::new();
 7518        let mut refold_creases = Vec::new();
 7519
 7520        let selections = self.selections.all::<Point>(cx);
 7521        let mut selections = selections.iter().peekable();
 7522        let mut contiguous_row_selections = Vec::new();
 7523        let mut new_selections = Vec::new();
 7524
 7525        while let Some(selection) = selections.next() {
 7526            // Find all the selections that span a contiguous row range
 7527            let (start_row, end_row) = consume_contiguous_rows(
 7528                &mut contiguous_row_selections,
 7529                selection,
 7530                &display_map,
 7531                &mut selections,
 7532            );
 7533
 7534            // Move the text spanned by the row range to be before the line preceding the row range
 7535            if start_row.0 > 0 {
 7536                let range_to_move = Point::new(
 7537                    start_row.previous_row().0,
 7538                    buffer.line_len(start_row.previous_row()),
 7539                )
 7540                    ..Point::new(
 7541                        end_row.previous_row().0,
 7542                        buffer.line_len(end_row.previous_row()),
 7543                    );
 7544                let insertion_point = display_map
 7545                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7546                    .0;
 7547
 7548                // Don't move lines across excerpts
 7549                if buffer
 7550                    .excerpt_containing(insertion_point..range_to_move.end)
 7551                    .is_some()
 7552                {
 7553                    let text = buffer
 7554                        .text_for_range(range_to_move.clone())
 7555                        .flat_map(|s| s.chars())
 7556                        .skip(1)
 7557                        .chain(['\n'])
 7558                        .collect::<String>();
 7559
 7560                    edits.push((
 7561                        buffer.anchor_after(range_to_move.start)
 7562                            ..buffer.anchor_before(range_to_move.end),
 7563                        String::new(),
 7564                    ));
 7565                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7566                    edits.push((insertion_anchor..insertion_anchor, text));
 7567
 7568                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7569
 7570                    // Move selections up
 7571                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7572                        |mut selection| {
 7573                            selection.start.row -= row_delta;
 7574                            selection.end.row -= row_delta;
 7575                            selection
 7576                        },
 7577                    ));
 7578
 7579                    // Move folds up
 7580                    unfold_ranges.push(range_to_move.clone());
 7581                    for fold in display_map.folds_in_range(
 7582                        buffer.anchor_before(range_to_move.start)
 7583                            ..buffer.anchor_after(range_to_move.end),
 7584                    ) {
 7585                        let mut start = fold.range.start.to_point(&buffer);
 7586                        let mut end = fold.range.end.to_point(&buffer);
 7587                        start.row -= row_delta;
 7588                        end.row -= row_delta;
 7589                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7590                    }
 7591                }
 7592            }
 7593
 7594            // If we didn't move line(s), preserve the existing selections
 7595            new_selections.append(&mut contiguous_row_selections);
 7596        }
 7597
 7598        self.transact(window, cx, |this, window, cx| {
 7599            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7600            this.buffer.update(cx, |buffer, cx| {
 7601                for (range, text) in edits {
 7602                    buffer.edit([(range, text)], None, cx);
 7603                }
 7604            });
 7605            this.fold_creases(refold_creases, true, window, cx);
 7606            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7607                s.select(new_selections);
 7608            })
 7609        });
 7610    }
 7611
 7612    pub fn move_line_down(
 7613        &mut self,
 7614        _: &MoveLineDown,
 7615        window: &mut Window,
 7616        cx: &mut Context<Self>,
 7617    ) {
 7618        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7619        let buffer = self.buffer.read(cx).snapshot(cx);
 7620
 7621        let mut edits = Vec::new();
 7622        let mut unfold_ranges = Vec::new();
 7623        let mut refold_creases = Vec::new();
 7624
 7625        let selections = self.selections.all::<Point>(cx);
 7626        let mut selections = selections.iter().peekable();
 7627        let mut contiguous_row_selections = Vec::new();
 7628        let mut new_selections = Vec::new();
 7629
 7630        while let Some(selection) = selections.next() {
 7631            // Find all the selections that span a contiguous row range
 7632            let (start_row, end_row) = consume_contiguous_rows(
 7633                &mut contiguous_row_selections,
 7634                selection,
 7635                &display_map,
 7636                &mut selections,
 7637            );
 7638
 7639            // Move the text spanned by the row range to be after the last line of the row range
 7640            if end_row.0 <= buffer.max_point().row {
 7641                let range_to_move =
 7642                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7643                let insertion_point = display_map
 7644                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7645                    .0;
 7646
 7647                // Don't move lines across excerpt boundaries
 7648                if buffer
 7649                    .excerpt_containing(range_to_move.start..insertion_point)
 7650                    .is_some()
 7651                {
 7652                    let mut text = String::from("\n");
 7653                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7654                    text.pop(); // Drop trailing newline
 7655                    edits.push((
 7656                        buffer.anchor_after(range_to_move.start)
 7657                            ..buffer.anchor_before(range_to_move.end),
 7658                        String::new(),
 7659                    ));
 7660                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7661                    edits.push((insertion_anchor..insertion_anchor, text));
 7662
 7663                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7664
 7665                    // Move selections down
 7666                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7667                        |mut selection| {
 7668                            selection.start.row += row_delta;
 7669                            selection.end.row += row_delta;
 7670                            selection
 7671                        },
 7672                    ));
 7673
 7674                    // Move folds down
 7675                    unfold_ranges.push(range_to_move.clone());
 7676                    for fold in display_map.folds_in_range(
 7677                        buffer.anchor_before(range_to_move.start)
 7678                            ..buffer.anchor_after(range_to_move.end),
 7679                    ) {
 7680                        let mut start = fold.range.start.to_point(&buffer);
 7681                        let mut end = fold.range.end.to_point(&buffer);
 7682                        start.row += row_delta;
 7683                        end.row += row_delta;
 7684                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7685                    }
 7686                }
 7687            }
 7688
 7689            // If we didn't move line(s), preserve the existing selections
 7690            new_selections.append(&mut contiguous_row_selections);
 7691        }
 7692
 7693        self.transact(window, cx, |this, window, cx| {
 7694            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7695            this.buffer.update(cx, |buffer, cx| {
 7696                for (range, text) in edits {
 7697                    buffer.edit([(range, text)], None, cx);
 7698                }
 7699            });
 7700            this.fold_creases(refold_creases, true, window, cx);
 7701            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7702                s.select(new_selections)
 7703            });
 7704        });
 7705    }
 7706
 7707    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7708        let text_layout_details = &self.text_layout_details(window);
 7709        self.transact(window, cx, |this, window, cx| {
 7710            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7711                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7712                let line_mode = s.line_mode;
 7713                s.move_with(|display_map, selection| {
 7714                    if !selection.is_empty() || line_mode {
 7715                        return;
 7716                    }
 7717
 7718                    let mut head = selection.head();
 7719                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7720                    if head.column() == display_map.line_len(head.row()) {
 7721                        transpose_offset = display_map
 7722                            .buffer_snapshot
 7723                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7724                    }
 7725
 7726                    if transpose_offset == 0 {
 7727                        return;
 7728                    }
 7729
 7730                    *head.column_mut() += 1;
 7731                    head = display_map.clip_point(head, Bias::Right);
 7732                    let goal = SelectionGoal::HorizontalPosition(
 7733                        display_map
 7734                            .x_for_display_point(head, text_layout_details)
 7735                            .into(),
 7736                    );
 7737                    selection.collapse_to(head, goal);
 7738
 7739                    let transpose_start = display_map
 7740                        .buffer_snapshot
 7741                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7742                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7743                        let transpose_end = display_map
 7744                            .buffer_snapshot
 7745                            .clip_offset(transpose_offset + 1, Bias::Right);
 7746                        if let Some(ch) =
 7747                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7748                        {
 7749                            edits.push((transpose_start..transpose_offset, String::new()));
 7750                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7751                        }
 7752                    }
 7753                });
 7754                edits
 7755            });
 7756            this.buffer
 7757                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7758            let selections = this.selections.all::<usize>(cx);
 7759            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7760                s.select(selections);
 7761            });
 7762        });
 7763    }
 7764
 7765    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7766        self.rewrap_impl(IsVimMode::No, cx)
 7767    }
 7768
 7769    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7770        let buffer = self.buffer.read(cx).snapshot(cx);
 7771        let selections = self.selections.all::<Point>(cx);
 7772        let mut selections = selections.iter().peekable();
 7773
 7774        let mut edits = Vec::new();
 7775        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7776
 7777        while let Some(selection) = selections.next() {
 7778            let mut start_row = selection.start.row;
 7779            let mut end_row = selection.end.row;
 7780
 7781            // Skip selections that overlap with a range that has already been rewrapped.
 7782            let selection_range = start_row..end_row;
 7783            if rewrapped_row_ranges
 7784                .iter()
 7785                .any(|range| range.overlaps(&selection_range))
 7786            {
 7787                continue;
 7788            }
 7789
 7790            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7791
 7792            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7793                match language_scope.language_name().as_ref() {
 7794                    "Markdown" | "Plain Text" => {
 7795                        should_rewrap = true;
 7796                    }
 7797                    _ => {}
 7798                }
 7799            }
 7800
 7801            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7802
 7803            // Since not all lines in the selection may be at the same indent
 7804            // level, choose the indent size that is the most common between all
 7805            // of the lines.
 7806            //
 7807            // If there is a tie, we use the deepest indent.
 7808            let (indent_size, indent_end) = {
 7809                let mut indent_size_occurrences = HashMap::default();
 7810                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7811
 7812                for row in start_row..=end_row {
 7813                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7814                    rows_by_indent_size.entry(indent).or_default().push(row);
 7815                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7816                }
 7817
 7818                let indent_size = indent_size_occurrences
 7819                    .into_iter()
 7820                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7821                    .map(|(indent, _)| indent)
 7822                    .unwrap_or_default();
 7823                let row = rows_by_indent_size[&indent_size][0];
 7824                let indent_end = Point::new(row, indent_size.len);
 7825
 7826                (indent_size, indent_end)
 7827            };
 7828
 7829            let mut line_prefix = indent_size.chars().collect::<String>();
 7830
 7831            if let Some(comment_prefix) =
 7832                buffer
 7833                    .language_scope_at(selection.head())
 7834                    .and_then(|language| {
 7835                        language
 7836                            .line_comment_prefixes()
 7837                            .iter()
 7838                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7839                            .cloned()
 7840                    })
 7841            {
 7842                line_prefix.push_str(&comment_prefix);
 7843                should_rewrap = true;
 7844            }
 7845
 7846            if !should_rewrap {
 7847                continue;
 7848            }
 7849
 7850            if selection.is_empty() {
 7851                'expand_upwards: while start_row > 0 {
 7852                    let prev_row = start_row - 1;
 7853                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7854                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7855                    {
 7856                        start_row = prev_row;
 7857                    } else {
 7858                        break 'expand_upwards;
 7859                    }
 7860                }
 7861
 7862                'expand_downwards: while end_row < buffer.max_point().row {
 7863                    let next_row = end_row + 1;
 7864                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7865                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7866                    {
 7867                        end_row = next_row;
 7868                    } else {
 7869                        break 'expand_downwards;
 7870                    }
 7871                }
 7872            }
 7873
 7874            let start = Point::new(start_row, 0);
 7875            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7876            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7877            let Some(lines_without_prefixes) = selection_text
 7878                .lines()
 7879                .map(|line| {
 7880                    line.strip_prefix(&line_prefix)
 7881                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7882                        .ok_or_else(|| {
 7883                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7884                        })
 7885                })
 7886                .collect::<Result<Vec<_>, _>>()
 7887                .log_err()
 7888            else {
 7889                continue;
 7890            };
 7891
 7892            let wrap_column = buffer
 7893                .settings_at(Point::new(start_row, 0), cx)
 7894                .preferred_line_length as usize;
 7895            let wrapped_text = wrap_with_prefix(
 7896                line_prefix,
 7897                lines_without_prefixes.join(" "),
 7898                wrap_column,
 7899                tab_size,
 7900            );
 7901
 7902            // TODO: should always use char-based diff while still supporting cursor behavior that
 7903            // matches vim.
 7904            let diff = match is_vim_mode {
 7905                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7906                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7907            };
 7908            let mut offset = start.to_offset(&buffer);
 7909            let mut moved_since_edit = true;
 7910
 7911            for change in diff.iter_all_changes() {
 7912                let value = change.value();
 7913                match change.tag() {
 7914                    ChangeTag::Equal => {
 7915                        offset += value.len();
 7916                        moved_since_edit = true;
 7917                    }
 7918                    ChangeTag::Delete => {
 7919                        let start = buffer.anchor_after(offset);
 7920                        let end = buffer.anchor_before(offset + value.len());
 7921
 7922                        if moved_since_edit {
 7923                            edits.push((start..end, String::new()));
 7924                        } else {
 7925                            edits.last_mut().unwrap().0.end = end;
 7926                        }
 7927
 7928                        offset += value.len();
 7929                        moved_since_edit = false;
 7930                    }
 7931                    ChangeTag::Insert => {
 7932                        if moved_since_edit {
 7933                            let anchor = buffer.anchor_after(offset);
 7934                            edits.push((anchor..anchor, value.to_string()));
 7935                        } else {
 7936                            edits.last_mut().unwrap().1.push_str(value);
 7937                        }
 7938
 7939                        moved_since_edit = false;
 7940                    }
 7941                }
 7942            }
 7943
 7944            rewrapped_row_ranges.push(start_row..=end_row);
 7945        }
 7946
 7947        self.buffer
 7948            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7949    }
 7950
 7951    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7952        let mut text = String::new();
 7953        let buffer = self.buffer.read(cx).snapshot(cx);
 7954        let mut selections = self.selections.all::<Point>(cx);
 7955        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7956        {
 7957            let max_point = buffer.max_point();
 7958            let mut is_first = true;
 7959            for selection in &mut selections {
 7960                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7961                if is_entire_line {
 7962                    selection.start = Point::new(selection.start.row, 0);
 7963                    if !selection.is_empty() && selection.end.column == 0 {
 7964                        selection.end = cmp::min(max_point, selection.end);
 7965                    } else {
 7966                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7967                    }
 7968                    selection.goal = SelectionGoal::None;
 7969                }
 7970                if is_first {
 7971                    is_first = false;
 7972                } else {
 7973                    text += "\n";
 7974                }
 7975                let mut len = 0;
 7976                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7977                    text.push_str(chunk);
 7978                    len += chunk.len();
 7979                }
 7980                clipboard_selections.push(ClipboardSelection {
 7981                    len,
 7982                    is_entire_line,
 7983                    first_line_indent: buffer
 7984                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7985                        .len,
 7986                });
 7987            }
 7988        }
 7989
 7990        self.transact(window, cx, |this, window, cx| {
 7991            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7992                s.select(selections);
 7993            });
 7994            this.insert("", window, cx);
 7995        });
 7996        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7997    }
 7998
 7999    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8000        let item = self.cut_common(window, cx);
 8001        cx.write_to_clipboard(item);
 8002    }
 8003
 8004    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8005        self.change_selections(None, window, cx, |s| {
 8006            s.move_with(|snapshot, sel| {
 8007                if sel.is_empty() {
 8008                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8009                }
 8010            });
 8011        });
 8012        let item = self.cut_common(window, cx);
 8013        cx.set_global(KillRing(item))
 8014    }
 8015
 8016    pub fn kill_ring_yank(
 8017        &mut self,
 8018        _: &KillRingYank,
 8019        window: &mut Window,
 8020        cx: &mut Context<Self>,
 8021    ) {
 8022        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8023            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8024                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8025            } else {
 8026                return;
 8027            }
 8028        } else {
 8029            return;
 8030        };
 8031        self.do_paste(&text, metadata, false, window, cx);
 8032    }
 8033
 8034    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8035        let selections = self.selections.all::<Point>(cx);
 8036        let buffer = self.buffer.read(cx).read(cx);
 8037        let mut text = String::new();
 8038
 8039        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8040        {
 8041            let max_point = buffer.max_point();
 8042            let mut is_first = true;
 8043            for selection in selections.iter() {
 8044                let mut start = selection.start;
 8045                let mut end = selection.end;
 8046                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8047                if is_entire_line {
 8048                    start = Point::new(start.row, 0);
 8049                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8050                }
 8051                if is_first {
 8052                    is_first = false;
 8053                } else {
 8054                    text += "\n";
 8055                }
 8056                let mut len = 0;
 8057                for chunk in buffer.text_for_range(start..end) {
 8058                    text.push_str(chunk);
 8059                    len += chunk.len();
 8060                }
 8061                clipboard_selections.push(ClipboardSelection {
 8062                    len,
 8063                    is_entire_line,
 8064                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8065                });
 8066            }
 8067        }
 8068
 8069        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8070            text,
 8071            clipboard_selections,
 8072        ));
 8073    }
 8074
 8075    pub fn do_paste(
 8076        &mut self,
 8077        text: &String,
 8078        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8079        handle_entire_lines: bool,
 8080        window: &mut Window,
 8081        cx: &mut Context<Self>,
 8082    ) {
 8083        if self.read_only(cx) {
 8084            return;
 8085        }
 8086
 8087        let clipboard_text = Cow::Borrowed(text);
 8088
 8089        self.transact(window, cx, |this, window, cx| {
 8090            if let Some(mut clipboard_selections) = clipboard_selections {
 8091                let old_selections = this.selections.all::<usize>(cx);
 8092                let all_selections_were_entire_line =
 8093                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8094                let first_selection_indent_column =
 8095                    clipboard_selections.first().map(|s| s.first_line_indent);
 8096                if clipboard_selections.len() != old_selections.len() {
 8097                    clipboard_selections.drain(..);
 8098                }
 8099                let cursor_offset = this.selections.last::<usize>(cx).head();
 8100                let mut auto_indent_on_paste = true;
 8101
 8102                this.buffer.update(cx, |buffer, cx| {
 8103                    let snapshot = buffer.read(cx);
 8104                    auto_indent_on_paste =
 8105                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8106
 8107                    let mut start_offset = 0;
 8108                    let mut edits = Vec::new();
 8109                    let mut original_indent_columns = Vec::new();
 8110                    for (ix, selection) in old_selections.iter().enumerate() {
 8111                        let to_insert;
 8112                        let entire_line;
 8113                        let original_indent_column;
 8114                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8115                            let end_offset = start_offset + clipboard_selection.len;
 8116                            to_insert = &clipboard_text[start_offset..end_offset];
 8117                            entire_line = clipboard_selection.is_entire_line;
 8118                            start_offset = end_offset + 1;
 8119                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8120                        } else {
 8121                            to_insert = clipboard_text.as_str();
 8122                            entire_line = all_selections_were_entire_line;
 8123                            original_indent_column = first_selection_indent_column
 8124                        }
 8125
 8126                        // If the corresponding selection was empty when this slice of the
 8127                        // clipboard text was written, then the entire line containing the
 8128                        // selection was copied. If this selection is also currently empty,
 8129                        // then paste the line before the current line of the buffer.
 8130                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8131                            let column = selection.start.to_point(&snapshot).column as usize;
 8132                            let line_start = selection.start - column;
 8133                            line_start..line_start
 8134                        } else {
 8135                            selection.range()
 8136                        };
 8137
 8138                        edits.push((range, to_insert));
 8139                        original_indent_columns.extend(original_indent_column);
 8140                    }
 8141                    drop(snapshot);
 8142
 8143                    buffer.edit(
 8144                        edits,
 8145                        if auto_indent_on_paste {
 8146                            Some(AutoindentMode::Block {
 8147                                original_indent_columns,
 8148                            })
 8149                        } else {
 8150                            None
 8151                        },
 8152                        cx,
 8153                    );
 8154                });
 8155
 8156                let selections = this.selections.all::<usize>(cx);
 8157                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8158                    s.select(selections)
 8159                });
 8160            } else {
 8161                this.insert(&clipboard_text, window, cx);
 8162            }
 8163        });
 8164    }
 8165
 8166    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8167        if let Some(item) = cx.read_from_clipboard() {
 8168            let entries = item.entries();
 8169
 8170            match entries.first() {
 8171                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8172                // of all the pasted entries.
 8173                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8174                    .do_paste(
 8175                        clipboard_string.text(),
 8176                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8177                        true,
 8178                        window,
 8179                        cx,
 8180                    ),
 8181                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8182            }
 8183        }
 8184    }
 8185
 8186    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8187        if self.read_only(cx) {
 8188            return;
 8189        }
 8190
 8191        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8192            if let Some((selections, _)) =
 8193                self.selection_history.transaction(transaction_id).cloned()
 8194            {
 8195                self.change_selections(None, window, cx, |s| {
 8196                    s.select_anchors(selections.to_vec());
 8197                });
 8198            }
 8199            self.request_autoscroll(Autoscroll::fit(), cx);
 8200            self.unmark_text(window, cx);
 8201            self.refresh_inline_completion(true, false, window, cx);
 8202            cx.emit(EditorEvent::Edited { transaction_id });
 8203            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8204        }
 8205    }
 8206
 8207    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8208        if self.read_only(cx) {
 8209            return;
 8210        }
 8211
 8212        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8213            if let Some((_, Some(selections))) =
 8214                self.selection_history.transaction(transaction_id).cloned()
 8215            {
 8216                self.change_selections(None, window, cx, |s| {
 8217                    s.select_anchors(selections.to_vec());
 8218                });
 8219            }
 8220            self.request_autoscroll(Autoscroll::fit(), cx);
 8221            self.unmark_text(window, cx);
 8222            self.refresh_inline_completion(true, false, window, cx);
 8223            cx.emit(EditorEvent::Edited { transaction_id });
 8224        }
 8225    }
 8226
 8227    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8228        self.buffer
 8229            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8230    }
 8231
 8232    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8233        self.buffer
 8234            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8235    }
 8236
 8237    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8238        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8239            let line_mode = s.line_mode;
 8240            s.move_with(|map, selection| {
 8241                let cursor = if selection.is_empty() && !line_mode {
 8242                    movement::left(map, selection.start)
 8243                } else {
 8244                    selection.start
 8245                };
 8246                selection.collapse_to(cursor, SelectionGoal::None);
 8247            });
 8248        })
 8249    }
 8250
 8251    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8252        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8253            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8254        })
 8255    }
 8256
 8257    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8258        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8259            let line_mode = s.line_mode;
 8260            s.move_with(|map, selection| {
 8261                let cursor = if selection.is_empty() && !line_mode {
 8262                    movement::right(map, selection.end)
 8263                } else {
 8264                    selection.end
 8265                };
 8266                selection.collapse_to(cursor, SelectionGoal::None)
 8267            });
 8268        })
 8269    }
 8270
 8271    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8272        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8273            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8274        })
 8275    }
 8276
 8277    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8278        if self.take_rename(true, window, cx).is_some() {
 8279            return;
 8280        }
 8281
 8282        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8283            cx.propagate();
 8284            return;
 8285        }
 8286
 8287        let text_layout_details = &self.text_layout_details(window);
 8288        let selection_count = self.selections.count();
 8289        let first_selection = self.selections.first_anchor();
 8290
 8291        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8292            let line_mode = s.line_mode;
 8293            s.move_with(|map, selection| {
 8294                if !selection.is_empty() && !line_mode {
 8295                    selection.goal = SelectionGoal::None;
 8296                }
 8297                let (cursor, goal) = movement::up(
 8298                    map,
 8299                    selection.start,
 8300                    selection.goal,
 8301                    false,
 8302                    text_layout_details,
 8303                );
 8304                selection.collapse_to(cursor, goal);
 8305            });
 8306        });
 8307
 8308        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8309        {
 8310            cx.propagate();
 8311        }
 8312    }
 8313
 8314    pub fn move_up_by_lines(
 8315        &mut self,
 8316        action: &MoveUpByLines,
 8317        window: &mut Window,
 8318        cx: &mut Context<Self>,
 8319    ) {
 8320        if self.take_rename(true, window, cx).is_some() {
 8321            return;
 8322        }
 8323
 8324        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8325            cx.propagate();
 8326            return;
 8327        }
 8328
 8329        let text_layout_details = &self.text_layout_details(window);
 8330
 8331        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8332            let line_mode = s.line_mode;
 8333            s.move_with(|map, selection| {
 8334                if !selection.is_empty() && !line_mode {
 8335                    selection.goal = SelectionGoal::None;
 8336                }
 8337                let (cursor, goal) = movement::up_by_rows(
 8338                    map,
 8339                    selection.start,
 8340                    action.lines,
 8341                    selection.goal,
 8342                    false,
 8343                    text_layout_details,
 8344                );
 8345                selection.collapse_to(cursor, goal);
 8346            });
 8347        })
 8348    }
 8349
 8350    pub fn move_down_by_lines(
 8351        &mut self,
 8352        action: &MoveDownByLines,
 8353        window: &mut Window,
 8354        cx: &mut Context<Self>,
 8355    ) {
 8356        if self.take_rename(true, window, cx).is_some() {
 8357            return;
 8358        }
 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
 8367        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8368            let line_mode = s.line_mode;
 8369            s.move_with(|map, selection| {
 8370                if !selection.is_empty() && !line_mode {
 8371                    selection.goal = SelectionGoal::None;
 8372                }
 8373                let (cursor, goal) = movement::down_by_rows(
 8374                    map,
 8375                    selection.start,
 8376                    action.lines,
 8377                    selection.goal,
 8378                    false,
 8379                    text_layout_details,
 8380                );
 8381                selection.collapse_to(cursor, goal);
 8382            });
 8383        })
 8384    }
 8385
 8386    pub fn select_down_by_lines(
 8387        &mut self,
 8388        action: &SelectDownByLines,
 8389        window: &mut Window,
 8390        cx: &mut Context<Self>,
 8391    ) {
 8392        let text_layout_details = &self.text_layout_details(window);
 8393        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8394            s.move_heads_with(|map, head, goal| {
 8395                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8396            })
 8397        })
 8398    }
 8399
 8400    pub fn select_up_by_lines(
 8401        &mut self,
 8402        action: &SelectUpByLines,
 8403        window: &mut Window,
 8404        cx: &mut Context<Self>,
 8405    ) {
 8406        let text_layout_details = &self.text_layout_details(window);
 8407        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8408            s.move_heads_with(|map, head, goal| {
 8409                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8410            })
 8411        })
 8412    }
 8413
 8414    pub fn select_page_up(
 8415        &mut self,
 8416        _: &SelectPageUp,
 8417        window: &mut Window,
 8418        cx: &mut Context<Self>,
 8419    ) {
 8420        let Some(row_count) = self.visible_row_count() else {
 8421            return;
 8422        };
 8423
 8424        let text_layout_details = &self.text_layout_details(window);
 8425
 8426        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8427            s.move_heads_with(|map, head, goal| {
 8428                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8429            })
 8430        })
 8431    }
 8432
 8433    pub fn move_page_up(
 8434        &mut self,
 8435        action: &MovePageUp,
 8436        window: &mut Window,
 8437        cx: &mut Context<Self>,
 8438    ) {
 8439        if self.take_rename(true, window, cx).is_some() {
 8440            return;
 8441        }
 8442
 8443        if self
 8444            .context_menu
 8445            .borrow_mut()
 8446            .as_mut()
 8447            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8448            .unwrap_or(false)
 8449        {
 8450            return;
 8451        }
 8452
 8453        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8454            cx.propagate();
 8455            return;
 8456        }
 8457
 8458        let Some(row_count) = self.visible_row_count() else {
 8459            return;
 8460        };
 8461
 8462        let autoscroll = if action.center_cursor {
 8463            Autoscroll::center()
 8464        } else {
 8465            Autoscroll::fit()
 8466        };
 8467
 8468        let text_layout_details = &self.text_layout_details(window);
 8469
 8470        self.change_selections(Some(autoscroll), window, cx, |s| {
 8471            let line_mode = s.line_mode;
 8472            s.move_with(|map, selection| {
 8473                if !selection.is_empty() && !line_mode {
 8474                    selection.goal = SelectionGoal::None;
 8475                }
 8476                let (cursor, goal) = movement::up_by_rows(
 8477                    map,
 8478                    selection.end,
 8479                    row_count,
 8480                    selection.goal,
 8481                    false,
 8482                    text_layout_details,
 8483                );
 8484                selection.collapse_to(cursor, goal);
 8485            });
 8486        });
 8487    }
 8488
 8489    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8490        let text_layout_details = &self.text_layout_details(window);
 8491        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8492            s.move_heads_with(|map, head, goal| {
 8493                movement::up(map, head, goal, false, text_layout_details)
 8494            })
 8495        })
 8496    }
 8497
 8498    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8499        self.take_rename(true, window, cx);
 8500
 8501        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8502            cx.propagate();
 8503            return;
 8504        }
 8505
 8506        let text_layout_details = &self.text_layout_details(window);
 8507        let selection_count = self.selections.count();
 8508        let first_selection = self.selections.first_anchor();
 8509
 8510        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8511            let line_mode = s.line_mode;
 8512            s.move_with(|map, selection| {
 8513                if !selection.is_empty() && !line_mode {
 8514                    selection.goal = SelectionGoal::None;
 8515                }
 8516                let (cursor, goal) = movement::down(
 8517                    map,
 8518                    selection.end,
 8519                    selection.goal,
 8520                    false,
 8521                    text_layout_details,
 8522                );
 8523                selection.collapse_to(cursor, goal);
 8524            });
 8525        });
 8526
 8527        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8528        {
 8529            cx.propagate();
 8530        }
 8531    }
 8532
 8533    pub fn select_page_down(
 8534        &mut self,
 8535        _: &SelectPageDown,
 8536        window: &mut Window,
 8537        cx: &mut Context<Self>,
 8538    ) {
 8539        let Some(row_count) = self.visible_row_count() else {
 8540            return;
 8541        };
 8542
 8543        let text_layout_details = &self.text_layout_details(window);
 8544
 8545        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8546            s.move_heads_with(|map, head, goal| {
 8547                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8548            })
 8549        })
 8550    }
 8551
 8552    pub fn move_page_down(
 8553        &mut self,
 8554        action: &MovePageDown,
 8555        window: &mut Window,
 8556        cx: &mut Context<Self>,
 8557    ) {
 8558        if self.take_rename(true, window, cx).is_some() {
 8559            return;
 8560        }
 8561
 8562        if self
 8563            .context_menu
 8564            .borrow_mut()
 8565            .as_mut()
 8566            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8567            .unwrap_or(false)
 8568        {
 8569            return;
 8570        }
 8571
 8572        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8573            cx.propagate();
 8574            return;
 8575        }
 8576
 8577        let Some(row_count) = self.visible_row_count() else {
 8578            return;
 8579        };
 8580
 8581        let autoscroll = if action.center_cursor {
 8582            Autoscroll::center()
 8583        } else {
 8584            Autoscroll::fit()
 8585        };
 8586
 8587        let text_layout_details = &self.text_layout_details(window);
 8588        self.change_selections(Some(autoscroll), window, cx, |s| {
 8589            let line_mode = s.line_mode;
 8590            s.move_with(|map, selection| {
 8591                if !selection.is_empty() && !line_mode {
 8592                    selection.goal = SelectionGoal::None;
 8593                }
 8594                let (cursor, goal) = movement::down_by_rows(
 8595                    map,
 8596                    selection.end,
 8597                    row_count,
 8598                    selection.goal,
 8599                    false,
 8600                    text_layout_details,
 8601                );
 8602                selection.collapse_to(cursor, goal);
 8603            });
 8604        });
 8605    }
 8606
 8607    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8608        let text_layout_details = &self.text_layout_details(window);
 8609        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8610            s.move_heads_with(|map, head, goal| {
 8611                movement::down(map, head, goal, false, text_layout_details)
 8612            })
 8613        });
 8614    }
 8615
 8616    pub fn context_menu_first(
 8617        &mut self,
 8618        _: &ContextMenuFirst,
 8619        _window: &mut Window,
 8620        cx: &mut Context<Self>,
 8621    ) {
 8622        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8623            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8624        }
 8625    }
 8626
 8627    pub fn context_menu_prev(
 8628        &mut self,
 8629        _: &ContextMenuPrev,
 8630        _window: &mut Window,
 8631        cx: &mut Context<Self>,
 8632    ) {
 8633        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8634            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8635        }
 8636    }
 8637
 8638    pub fn context_menu_next(
 8639        &mut self,
 8640        _: &ContextMenuNext,
 8641        _window: &mut Window,
 8642        cx: &mut Context<Self>,
 8643    ) {
 8644        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8645            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8646        }
 8647    }
 8648
 8649    pub fn context_menu_last(
 8650        &mut self,
 8651        _: &ContextMenuLast,
 8652        _window: &mut Window,
 8653        cx: &mut Context<Self>,
 8654    ) {
 8655        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8656            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8657        }
 8658    }
 8659
 8660    pub fn move_to_previous_word_start(
 8661        &mut self,
 8662        _: &MoveToPreviousWordStart,
 8663        window: &mut Window,
 8664        cx: &mut Context<Self>,
 8665    ) {
 8666        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8667            s.move_cursors_with(|map, head, _| {
 8668                (
 8669                    movement::previous_word_start(map, head),
 8670                    SelectionGoal::None,
 8671                )
 8672            });
 8673        })
 8674    }
 8675
 8676    pub fn move_to_previous_subword_start(
 8677        &mut self,
 8678        _: &MoveToPreviousSubwordStart,
 8679        window: &mut Window,
 8680        cx: &mut Context<Self>,
 8681    ) {
 8682        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8683            s.move_cursors_with(|map, head, _| {
 8684                (
 8685                    movement::previous_subword_start(map, head),
 8686                    SelectionGoal::None,
 8687                )
 8688            });
 8689        })
 8690    }
 8691
 8692    pub fn select_to_previous_word_start(
 8693        &mut self,
 8694        _: &SelectToPreviousWordStart,
 8695        window: &mut Window,
 8696        cx: &mut Context<Self>,
 8697    ) {
 8698        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8699            s.move_heads_with(|map, head, _| {
 8700                (
 8701                    movement::previous_word_start(map, head),
 8702                    SelectionGoal::None,
 8703                )
 8704            });
 8705        })
 8706    }
 8707
 8708    pub fn select_to_previous_subword_start(
 8709        &mut self,
 8710        _: &SelectToPreviousSubwordStart,
 8711        window: &mut Window,
 8712        cx: &mut Context<Self>,
 8713    ) {
 8714        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8715            s.move_heads_with(|map, head, _| {
 8716                (
 8717                    movement::previous_subword_start(map, head),
 8718                    SelectionGoal::None,
 8719                )
 8720            });
 8721        })
 8722    }
 8723
 8724    pub fn delete_to_previous_word_start(
 8725        &mut self,
 8726        action: &DeleteToPreviousWordStart,
 8727        window: &mut Window,
 8728        cx: &mut Context<Self>,
 8729    ) {
 8730        self.transact(window, cx, |this, window, cx| {
 8731            this.select_autoclose_pair(window, cx);
 8732            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8733                let line_mode = s.line_mode;
 8734                s.move_with(|map, selection| {
 8735                    if selection.is_empty() && !line_mode {
 8736                        let cursor = if action.ignore_newlines {
 8737                            movement::previous_word_start(map, selection.head())
 8738                        } else {
 8739                            movement::previous_word_start_or_newline(map, selection.head())
 8740                        };
 8741                        selection.set_head(cursor, SelectionGoal::None);
 8742                    }
 8743                });
 8744            });
 8745            this.insert("", window, cx);
 8746        });
 8747    }
 8748
 8749    pub fn delete_to_previous_subword_start(
 8750        &mut self,
 8751        _: &DeleteToPreviousSubwordStart,
 8752        window: &mut Window,
 8753        cx: &mut Context<Self>,
 8754    ) {
 8755        self.transact(window, cx, |this, window, cx| {
 8756            this.select_autoclose_pair(window, cx);
 8757            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8758                let line_mode = s.line_mode;
 8759                s.move_with(|map, selection| {
 8760                    if selection.is_empty() && !line_mode {
 8761                        let cursor = movement::previous_subword_start(map, selection.head());
 8762                        selection.set_head(cursor, SelectionGoal::None);
 8763                    }
 8764                });
 8765            });
 8766            this.insert("", window, cx);
 8767        });
 8768    }
 8769
 8770    pub fn move_to_next_word_end(
 8771        &mut self,
 8772        _: &MoveToNextWordEnd,
 8773        window: &mut Window,
 8774        cx: &mut Context<Self>,
 8775    ) {
 8776        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8777            s.move_cursors_with(|map, head, _| {
 8778                (movement::next_word_end(map, head), SelectionGoal::None)
 8779            });
 8780        })
 8781    }
 8782
 8783    pub fn move_to_next_subword_end(
 8784        &mut self,
 8785        _: &MoveToNextSubwordEnd,
 8786        window: &mut Window,
 8787        cx: &mut Context<Self>,
 8788    ) {
 8789        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8790            s.move_cursors_with(|map, head, _| {
 8791                (movement::next_subword_end(map, head), SelectionGoal::None)
 8792            });
 8793        })
 8794    }
 8795
 8796    pub fn select_to_next_word_end(
 8797        &mut self,
 8798        _: &SelectToNextWordEnd,
 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                (movement::next_word_end(map, head), SelectionGoal::None)
 8805            });
 8806        })
 8807    }
 8808
 8809    pub fn select_to_next_subword_end(
 8810        &mut self,
 8811        _: &SelectToNextSubwordEnd,
 8812        window: &mut Window,
 8813        cx: &mut Context<Self>,
 8814    ) {
 8815        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8816            s.move_heads_with(|map, head, _| {
 8817                (movement::next_subword_end(map, head), SelectionGoal::None)
 8818            });
 8819        })
 8820    }
 8821
 8822    pub fn delete_to_next_word_end(
 8823        &mut self,
 8824        action: &DeleteToNextWordEnd,
 8825        window: &mut Window,
 8826        cx: &mut Context<Self>,
 8827    ) {
 8828        self.transact(window, cx, |this, window, cx| {
 8829            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8830                let line_mode = s.line_mode;
 8831                s.move_with(|map, selection| {
 8832                    if selection.is_empty() && !line_mode {
 8833                        let cursor = if action.ignore_newlines {
 8834                            movement::next_word_end(map, selection.head())
 8835                        } else {
 8836                            movement::next_word_end_or_newline(map, selection.head())
 8837                        };
 8838                        selection.set_head(cursor, SelectionGoal::None);
 8839                    }
 8840                });
 8841            });
 8842            this.insert("", window, cx);
 8843        });
 8844    }
 8845
 8846    pub fn delete_to_next_subword_end(
 8847        &mut self,
 8848        _: &DeleteToNextSubwordEnd,
 8849        window: &mut Window,
 8850        cx: &mut Context<Self>,
 8851    ) {
 8852        self.transact(window, cx, |this, window, cx| {
 8853            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8854                s.move_with(|map, selection| {
 8855                    if selection.is_empty() {
 8856                        let cursor = movement::next_subword_end(map, selection.head());
 8857                        selection.set_head(cursor, SelectionGoal::None);
 8858                    }
 8859                });
 8860            });
 8861            this.insert("", window, cx);
 8862        });
 8863    }
 8864
 8865    pub fn move_to_beginning_of_line(
 8866        &mut self,
 8867        action: &MoveToBeginningOfLine,
 8868        window: &mut Window,
 8869        cx: &mut Context<Self>,
 8870    ) {
 8871        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8872            s.move_cursors_with(|map, head, _| {
 8873                (
 8874                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8875                    SelectionGoal::None,
 8876                )
 8877            });
 8878        })
 8879    }
 8880
 8881    pub fn select_to_beginning_of_line(
 8882        &mut self,
 8883        action: &SelectToBeginningOfLine,
 8884        window: &mut Window,
 8885        cx: &mut Context<Self>,
 8886    ) {
 8887        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8888            s.move_heads_with(|map, head, _| {
 8889                (
 8890                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8891                    SelectionGoal::None,
 8892                )
 8893            });
 8894        });
 8895    }
 8896
 8897    pub fn delete_to_beginning_of_line(
 8898        &mut self,
 8899        _: &DeleteToBeginningOfLine,
 8900        window: &mut Window,
 8901        cx: &mut Context<Self>,
 8902    ) {
 8903        self.transact(window, cx, |this, window, cx| {
 8904            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8905                s.move_with(|_, selection| {
 8906                    selection.reversed = true;
 8907                });
 8908            });
 8909
 8910            this.select_to_beginning_of_line(
 8911                &SelectToBeginningOfLine {
 8912                    stop_at_soft_wraps: false,
 8913                },
 8914                window,
 8915                cx,
 8916            );
 8917            this.backspace(&Backspace, window, cx);
 8918        });
 8919    }
 8920
 8921    pub fn move_to_end_of_line(
 8922        &mut self,
 8923        action: &MoveToEndOfLine,
 8924        window: &mut Window,
 8925        cx: &mut Context<Self>,
 8926    ) {
 8927        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8928            s.move_cursors_with(|map, head, _| {
 8929                (
 8930                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8931                    SelectionGoal::None,
 8932                )
 8933            });
 8934        })
 8935    }
 8936
 8937    pub fn select_to_end_of_line(
 8938        &mut self,
 8939        action: &SelectToEndOfLine,
 8940        window: &mut Window,
 8941        cx: &mut Context<Self>,
 8942    ) {
 8943        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8944            s.move_heads_with(|map, head, _| {
 8945                (
 8946                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8947                    SelectionGoal::None,
 8948                )
 8949            });
 8950        })
 8951    }
 8952
 8953    pub fn delete_to_end_of_line(
 8954        &mut self,
 8955        _: &DeleteToEndOfLine,
 8956        window: &mut Window,
 8957        cx: &mut Context<Self>,
 8958    ) {
 8959        self.transact(window, cx, |this, window, cx| {
 8960            this.select_to_end_of_line(
 8961                &SelectToEndOfLine {
 8962                    stop_at_soft_wraps: false,
 8963                },
 8964                window,
 8965                cx,
 8966            );
 8967            this.delete(&Delete, window, cx);
 8968        });
 8969    }
 8970
 8971    pub fn cut_to_end_of_line(
 8972        &mut self,
 8973        _: &CutToEndOfLine,
 8974        window: &mut Window,
 8975        cx: &mut Context<Self>,
 8976    ) {
 8977        self.transact(window, cx, |this, window, cx| {
 8978            this.select_to_end_of_line(
 8979                &SelectToEndOfLine {
 8980                    stop_at_soft_wraps: false,
 8981                },
 8982                window,
 8983                cx,
 8984            );
 8985            this.cut(&Cut, window, cx);
 8986        });
 8987    }
 8988
 8989    pub fn move_to_start_of_paragraph(
 8990        &mut self,
 8991        _: &MoveToStartOfParagraph,
 8992        window: &mut Window,
 8993        cx: &mut Context<Self>,
 8994    ) {
 8995        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8996            cx.propagate();
 8997            return;
 8998        }
 8999
 9000        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9001            s.move_with(|map, selection| {
 9002                selection.collapse_to(
 9003                    movement::start_of_paragraph(map, selection.head(), 1),
 9004                    SelectionGoal::None,
 9005                )
 9006            });
 9007        })
 9008    }
 9009
 9010    pub fn move_to_end_of_paragraph(
 9011        &mut self,
 9012        _: &MoveToEndOfParagraph,
 9013        window: &mut Window,
 9014        cx: &mut Context<Self>,
 9015    ) {
 9016        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9017            cx.propagate();
 9018            return;
 9019        }
 9020
 9021        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9022            s.move_with(|map, selection| {
 9023                selection.collapse_to(
 9024                    movement::end_of_paragraph(map, selection.head(), 1),
 9025                    SelectionGoal::None,
 9026                )
 9027            });
 9028        })
 9029    }
 9030
 9031    pub fn select_to_start_of_paragraph(
 9032        &mut self,
 9033        _: &SelectToStartOfParagraph,
 9034        window: &mut Window,
 9035        cx: &mut Context<Self>,
 9036    ) {
 9037        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9038            cx.propagate();
 9039            return;
 9040        }
 9041
 9042        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9043            s.move_heads_with(|map, head, _| {
 9044                (
 9045                    movement::start_of_paragraph(map, head, 1),
 9046                    SelectionGoal::None,
 9047                )
 9048            });
 9049        })
 9050    }
 9051
 9052    pub fn select_to_end_of_paragraph(
 9053        &mut self,
 9054        _: &SelectToEndOfParagraph,
 9055        window: &mut Window,
 9056        cx: &mut Context<Self>,
 9057    ) {
 9058        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9059            cx.propagate();
 9060            return;
 9061        }
 9062
 9063        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9064            s.move_heads_with(|map, head, _| {
 9065                (
 9066                    movement::end_of_paragraph(map, head, 1),
 9067                    SelectionGoal::None,
 9068                )
 9069            });
 9070        })
 9071    }
 9072
 9073    pub fn move_to_beginning(
 9074        &mut self,
 9075        _: &MoveToBeginning,
 9076        window: &mut Window,
 9077        cx: &mut Context<Self>,
 9078    ) {
 9079        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9080            cx.propagate();
 9081            return;
 9082        }
 9083
 9084        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9085            s.select_ranges(vec![0..0]);
 9086        });
 9087    }
 9088
 9089    pub fn select_to_beginning(
 9090        &mut self,
 9091        _: &SelectToBeginning,
 9092        window: &mut Window,
 9093        cx: &mut Context<Self>,
 9094    ) {
 9095        let mut selection = self.selections.last::<Point>(cx);
 9096        selection.set_head(Point::zero(), SelectionGoal::None);
 9097
 9098        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9099            s.select(vec![selection]);
 9100        });
 9101    }
 9102
 9103    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9104        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9105            cx.propagate();
 9106            return;
 9107        }
 9108
 9109        let cursor = self.buffer.read(cx).read(cx).len();
 9110        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9111            s.select_ranges(vec![cursor..cursor])
 9112        });
 9113    }
 9114
 9115    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9116        self.nav_history = nav_history;
 9117    }
 9118
 9119    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9120        self.nav_history.as_ref()
 9121    }
 9122
 9123    fn push_to_nav_history(
 9124        &mut self,
 9125        cursor_anchor: Anchor,
 9126        new_position: Option<Point>,
 9127        cx: &mut Context<Self>,
 9128    ) {
 9129        if let Some(nav_history) = self.nav_history.as_mut() {
 9130            let buffer = self.buffer.read(cx).read(cx);
 9131            let cursor_position = cursor_anchor.to_point(&buffer);
 9132            let scroll_state = self.scroll_manager.anchor();
 9133            let scroll_top_row = scroll_state.top_row(&buffer);
 9134            drop(buffer);
 9135
 9136            if let Some(new_position) = new_position {
 9137                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9138                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9139                    return;
 9140                }
 9141            }
 9142
 9143            nav_history.push(
 9144                Some(NavigationData {
 9145                    cursor_anchor,
 9146                    cursor_position,
 9147                    scroll_anchor: scroll_state,
 9148                    scroll_top_row,
 9149                }),
 9150                cx,
 9151            );
 9152        }
 9153    }
 9154
 9155    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9156        let buffer = self.buffer.read(cx).snapshot(cx);
 9157        let mut selection = self.selections.first::<usize>(cx);
 9158        selection.set_head(buffer.len(), SelectionGoal::None);
 9159        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9160            s.select(vec![selection]);
 9161        });
 9162    }
 9163
 9164    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9165        let end = self.buffer.read(cx).read(cx).len();
 9166        self.change_selections(None, window, cx, |s| {
 9167            s.select_ranges(vec![0..end]);
 9168        });
 9169    }
 9170
 9171    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9172        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9173        let mut selections = self.selections.all::<Point>(cx);
 9174        let max_point = display_map.buffer_snapshot.max_point();
 9175        for selection in &mut selections {
 9176            let rows = selection.spanned_rows(true, &display_map);
 9177            selection.start = Point::new(rows.start.0, 0);
 9178            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9179            selection.reversed = false;
 9180        }
 9181        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9182            s.select(selections);
 9183        });
 9184    }
 9185
 9186    pub fn split_selection_into_lines(
 9187        &mut self,
 9188        _: &SplitSelectionIntoLines,
 9189        window: &mut Window,
 9190        cx: &mut Context<Self>,
 9191    ) {
 9192        let selections = self
 9193            .selections
 9194            .all::<Point>(cx)
 9195            .into_iter()
 9196            .map(|selection| selection.start..selection.end)
 9197            .collect::<Vec<_>>();
 9198        self.unfold_ranges(&selections, true, true, cx);
 9199
 9200        let mut new_selection_ranges = Vec::new();
 9201        {
 9202            let buffer = self.buffer.read(cx).read(cx);
 9203            for selection in selections {
 9204                for row in selection.start.row..selection.end.row {
 9205                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9206                    new_selection_ranges.push(cursor..cursor);
 9207                }
 9208
 9209                let is_multiline_selection = selection.start.row != selection.end.row;
 9210                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9211                // so this action feels more ergonomic when paired with other selection operations
 9212                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9213                if !should_skip_last {
 9214                    new_selection_ranges.push(selection.end..selection.end);
 9215                }
 9216            }
 9217        }
 9218        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9219            s.select_ranges(new_selection_ranges);
 9220        });
 9221    }
 9222
 9223    pub fn add_selection_above(
 9224        &mut self,
 9225        _: &AddSelectionAbove,
 9226        window: &mut Window,
 9227        cx: &mut Context<Self>,
 9228    ) {
 9229        self.add_selection(true, window, cx);
 9230    }
 9231
 9232    pub fn add_selection_below(
 9233        &mut self,
 9234        _: &AddSelectionBelow,
 9235        window: &mut Window,
 9236        cx: &mut Context<Self>,
 9237    ) {
 9238        self.add_selection(false, window, cx);
 9239    }
 9240
 9241    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9242        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9243        let mut selections = self.selections.all::<Point>(cx);
 9244        let text_layout_details = self.text_layout_details(window);
 9245        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9246            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9247            let range = oldest_selection.display_range(&display_map).sorted();
 9248
 9249            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9250            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9251            let positions = start_x.min(end_x)..start_x.max(end_x);
 9252
 9253            selections.clear();
 9254            let mut stack = Vec::new();
 9255            for row in range.start.row().0..=range.end.row().0 {
 9256                if let Some(selection) = self.selections.build_columnar_selection(
 9257                    &display_map,
 9258                    DisplayRow(row),
 9259                    &positions,
 9260                    oldest_selection.reversed,
 9261                    &text_layout_details,
 9262                ) {
 9263                    stack.push(selection.id);
 9264                    selections.push(selection);
 9265                }
 9266            }
 9267
 9268            if above {
 9269                stack.reverse();
 9270            }
 9271
 9272            AddSelectionsState { above, stack }
 9273        });
 9274
 9275        let last_added_selection = *state.stack.last().unwrap();
 9276        let mut new_selections = Vec::new();
 9277        if above == state.above {
 9278            let end_row = if above {
 9279                DisplayRow(0)
 9280            } else {
 9281                display_map.max_point().row()
 9282            };
 9283
 9284            'outer: for selection in selections {
 9285                if selection.id == last_added_selection {
 9286                    let range = selection.display_range(&display_map).sorted();
 9287                    debug_assert_eq!(range.start.row(), range.end.row());
 9288                    let mut row = range.start.row();
 9289                    let positions =
 9290                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9291                            px(start)..px(end)
 9292                        } else {
 9293                            let start_x =
 9294                                display_map.x_for_display_point(range.start, &text_layout_details);
 9295                            let end_x =
 9296                                display_map.x_for_display_point(range.end, &text_layout_details);
 9297                            start_x.min(end_x)..start_x.max(end_x)
 9298                        };
 9299
 9300                    while row != end_row {
 9301                        if above {
 9302                            row.0 -= 1;
 9303                        } else {
 9304                            row.0 += 1;
 9305                        }
 9306
 9307                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9308                            &display_map,
 9309                            row,
 9310                            &positions,
 9311                            selection.reversed,
 9312                            &text_layout_details,
 9313                        ) {
 9314                            state.stack.push(new_selection.id);
 9315                            if above {
 9316                                new_selections.push(new_selection);
 9317                                new_selections.push(selection);
 9318                            } else {
 9319                                new_selections.push(selection);
 9320                                new_selections.push(new_selection);
 9321                            }
 9322
 9323                            continue 'outer;
 9324                        }
 9325                    }
 9326                }
 9327
 9328                new_selections.push(selection);
 9329            }
 9330        } else {
 9331            new_selections = selections;
 9332            new_selections.retain(|s| s.id != last_added_selection);
 9333            state.stack.pop();
 9334        }
 9335
 9336        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9337            s.select(new_selections);
 9338        });
 9339        if state.stack.len() > 1 {
 9340            self.add_selections_state = Some(state);
 9341        }
 9342    }
 9343
 9344    pub fn select_next_match_internal(
 9345        &mut self,
 9346        display_map: &DisplaySnapshot,
 9347        replace_newest: bool,
 9348        autoscroll: Option<Autoscroll>,
 9349        window: &mut Window,
 9350        cx: &mut Context<Self>,
 9351    ) -> Result<()> {
 9352        fn select_next_match_ranges(
 9353            this: &mut Editor,
 9354            range: Range<usize>,
 9355            replace_newest: bool,
 9356            auto_scroll: Option<Autoscroll>,
 9357            window: &mut Window,
 9358            cx: &mut Context<Editor>,
 9359        ) {
 9360            this.unfold_ranges(&[range.clone()], false, true, cx);
 9361            this.change_selections(auto_scroll, window, cx, |s| {
 9362                if replace_newest {
 9363                    s.delete(s.newest_anchor().id);
 9364                }
 9365                s.insert_range(range.clone());
 9366            });
 9367        }
 9368
 9369        let buffer = &display_map.buffer_snapshot;
 9370        let mut selections = self.selections.all::<usize>(cx);
 9371        if let Some(mut select_next_state) = self.select_next_state.take() {
 9372            let query = &select_next_state.query;
 9373            if !select_next_state.done {
 9374                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9375                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9376                let mut next_selected_range = None;
 9377
 9378                let bytes_after_last_selection =
 9379                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9380                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9381                let query_matches = query
 9382                    .stream_find_iter(bytes_after_last_selection)
 9383                    .map(|result| (last_selection.end, result))
 9384                    .chain(
 9385                        query
 9386                            .stream_find_iter(bytes_before_first_selection)
 9387                            .map(|result| (0, result)),
 9388                    );
 9389
 9390                for (start_offset, query_match) in query_matches {
 9391                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9392                    let offset_range =
 9393                        start_offset + query_match.start()..start_offset + query_match.end();
 9394                    let display_range = offset_range.start.to_display_point(display_map)
 9395                        ..offset_range.end.to_display_point(display_map);
 9396
 9397                    if !select_next_state.wordwise
 9398                        || (!movement::is_inside_word(display_map, display_range.start)
 9399                            && !movement::is_inside_word(display_map, display_range.end))
 9400                    {
 9401                        // TODO: This is n^2, because we might check all the selections
 9402                        if !selections
 9403                            .iter()
 9404                            .any(|selection| selection.range().overlaps(&offset_range))
 9405                        {
 9406                            next_selected_range = Some(offset_range);
 9407                            break;
 9408                        }
 9409                    }
 9410                }
 9411
 9412                if let Some(next_selected_range) = next_selected_range {
 9413                    select_next_match_ranges(
 9414                        self,
 9415                        next_selected_range,
 9416                        replace_newest,
 9417                        autoscroll,
 9418                        window,
 9419                        cx,
 9420                    );
 9421                } else {
 9422                    select_next_state.done = true;
 9423                }
 9424            }
 9425
 9426            self.select_next_state = Some(select_next_state);
 9427        } else {
 9428            let mut only_carets = true;
 9429            let mut same_text_selected = true;
 9430            let mut selected_text = None;
 9431
 9432            let mut selections_iter = selections.iter().peekable();
 9433            while let Some(selection) = selections_iter.next() {
 9434                if selection.start != selection.end {
 9435                    only_carets = false;
 9436                }
 9437
 9438                if same_text_selected {
 9439                    if selected_text.is_none() {
 9440                        selected_text =
 9441                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9442                    }
 9443
 9444                    if let Some(next_selection) = selections_iter.peek() {
 9445                        if next_selection.range().len() == selection.range().len() {
 9446                            let next_selected_text = buffer
 9447                                .text_for_range(next_selection.range())
 9448                                .collect::<String>();
 9449                            if Some(next_selected_text) != selected_text {
 9450                                same_text_selected = false;
 9451                                selected_text = None;
 9452                            }
 9453                        } else {
 9454                            same_text_selected = false;
 9455                            selected_text = None;
 9456                        }
 9457                    }
 9458                }
 9459            }
 9460
 9461            if only_carets {
 9462                for selection in &mut selections {
 9463                    let word_range = movement::surrounding_word(
 9464                        display_map,
 9465                        selection.start.to_display_point(display_map),
 9466                    );
 9467                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9468                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9469                    selection.goal = SelectionGoal::None;
 9470                    selection.reversed = false;
 9471                    select_next_match_ranges(
 9472                        self,
 9473                        selection.start..selection.end,
 9474                        replace_newest,
 9475                        autoscroll,
 9476                        window,
 9477                        cx,
 9478                    );
 9479                }
 9480
 9481                if selections.len() == 1 {
 9482                    let selection = selections
 9483                        .last()
 9484                        .expect("ensured that there's only one selection");
 9485                    let query = buffer
 9486                        .text_for_range(selection.start..selection.end)
 9487                        .collect::<String>();
 9488                    let is_empty = query.is_empty();
 9489                    let select_state = SelectNextState {
 9490                        query: AhoCorasick::new(&[query])?,
 9491                        wordwise: true,
 9492                        done: is_empty,
 9493                    };
 9494                    self.select_next_state = Some(select_state);
 9495                } else {
 9496                    self.select_next_state = None;
 9497                }
 9498            } else if let Some(selected_text) = selected_text {
 9499                self.select_next_state = Some(SelectNextState {
 9500                    query: AhoCorasick::new(&[selected_text])?,
 9501                    wordwise: false,
 9502                    done: false,
 9503                });
 9504                self.select_next_match_internal(
 9505                    display_map,
 9506                    replace_newest,
 9507                    autoscroll,
 9508                    window,
 9509                    cx,
 9510                )?;
 9511            }
 9512        }
 9513        Ok(())
 9514    }
 9515
 9516    pub fn select_all_matches(
 9517        &mut self,
 9518        _action: &SelectAllMatches,
 9519        window: &mut Window,
 9520        cx: &mut Context<Self>,
 9521    ) -> Result<()> {
 9522        self.push_to_selection_history();
 9523        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9524
 9525        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9526        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9527            return Ok(());
 9528        };
 9529        if select_next_state.done {
 9530            return Ok(());
 9531        }
 9532
 9533        let mut new_selections = self.selections.all::<usize>(cx);
 9534
 9535        let buffer = &display_map.buffer_snapshot;
 9536        let query_matches = select_next_state
 9537            .query
 9538            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9539
 9540        for query_match in query_matches {
 9541            let query_match = query_match.unwrap(); // can only fail due to I/O
 9542            let offset_range = query_match.start()..query_match.end();
 9543            let display_range = offset_range.start.to_display_point(&display_map)
 9544                ..offset_range.end.to_display_point(&display_map);
 9545
 9546            if !select_next_state.wordwise
 9547                || (!movement::is_inside_word(&display_map, display_range.start)
 9548                    && !movement::is_inside_word(&display_map, display_range.end))
 9549            {
 9550                self.selections.change_with(cx, |selections| {
 9551                    new_selections.push(Selection {
 9552                        id: selections.new_selection_id(),
 9553                        start: offset_range.start,
 9554                        end: offset_range.end,
 9555                        reversed: false,
 9556                        goal: SelectionGoal::None,
 9557                    });
 9558                });
 9559            }
 9560        }
 9561
 9562        new_selections.sort_by_key(|selection| selection.start);
 9563        let mut ix = 0;
 9564        while ix + 1 < new_selections.len() {
 9565            let current_selection = &new_selections[ix];
 9566            let next_selection = &new_selections[ix + 1];
 9567            if current_selection.range().overlaps(&next_selection.range()) {
 9568                if current_selection.id < next_selection.id {
 9569                    new_selections.remove(ix + 1);
 9570                } else {
 9571                    new_selections.remove(ix);
 9572                }
 9573            } else {
 9574                ix += 1;
 9575            }
 9576        }
 9577
 9578        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9579
 9580        for selection in new_selections.iter_mut() {
 9581            selection.reversed = reversed;
 9582        }
 9583
 9584        select_next_state.done = true;
 9585        self.unfold_ranges(
 9586            &new_selections
 9587                .iter()
 9588                .map(|selection| selection.range())
 9589                .collect::<Vec<_>>(),
 9590            false,
 9591            false,
 9592            cx,
 9593        );
 9594        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9595            selections.select(new_selections)
 9596        });
 9597
 9598        Ok(())
 9599    }
 9600
 9601    pub fn select_next(
 9602        &mut self,
 9603        action: &SelectNext,
 9604        window: &mut Window,
 9605        cx: &mut Context<Self>,
 9606    ) -> Result<()> {
 9607        self.push_to_selection_history();
 9608        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9609        self.select_next_match_internal(
 9610            &display_map,
 9611            action.replace_newest,
 9612            Some(Autoscroll::newest()),
 9613            window,
 9614            cx,
 9615        )?;
 9616        Ok(())
 9617    }
 9618
 9619    pub fn select_previous(
 9620        &mut self,
 9621        action: &SelectPrevious,
 9622        window: &mut Window,
 9623        cx: &mut Context<Self>,
 9624    ) -> Result<()> {
 9625        self.push_to_selection_history();
 9626        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9627        let buffer = &display_map.buffer_snapshot;
 9628        let mut selections = self.selections.all::<usize>(cx);
 9629        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9630            let query = &select_prev_state.query;
 9631            if !select_prev_state.done {
 9632                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9633                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9634                let mut next_selected_range = None;
 9635                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9636                let bytes_before_last_selection =
 9637                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9638                let bytes_after_first_selection =
 9639                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9640                let query_matches = query
 9641                    .stream_find_iter(bytes_before_last_selection)
 9642                    .map(|result| (last_selection.start, result))
 9643                    .chain(
 9644                        query
 9645                            .stream_find_iter(bytes_after_first_selection)
 9646                            .map(|result| (buffer.len(), result)),
 9647                    );
 9648                for (end_offset, query_match) in query_matches {
 9649                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9650                    let offset_range =
 9651                        end_offset - query_match.end()..end_offset - query_match.start();
 9652                    let display_range = offset_range.start.to_display_point(&display_map)
 9653                        ..offset_range.end.to_display_point(&display_map);
 9654
 9655                    if !select_prev_state.wordwise
 9656                        || (!movement::is_inside_word(&display_map, display_range.start)
 9657                            && !movement::is_inside_word(&display_map, display_range.end))
 9658                    {
 9659                        next_selected_range = Some(offset_range);
 9660                        break;
 9661                    }
 9662                }
 9663
 9664                if let Some(next_selected_range) = next_selected_range {
 9665                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9666                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9667                        if action.replace_newest {
 9668                            s.delete(s.newest_anchor().id);
 9669                        }
 9670                        s.insert_range(next_selected_range);
 9671                    });
 9672                } else {
 9673                    select_prev_state.done = true;
 9674                }
 9675            }
 9676
 9677            self.select_prev_state = Some(select_prev_state);
 9678        } else {
 9679            let mut only_carets = true;
 9680            let mut same_text_selected = true;
 9681            let mut selected_text = None;
 9682
 9683            let mut selections_iter = selections.iter().peekable();
 9684            while let Some(selection) = selections_iter.next() {
 9685                if selection.start != selection.end {
 9686                    only_carets = false;
 9687                }
 9688
 9689                if same_text_selected {
 9690                    if selected_text.is_none() {
 9691                        selected_text =
 9692                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9693                    }
 9694
 9695                    if let Some(next_selection) = selections_iter.peek() {
 9696                        if next_selection.range().len() == selection.range().len() {
 9697                            let next_selected_text = buffer
 9698                                .text_for_range(next_selection.range())
 9699                                .collect::<String>();
 9700                            if Some(next_selected_text) != selected_text {
 9701                                same_text_selected = false;
 9702                                selected_text = None;
 9703                            }
 9704                        } else {
 9705                            same_text_selected = false;
 9706                            selected_text = None;
 9707                        }
 9708                    }
 9709                }
 9710            }
 9711
 9712            if only_carets {
 9713                for selection in &mut selections {
 9714                    let word_range = movement::surrounding_word(
 9715                        &display_map,
 9716                        selection.start.to_display_point(&display_map),
 9717                    );
 9718                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9719                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9720                    selection.goal = SelectionGoal::None;
 9721                    selection.reversed = false;
 9722                }
 9723                if selections.len() == 1 {
 9724                    let selection = selections
 9725                        .last()
 9726                        .expect("ensured that there's only one selection");
 9727                    let query = buffer
 9728                        .text_for_range(selection.start..selection.end)
 9729                        .collect::<String>();
 9730                    let is_empty = query.is_empty();
 9731                    let select_state = SelectNextState {
 9732                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9733                        wordwise: true,
 9734                        done: is_empty,
 9735                    };
 9736                    self.select_prev_state = Some(select_state);
 9737                } else {
 9738                    self.select_prev_state = None;
 9739                }
 9740
 9741                self.unfold_ranges(
 9742                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9743                    false,
 9744                    true,
 9745                    cx,
 9746                );
 9747                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9748                    s.select(selections);
 9749                });
 9750            } else if let Some(selected_text) = selected_text {
 9751                self.select_prev_state = Some(SelectNextState {
 9752                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9753                    wordwise: false,
 9754                    done: false,
 9755                });
 9756                self.select_previous(action, window, cx)?;
 9757            }
 9758        }
 9759        Ok(())
 9760    }
 9761
 9762    pub fn toggle_comments(
 9763        &mut self,
 9764        action: &ToggleComments,
 9765        window: &mut Window,
 9766        cx: &mut Context<Self>,
 9767    ) {
 9768        if self.read_only(cx) {
 9769            return;
 9770        }
 9771        let text_layout_details = &self.text_layout_details(window);
 9772        self.transact(window, cx, |this, window, cx| {
 9773            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9774            let mut edits = Vec::new();
 9775            let mut selection_edit_ranges = Vec::new();
 9776            let mut last_toggled_row = None;
 9777            let snapshot = this.buffer.read(cx).read(cx);
 9778            let empty_str: Arc<str> = Arc::default();
 9779            let mut suffixes_inserted = Vec::new();
 9780            let ignore_indent = action.ignore_indent;
 9781
 9782            fn comment_prefix_range(
 9783                snapshot: &MultiBufferSnapshot,
 9784                row: MultiBufferRow,
 9785                comment_prefix: &str,
 9786                comment_prefix_whitespace: &str,
 9787                ignore_indent: bool,
 9788            ) -> Range<Point> {
 9789                let indent_size = if ignore_indent {
 9790                    0
 9791                } else {
 9792                    snapshot.indent_size_for_line(row).len
 9793                };
 9794
 9795                let start = Point::new(row.0, indent_size);
 9796
 9797                let mut line_bytes = snapshot
 9798                    .bytes_in_range(start..snapshot.max_point())
 9799                    .flatten()
 9800                    .copied();
 9801
 9802                // If this line currently begins with the line comment prefix, then record
 9803                // the range containing the prefix.
 9804                if line_bytes
 9805                    .by_ref()
 9806                    .take(comment_prefix.len())
 9807                    .eq(comment_prefix.bytes())
 9808                {
 9809                    // Include any whitespace that matches the comment prefix.
 9810                    let matching_whitespace_len = line_bytes
 9811                        .zip(comment_prefix_whitespace.bytes())
 9812                        .take_while(|(a, b)| a == b)
 9813                        .count() as u32;
 9814                    let end = Point::new(
 9815                        start.row,
 9816                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9817                    );
 9818                    start..end
 9819                } else {
 9820                    start..start
 9821                }
 9822            }
 9823
 9824            fn comment_suffix_range(
 9825                snapshot: &MultiBufferSnapshot,
 9826                row: MultiBufferRow,
 9827                comment_suffix: &str,
 9828                comment_suffix_has_leading_space: bool,
 9829            ) -> Range<Point> {
 9830                let end = Point::new(row.0, snapshot.line_len(row));
 9831                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9832
 9833                let mut line_end_bytes = snapshot
 9834                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9835                    .flatten()
 9836                    .copied();
 9837
 9838                let leading_space_len = if suffix_start_column > 0
 9839                    && line_end_bytes.next() == Some(b' ')
 9840                    && comment_suffix_has_leading_space
 9841                {
 9842                    1
 9843                } else {
 9844                    0
 9845                };
 9846
 9847                // If this line currently begins with the line comment prefix, then record
 9848                // the range containing the prefix.
 9849                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9850                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9851                    start..end
 9852                } else {
 9853                    end..end
 9854                }
 9855            }
 9856
 9857            // TODO: Handle selections that cross excerpts
 9858            for selection in &mut selections {
 9859                let start_column = snapshot
 9860                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9861                    .len;
 9862                let language = if let Some(language) =
 9863                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9864                {
 9865                    language
 9866                } else {
 9867                    continue;
 9868                };
 9869
 9870                selection_edit_ranges.clear();
 9871
 9872                // If multiple selections contain a given row, avoid processing that
 9873                // row more than once.
 9874                let mut start_row = MultiBufferRow(selection.start.row);
 9875                if last_toggled_row == Some(start_row) {
 9876                    start_row = start_row.next_row();
 9877                }
 9878                let end_row =
 9879                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9880                        MultiBufferRow(selection.end.row - 1)
 9881                    } else {
 9882                        MultiBufferRow(selection.end.row)
 9883                    };
 9884                last_toggled_row = Some(end_row);
 9885
 9886                if start_row > end_row {
 9887                    continue;
 9888                }
 9889
 9890                // If the language has line comments, toggle those.
 9891                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9892
 9893                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9894                if ignore_indent {
 9895                    full_comment_prefixes = full_comment_prefixes
 9896                        .into_iter()
 9897                        .map(|s| Arc::from(s.trim_end()))
 9898                        .collect();
 9899                }
 9900
 9901                if !full_comment_prefixes.is_empty() {
 9902                    let first_prefix = full_comment_prefixes
 9903                        .first()
 9904                        .expect("prefixes is non-empty");
 9905                    let prefix_trimmed_lengths = full_comment_prefixes
 9906                        .iter()
 9907                        .map(|p| p.trim_end_matches(' ').len())
 9908                        .collect::<SmallVec<[usize; 4]>>();
 9909
 9910                    let mut all_selection_lines_are_comments = true;
 9911
 9912                    for row in start_row.0..=end_row.0 {
 9913                        let row = MultiBufferRow(row);
 9914                        if start_row < end_row && snapshot.is_line_blank(row) {
 9915                            continue;
 9916                        }
 9917
 9918                        let prefix_range = full_comment_prefixes
 9919                            .iter()
 9920                            .zip(prefix_trimmed_lengths.iter().copied())
 9921                            .map(|(prefix, trimmed_prefix_len)| {
 9922                                comment_prefix_range(
 9923                                    snapshot.deref(),
 9924                                    row,
 9925                                    &prefix[..trimmed_prefix_len],
 9926                                    &prefix[trimmed_prefix_len..],
 9927                                    ignore_indent,
 9928                                )
 9929                            })
 9930                            .max_by_key(|range| range.end.column - range.start.column)
 9931                            .expect("prefixes is non-empty");
 9932
 9933                        if prefix_range.is_empty() {
 9934                            all_selection_lines_are_comments = false;
 9935                        }
 9936
 9937                        selection_edit_ranges.push(prefix_range);
 9938                    }
 9939
 9940                    if all_selection_lines_are_comments {
 9941                        edits.extend(
 9942                            selection_edit_ranges
 9943                                .iter()
 9944                                .cloned()
 9945                                .map(|range| (range, empty_str.clone())),
 9946                        );
 9947                    } else {
 9948                        let min_column = selection_edit_ranges
 9949                            .iter()
 9950                            .map(|range| range.start.column)
 9951                            .min()
 9952                            .unwrap_or(0);
 9953                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9954                            let position = Point::new(range.start.row, min_column);
 9955                            (position..position, first_prefix.clone())
 9956                        }));
 9957                    }
 9958                } else if let Some((full_comment_prefix, comment_suffix)) =
 9959                    language.block_comment_delimiters()
 9960                {
 9961                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9962                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9963                    let prefix_range = comment_prefix_range(
 9964                        snapshot.deref(),
 9965                        start_row,
 9966                        comment_prefix,
 9967                        comment_prefix_whitespace,
 9968                        ignore_indent,
 9969                    );
 9970                    let suffix_range = comment_suffix_range(
 9971                        snapshot.deref(),
 9972                        end_row,
 9973                        comment_suffix.trim_start_matches(' '),
 9974                        comment_suffix.starts_with(' '),
 9975                    );
 9976
 9977                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9978                        edits.push((
 9979                            prefix_range.start..prefix_range.start,
 9980                            full_comment_prefix.clone(),
 9981                        ));
 9982                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9983                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9984                    } else {
 9985                        edits.push((prefix_range, empty_str.clone()));
 9986                        edits.push((suffix_range, empty_str.clone()));
 9987                    }
 9988                } else {
 9989                    continue;
 9990                }
 9991            }
 9992
 9993            drop(snapshot);
 9994            this.buffer.update(cx, |buffer, cx| {
 9995                buffer.edit(edits, None, cx);
 9996            });
 9997
 9998            // Adjust selections so that they end before any comment suffixes that
 9999            // were inserted.
10000            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10001            let mut selections = this.selections.all::<Point>(cx);
10002            let snapshot = this.buffer.read(cx).read(cx);
10003            for selection in &mut selections {
10004                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10005                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10006                        Ordering::Less => {
10007                            suffixes_inserted.next();
10008                            continue;
10009                        }
10010                        Ordering::Greater => break,
10011                        Ordering::Equal => {
10012                            if selection.end.column == snapshot.line_len(row) {
10013                                if selection.is_empty() {
10014                                    selection.start.column -= suffix_len as u32;
10015                                }
10016                                selection.end.column -= suffix_len as u32;
10017                            }
10018                            break;
10019                        }
10020                    }
10021                }
10022            }
10023
10024            drop(snapshot);
10025            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10026                s.select(selections)
10027            });
10028
10029            let selections = this.selections.all::<Point>(cx);
10030            let selections_on_single_row = selections.windows(2).all(|selections| {
10031                selections[0].start.row == selections[1].start.row
10032                    && selections[0].end.row == selections[1].end.row
10033                    && selections[0].start.row == selections[0].end.row
10034            });
10035            let selections_selecting = selections
10036                .iter()
10037                .any(|selection| selection.start != selection.end);
10038            let advance_downwards = action.advance_downwards
10039                && selections_on_single_row
10040                && !selections_selecting
10041                && !matches!(this.mode, EditorMode::SingleLine { .. });
10042
10043            if advance_downwards {
10044                let snapshot = this.buffer.read(cx).snapshot(cx);
10045
10046                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10047                    s.move_cursors_with(|display_snapshot, display_point, _| {
10048                        let mut point = display_point.to_point(display_snapshot);
10049                        point.row += 1;
10050                        point = snapshot.clip_point(point, Bias::Left);
10051                        let display_point = point.to_display_point(display_snapshot);
10052                        let goal = SelectionGoal::HorizontalPosition(
10053                            display_snapshot
10054                                .x_for_display_point(display_point, text_layout_details)
10055                                .into(),
10056                        );
10057                        (display_point, goal)
10058                    })
10059                });
10060            }
10061        });
10062    }
10063
10064    pub fn select_enclosing_symbol(
10065        &mut self,
10066        _: &SelectEnclosingSymbol,
10067        window: &mut Window,
10068        cx: &mut Context<Self>,
10069    ) {
10070        let buffer = self.buffer.read(cx).snapshot(cx);
10071        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10072
10073        fn update_selection(
10074            selection: &Selection<usize>,
10075            buffer_snap: &MultiBufferSnapshot,
10076        ) -> Option<Selection<usize>> {
10077            let cursor = selection.head();
10078            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10079            for symbol in symbols.iter().rev() {
10080                let start = symbol.range.start.to_offset(buffer_snap);
10081                let end = symbol.range.end.to_offset(buffer_snap);
10082                let new_range = start..end;
10083                if start < selection.start || end > selection.end {
10084                    return Some(Selection {
10085                        id: selection.id,
10086                        start: new_range.start,
10087                        end: new_range.end,
10088                        goal: SelectionGoal::None,
10089                        reversed: selection.reversed,
10090                    });
10091                }
10092            }
10093            None
10094        }
10095
10096        let mut selected_larger_symbol = false;
10097        let new_selections = old_selections
10098            .iter()
10099            .map(|selection| match update_selection(selection, &buffer) {
10100                Some(new_selection) => {
10101                    if new_selection.range() != selection.range() {
10102                        selected_larger_symbol = true;
10103                    }
10104                    new_selection
10105                }
10106                None => selection.clone(),
10107            })
10108            .collect::<Vec<_>>();
10109
10110        if selected_larger_symbol {
10111            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10112                s.select(new_selections);
10113            });
10114        }
10115    }
10116
10117    pub fn select_larger_syntax_node(
10118        &mut self,
10119        _: &SelectLargerSyntaxNode,
10120        window: &mut Window,
10121        cx: &mut Context<Self>,
10122    ) {
10123        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10124        let buffer = self.buffer.read(cx).snapshot(cx);
10125        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10126
10127        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10128        let mut selected_larger_node = false;
10129        let new_selections = old_selections
10130            .iter()
10131            .map(|selection| {
10132                let old_range = selection.start..selection.end;
10133                let mut new_range = old_range.clone();
10134                let mut new_node = None;
10135                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10136                {
10137                    new_node = Some(node);
10138                    new_range = containing_range;
10139                    if !display_map.intersects_fold(new_range.start)
10140                        && !display_map.intersects_fold(new_range.end)
10141                    {
10142                        break;
10143                    }
10144                }
10145
10146                if let Some(node) = new_node {
10147                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10148                    // nodes. Parent and grandparent are also logged because this operation will not
10149                    // visit nodes that have the same range as their parent.
10150                    log::info!("Node: {node:?}");
10151                    let parent = node.parent();
10152                    log::info!("Parent: {parent:?}");
10153                    let grandparent = parent.and_then(|x| x.parent());
10154                    log::info!("Grandparent: {grandparent:?}");
10155                }
10156
10157                selected_larger_node |= new_range != old_range;
10158                Selection {
10159                    id: selection.id,
10160                    start: new_range.start,
10161                    end: new_range.end,
10162                    goal: SelectionGoal::None,
10163                    reversed: selection.reversed,
10164                }
10165            })
10166            .collect::<Vec<_>>();
10167
10168        if selected_larger_node {
10169            stack.push(old_selections);
10170            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10171                s.select(new_selections);
10172            });
10173        }
10174        self.select_larger_syntax_node_stack = stack;
10175    }
10176
10177    pub fn select_smaller_syntax_node(
10178        &mut self,
10179        _: &SelectSmallerSyntaxNode,
10180        window: &mut Window,
10181        cx: &mut Context<Self>,
10182    ) {
10183        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10184        if let Some(selections) = stack.pop() {
10185            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10186                s.select(selections.to_vec());
10187            });
10188        }
10189        self.select_larger_syntax_node_stack = stack;
10190    }
10191
10192    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10193        if !EditorSettings::get_global(cx).gutter.runnables {
10194            self.clear_tasks();
10195            return Task::ready(());
10196        }
10197        let project = self.project.as_ref().map(Entity::downgrade);
10198        cx.spawn_in(window, |this, mut cx| async move {
10199            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10200            let Some(project) = project.and_then(|p| p.upgrade()) else {
10201                return;
10202            };
10203            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10204                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10205            }) else {
10206                return;
10207            };
10208
10209            let hide_runnables = project
10210                .update(&mut cx, |project, cx| {
10211                    // Do not display any test indicators in non-dev server remote projects.
10212                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10213                })
10214                .unwrap_or(true);
10215            if hide_runnables {
10216                return;
10217            }
10218            let new_rows =
10219                cx.background_spawn({
10220                    let snapshot = display_snapshot.clone();
10221                    async move {
10222                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10223                    }
10224                })
10225                    .await;
10226
10227            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10228            this.update(&mut cx, |this, _| {
10229                this.clear_tasks();
10230                for (key, value) in rows {
10231                    this.insert_tasks(key, value);
10232                }
10233            })
10234            .ok();
10235        })
10236    }
10237    fn fetch_runnable_ranges(
10238        snapshot: &DisplaySnapshot,
10239        range: Range<Anchor>,
10240    ) -> Vec<language::RunnableRange> {
10241        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10242    }
10243
10244    fn runnable_rows(
10245        project: Entity<Project>,
10246        snapshot: DisplaySnapshot,
10247        runnable_ranges: Vec<RunnableRange>,
10248        mut cx: AsyncWindowContext,
10249    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10250        runnable_ranges
10251            .into_iter()
10252            .filter_map(|mut runnable| {
10253                let tasks = cx
10254                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10255                    .ok()?;
10256                if tasks.is_empty() {
10257                    return None;
10258                }
10259
10260                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10261
10262                let row = snapshot
10263                    .buffer_snapshot
10264                    .buffer_line_for_row(MultiBufferRow(point.row))?
10265                    .1
10266                    .start
10267                    .row;
10268
10269                let context_range =
10270                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10271                Some((
10272                    (runnable.buffer_id, row),
10273                    RunnableTasks {
10274                        templates: tasks,
10275                        offset: MultiBufferOffset(runnable.run_range.start),
10276                        context_range,
10277                        column: point.column,
10278                        extra_variables: runnable.extra_captures,
10279                    },
10280                ))
10281            })
10282            .collect()
10283    }
10284
10285    fn templates_with_tags(
10286        project: &Entity<Project>,
10287        runnable: &mut Runnable,
10288        cx: &mut App,
10289    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10290        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10291            let (worktree_id, file) = project
10292                .buffer_for_id(runnable.buffer, cx)
10293                .and_then(|buffer| buffer.read(cx).file())
10294                .map(|file| (file.worktree_id(cx), file.clone()))
10295                .unzip();
10296
10297            (
10298                project.task_store().read(cx).task_inventory().cloned(),
10299                worktree_id,
10300                file,
10301            )
10302        });
10303
10304        let tags = mem::take(&mut runnable.tags);
10305        let mut tags: Vec<_> = tags
10306            .into_iter()
10307            .flat_map(|tag| {
10308                let tag = tag.0.clone();
10309                inventory
10310                    .as_ref()
10311                    .into_iter()
10312                    .flat_map(|inventory| {
10313                        inventory.read(cx).list_tasks(
10314                            file.clone(),
10315                            Some(runnable.language.clone()),
10316                            worktree_id,
10317                            cx,
10318                        )
10319                    })
10320                    .filter(move |(_, template)| {
10321                        template.tags.iter().any(|source_tag| source_tag == &tag)
10322                    })
10323            })
10324            .sorted_by_key(|(kind, _)| kind.to_owned())
10325            .collect();
10326        if let Some((leading_tag_source, _)) = tags.first() {
10327            // Strongest source wins; if we have worktree tag binding, prefer that to
10328            // global and language bindings;
10329            // if we have a global binding, prefer that to language binding.
10330            let first_mismatch = tags
10331                .iter()
10332                .position(|(tag_source, _)| tag_source != leading_tag_source);
10333            if let Some(index) = first_mismatch {
10334                tags.truncate(index);
10335            }
10336        }
10337
10338        tags
10339    }
10340
10341    pub fn move_to_enclosing_bracket(
10342        &mut self,
10343        _: &MoveToEnclosingBracket,
10344        window: &mut Window,
10345        cx: &mut Context<Self>,
10346    ) {
10347        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10348            s.move_offsets_with(|snapshot, selection| {
10349                let Some(enclosing_bracket_ranges) =
10350                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10351                else {
10352                    return;
10353                };
10354
10355                let mut best_length = usize::MAX;
10356                let mut best_inside = false;
10357                let mut best_in_bracket_range = false;
10358                let mut best_destination = None;
10359                for (open, close) in enclosing_bracket_ranges {
10360                    let close = close.to_inclusive();
10361                    let length = close.end() - open.start;
10362                    let inside = selection.start >= open.end && selection.end <= *close.start();
10363                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10364                        || close.contains(&selection.head());
10365
10366                    // If best is next to a bracket and current isn't, skip
10367                    if !in_bracket_range && best_in_bracket_range {
10368                        continue;
10369                    }
10370
10371                    // Prefer smaller lengths unless best is inside and current isn't
10372                    if length > best_length && (best_inside || !inside) {
10373                        continue;
10374                    }
10375
10376                    best_length = length;
10377                    best_inside = inside;
10378                    best_in_bracket_range = in_bracket_range;
10379                    best_destination = Some(
10380                        if close.contains(&selection.start) && close.contains(&selection.end) {
10381                            if inside {
10382                                open.end
10383                            } else {
10384                                open.start
10385                            }
10386                        } else if inside {
10387                            *close.start()
10388                        } else {
10389                            *close.end()
10390                        },
10391                    );
10392                }
10393
10394                if let Some(destination) = best_destination {
10395                    selection.collapse_to(destination, SelectionGoal::None);
10396                }
10397            })
10398        });
10399    }
10400
10401    pub fn undo_selection(
10402        &mut self,
10403        _: &UndoSelection,
10404        window: &mut Window,
10405        cx: &mut Context<Self>,
10406    ) {
10407        self.end_selection(window, cx);
10408        self.selection_history.mode = SelectionHistoryMode::Undoing;
10409        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10410            self.change_selections(None, window, cx, |s| {
10411                s.select_anchors(entry.selections.to_vec())
10412            });
10413            self.select_next_state = entry.select_next_state;
10414            self.select_prev_state = entry.select_prev_state;
10415            self.add_selections_state = entry.add_selections_state;
10416            self.request_autoscroll(Autoscroll::newest(), cx);
10417        }
10418        self.selection_history.mode = SelectionHistoryMode::Normal;
10419    }
10420
10421    pub fn redo_selection(
10422        &mut self,
10423        _: &RedoSelection,
10424        window: &mut Window,
10425        cx: &mut Context<Self>,
10426    ) {
10427        self.end_selection(window, cx);
10428        self.selection_history.mode = SelectionHistoryMode::Redoing;
10429        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10430            self.change_selections(None, window, cx, |s| {
10431                s.select_anchors(entry.selections.to_vec())
10432            });
10433            self.select_next_state = entry.select_next_state;
10434            self.select_prev_state = entry.select_prev_state;
10435            self.add_selections_state = entry.add_selections_state;
10436            self.request_autoscroll(Autoscroll::newest(), cx);
10437        }
10438        self.selection_history.mode = SelectionHistoryMode::Normal;
10439    }
10440
10441    pub fn expand_excerpts(
10442        &mut self,
10443        action: &ExpandExcerpts,
10444        _: &mut Window,
10445        cx: &mut Context<Self>,
10446    ) {
10447        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10448    }
10449
10450    pub fn expand_excerpts_down(
10451        &mut self,
10452        action: &ExpandExcerptsDown,
10453        _: &mut Window,
10454        cx: &mut Context<Self>,
10455    ) {
10456        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10457    }
10458
10459    pub fn expand_excerpts_up(
10460        &mut self,
10461        action: &ExpandExcerptsUp,
10462        _: &mut Window,
10463        cx: &mut Context<Self>,
10464    ) {
10465        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10466    }
10467
10468    pub fn expand_excerpts_for_direction(
10469        &mut self,
10470        lines: u32,
10471        direction: ExpandExcerptDirection,
10472
10473        cx: &mut Context<Self>,
10474    ) {
10475        let selections = self.selections.disjoint_anchors();
10476
10477        let lines = if lines == 0 {
10478            EditorSettings::get_global(cx).expand_excerpt_lines
10479        } else {
10480            lines
10481        };
10482
10483        self.buffer.update(cx, |buffer, cx| {
10484            let snapshot = buffer.snapshot(cx);
10485            let mut excerpt_ids = selections
10486                .iter()
10487                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10488                .collect::<Vec<_>>();
10489            excerpt_ids.sort();
10490            excerpt_ids.dedup();
10491            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10492        })
10493    }
10494
10495    pub fn expand_excerpt(
10496        &mut self,
10497        excerpt: ExcerptId,
10498        direction: ExpandExcerptDirection,
10499        cx: &mut Context<Self>,
10500    ) {
10501        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10502        self.buffer.update(cx, |buffer, cx| {
10503            buffer.expand_excerpts([excerpt], lines, direction, cx)
10504        })
10505    }
10506
10507    pub fn go_to_singleton_buffer_point(
10508        &mut self,
10509        point: Point,
10510        window: &mut Window,
10511        cx: &mut Context<Self>,
10512    ) {
10513        self.go_to_singleton_buffer_range(point..point, window, cx);
10514    }
10515
10516    pub fn go_to_singleton_buffer_range(
10517        &mut self,
10518        range: Range<Point>,
10519        window: &mut Window,
10520        cx: &mut Context<Self>,
10521    ) {
10522        let multibuffer = self.buffer().read(cx);
10523        let Some(buffer) = multibuffer.as_singleton() else {
10524            return;
10525        };
10526        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10527            return;
10528        };
10529        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10530            return;
10531        };
10532        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10533            s.select_anchor_ranges([start..end])
10534        });
10535    }
10536
10537    fn go_to_diagnostic(
10538        &mut self,
10539        _: &GoToDiagnostic,
10540        window: &mut Window,
10541        cx: &mut Context<Self>,
10542    ) {
10543        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10544    }
10545
10546    fn go_to_prev_diagnostic(
10547        &mut self,
10548        _: &GoToPrevDiagnostic,
10549        window: &mut Window,
10550        cx: &mut Context<Self>,
10551    ) {
10552        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10553    }
10554
10555    pub fn go_to_diagnostic_impl(
10556        &mut self,
10557        direction: Direction,
10558        window: &mut Window,
10559        cx: &mut Context<Self>,
10560    ) {
10561        let buffer = self.buffer.read(cx).snapshot(cx);
10562        let selection = self.selections.newest::<usize>(cx);
10563
10564        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10565        if direction == Direction::Next {
10566            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10567                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10568                    return;
10569                };
10570                self.activate_diagnostics(
10571                    buffer_id,
10572                    popover.local_diagnostic.diagnostic.group_id,
10573                    window,
10574                    cx,
10575                );
10576                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10577                    let primary_range_start = active_diagnostics.primary_range.start;
10578                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10579                        let mut new_selection = s.newest_anchor().clone();
10580                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10581                        s.select_anchors(vec![new_selection.clone()]);
10582                    });
10583                    self.refresh_inline_completion(false, true, window, cx);
10584                }
10585                return;
10586            }
10587        }
10588
10589        let active_group_id = self
10590            .active_diagnostics
10591            .as_ref()
10592            .map(|active_group| active_group.group_id);
10593        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10594            active_diagnostics
10595                .primary_range
10596                .to_offset(&buffer)
10597                .to_inclusive()
10598        });
10599        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10600            if active_primary_range.contains(&selection.head()) {
10601                *active_primary_range.start()
10602            } else {
10603                selection.head()
10604            }
10605        } else {
10606            selection.head()
10607        };
10608
10609        let snapshot = self.snapshot(window, cx);
10610        let primary_diagnostics_before = buffer
10611            .diagnostics_in_range::<usize>(0..search_start)
10612            .filter(|entry| entry.diagnostic.is_primary)
10613            .filter(|entry| entry.range.start != entry.range.end)
10614            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10615            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10616            .collect::<Vec<_>>();
10617        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10618            primary_diagnostics_before
10619                .iter()
10620                .position(|entry| entry.diagnostic.group_id == active_group_id)
10621        });
10622
10623        let primary_diagnostics_after = buffer
10624            .diagnostics_in_range::<usize>(search_start..buffer.len())
10625            .filter(|entry| entry.diagnostic.is_primary)
10626            .filter(|entry| entry.range.start != entry.range.end)
10627            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10628            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10629            .collect::<Vec<_>>();
10630        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10631            primary_diagnostics_after
10632                .iter()
10633                .enumerate()
10634                .rev()
10635                .find_map(|(i, entry)| {
10636                    if entry.diagnostic.group_id == active_group_id {
10637                        Some(i)
10638                    } else {
10639                        None
10640                    }
10641                })
10642        });
10643
10644        let next_primary_diagnostic = match direction {
10645            Direction::Prev => primary_diagnostics_before
10646                .iter()
10647                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10648                .rev()
10649                .next(),
10650            Direction::Next => primary_diagnostics_after
10651                .iter()
10652                .skip(
10653                    last_same_group_diagnostic_after
10654                        .map(|index| index + 1)
10655                        .unwrap_or(0),
10656                )
10657                .next(),
10658        };
10659
10660        // Cycle around to the start of the buffer, potentially moving back to the start of
10661        // the currently active diagnostic.
10662        let cycle_around = || match direction {
10663            Direction::Prev => primary_diagnostics_after
10664                .iter()
10665                .rev()
10666                .chain(primary_diagnostics_before.iter().rev())
10667                .next(),
10668            Direction::Next => primary_diagnostics_before
10669                .iter()
10670                .chain(primary_diagnostics_after.iter())
10671                .next(),
10672        };
10673
10674        if let Some((primary_range, group_id)) = next_primary_diagnostic
10675            .or_else(cycle_around)
10676            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10677        {
10678            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10679                return;
10680            };
10681            self.activate_diagnostics(buffer_id, group_id, window, cx);
10682            if self.active_diagnostics.is_some() {
10683                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10684                    s.select(vec![Selection {
10685                        id: selection.id,
10686                        start: primary_range.start,
10687                        end: primary_range.start,
10688                        reversed: false,
10689                        goal: SelectionGoal::None,
10690                    }]);
10691                });
10692                self.refresh_inline_completion(false, true, window, cx);
10693            }
10694        }
10695    }
10696
10697    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10698        let snapshot = self.snapshot(window, cx);
10699        let selection = self.selections.newest::<Point>(cx);
10700        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10701    }
10702
10703    fn go_to_hunk_after_position(
10704        &mut self,
10705        snapshot: &EditorSnapshot,
10706        position: Point,
10707        window: &mut Window,
10708        cx: &mut Context<Editor>,
10709    ) -> Option<MultiBufferDiffHunk> {
10710        let mut hunk = snapshot
10711            .buffer_snapshot
10712            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10713            .find(|hunk| hunk.row_range.start.0 > position.row);
10714        if hunk.is_none() {
10715            hunk = snapshot
10716                .buffer_snapshot
10717                .diff_hunks_in_range(Point::zero()..position)
10718                .find(|hunk| hunk.row_range.end.0 < position.row)
10719        }
10720        if let Some(hunk) = &hunk {
10721            let destination = Point::new(hunk.row_range.start.0, 0);
10722            self.unfold_ranges(&[destination..destination], false, false, cx);
10723            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10724                s.select_ranges(vec![destination..destination]);
10725            });
10726        }
10727
10728        hunk
10729    }
10730
10731    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10732        let snapshot = self.snapshot(window, cx);
10733        let selection = self.selections.newest::<Point>(cx);
10734        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10735    }
10736
10737    fn go_to_hunk_before_position(
10738        &mut self,
10739        snapshot: &EditorSnapshot,
10740        position: Point,
10741        window: &mut Window,
10742        cx: &mut Context<Editor>,
10743    ) -> Option<MultiBufferDiffHunk> {
10744        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10745        if hunk.is_none() {
10746            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10747        }
10748        if let Some(hunk) = &hunk {
10749            let destination = Point::new(hunk.row_range.start.0, 0);
10750            self.unfold_ranges(&[destination..destination], false, false, cx);
10751            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10752                s.select_ranges(vec![destination..destination]);
10753            });
10754        }
10755
10756        hunk
10757    }
10758
10759    pub fn go_to_definition(
10760        &mut self,
10761        _: &GoToDefinition,
10762        window: &mut Window,
10763        cx: &mut Context<Self>,
10764    ) -> Task<Result<Navigated>> {
10765        let definition =
10766            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10767        cx.spawn_in(window, |editor, mut cx| async move {
10768            if definition.await? == Navigated::Yes {
10769                return Ok(Navigated::Yes);
10770            }
10771            match editor.update_in(&mut cx, |editor, window, cx| {
10772                editor.find_all_references(&FindAllReferences, window, cx)
10773            })? {
10774                Some(references) => references.await,
10775                None => Ok(Navigated::No),
10776            }
10777        })
10778    }
10779
10780    pub fn go_to_declaration(
10781        &mut self,
10782        _: &GoToDeclaration,
10783        window: &mut Window,
10784        cx: &mut Context<Self>,
10785    ) -> Task<Result<Navigated>> {
10786        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10787    }
10788
10789    pub fn go_to_declaration_split(
10790        &mut self,
10791        _: &GoToDeclaration,
10792        window: &mut Window,
10793        cx: &mut Context<Self>,
10794    ) -> Task<Result<Navigated>> {
10795        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10796    }
10797
10798    pub fn go_to_implementation(
10799        &mut self,
10800        _: &GoToImplementation,
10801        window: &mut Window,
10802        cx: &mut Context<Self>,
10803    ) -> Task<Result<Navigated>> {
10804        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10805    }
10806
10807    pub fn go_to_implementation_split(
10808        &mut self,
10809        _: &GoToImplementationSplit,
10810        window: &mut Window,
10811        cx: &mut Context<Self>,
10812    ) -> Task<Result<Navigated>> {
10813        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10814    }
10815
10816    pub fn go_to_type_definition(
10817        &mut self,
10818        _: &GoToTypeDefinition,
10819        window: &mut Window,
10820        cx: &mut Context<Self>,
10821    ) -> Task<Result<Navigated>> {
10822        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10823    }
10824
10825    pub fn go_to_definition_split(
10826        &mut self,
10827        _: &GoToDefinitionSplit,
10828        window: &mut Window,
10829        cx: &mut Context<Self>,
10830    ) -> Task<Result<Navigated>> {
10831        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10832    }
10833
10834    pub fn go_to_type_definition_split(
10835        &mut self,
10836        _: &GoToTypeDefinitionSplit,
10837        window: &mut Window,
10838        cx: &mut Context<Self>,
10839    ) -> Task<Result<Navigated>> {
10840        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10841    }
10842
10843    fn go_to_definition_of_kind(
10844        &mut self,
10845        kind: GotoDefinitionKind,
10846        split: bool,
10847        window: &mut Window,
10848        cx: &mut Context<Self>,
10849    ) -> Task<Result<Navigated>> {
10850        let Some(provider) = self.semantics_provider.clone() else {
10851            return Task::ready(Ok(Navigated::No));
10852        };
10853        let head = self.selections.newest::<usize>(cx).head();
10854        let buffer = self.buffer.read(cx);
10855        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10856            text_anchor
10857        } else {
10858            return Task::ready(Ok(Navigated::No));
10859        };
10860
10861        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10862            return Task::ready(Ok(Navigated::No));
10863        };
10864
10865        cx.spawn_in(window, |editor, mut cx| async move {
10866            let definitions = definitions.await?;
10867            let navigated = editor
10868                .update_in(&mut cx, |editor, window, cx| {
10869                    editor.navigate_to_hover_links(
10870                        Some(kind),
10871                        definitions
10872                            .into_iter()
10873                            .filter(|location| {
10874                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10875                            })
10876                            .map(HoverLink::Text)
10877                            .collect::<Vec<_>>(),
10878                        split,
10879                        window,
10880                        cx,
10881                    )
10882                })?
10883                .await?;
10884            anyhow::Ok(navigated)
10885        })
10886    }
10887
10888    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10889        let selection = self.selections.newest_anchor();
10890        let head = selection.head();
10891        let tail = selection.tail();
10892
10893        let Some((buffer, start_position)) =
10894            self.buffer.read(cx).text_anchor_for_position(head, cx)
10895        else {
10896            return;
10897        };
10898
10899        let end_position = if head != tail {
10900            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10901                return;
10902            };
10903            Some(pos)
10904        } else {
10905            None
10906        };
10907
10908        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10909            let url = if let Some(end_pos) = end_position {
10910                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10911            } else {
10912                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10913            };
10914
10915            if let Some(url) = url {
10916                editor.update(&mut cx, |_, cx| {
10917                    cx.open_url(&url);
10918                })
10919            } else {
10920                Ok(())
10921            }
10922        });
10923
10924        url_finder.detach();
10925    }
10926
10927    pub fn open_selected_filename(
10928        &mut self,
10929        _: &OpenSelectedFilename,
10930        window: &mut Window,
10931        cx: &mut Context<Self>,
10932    ) {
10933        let Some(workspace) = self.workspace() else {
10934            return;
10935        };
10936
10937        let position = self.selections.newest_anchor().head();
10938
10939        let Some((buffer, buffer_position)) =
10940            self.buffer.read(cx).text_anchor_for_position(position, cx)
10941        else {
10942            return;
10943        };
10944
10945        let project = self.project.clone();
10946
10947        cx.spawn_in(window, |_, mut cx| async move {
10948            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10949
10950            if let Some((_, path)) = result {
10951                workspace
10952                    .update_in(&mut cx, |workspace, window, cx| {
10953                        workspace.open_resolved_path(path, window, cx)
10954                    })?
10955                    .await?;
10956            }
10957            anyhow::Ok(())
10958        })
10959        .detach();
10960    }
10961
10962    pub(crate) fn navigate_to_hover_links(
10963        &mut self,
10964        kind: Option<GotoDefinitionKind>,
10965        mut definitions: Vec<HoverLink>,
10966        split: bool,
10967        window: &mut Window,
10968        cx: &mut Context<Editor>,
10969    ) -> Task<Result<Navigated>> {
10970        // If there is one definition, just open it directly
10971        if definitions.len() == 1 {
10972            let definition = definitions.pop().unwrap();
10973
10974            enum TargetTaskResult {
10975                Location(Option<Location>),
10976                AlreadyNavigated,
10977            }
10978
10979            let target_task = match definition {
10980                HoverLink::Text(link) => {
10981                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10982                }
10983                HoverLink::InlayHint(lsp_location, server_id) => {
10984                    let computation =
10985                        self.compute_target_location(lsp_location, server_id, window, cx);
10986                    cx.background_spawn(async move {
10987                        let location = computation.await?;
10988                        Ok(TargetTaskResult::Location(location))
10989                    })
10990                }
10991                HoverLink::Url(url) => {
10992                    cx.open_url(&url);
10993                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10994                }
10995                HoverLink::File(path) => {
10996                    if let Some(workspace) = self.workspace() {
10997                        cx.spawn_in(window, |_, mut cx| async move {
10998                            workspace
10999                                .update_in(&mut cx, |workspace, window, cx| {
11000                                    workspace.open_resolved_path(path, window, cx)
11001                                })?
11002                                .await
11003                                .map(|_| TargetTaskResult::AlreadyNavigated)
11004                        })
11005                    } else {
11006                        Task::ready(Ok(TargetTaskResult::Location(None)))
11007                    }
11008                }
11009            };
11010            cx.spawn_in(window, |editor, mut cx| async move {
11011                let target = match target_task.await.context("target resolution task")? {
11012                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11013                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11014                    TargetTaskResult::Location(Some(target)) => target,
11015                };
11016
11017                editor.update_in(&mut cx, |editor, window, cx| {
11018                    let Some(workspace) = editor.workspace() else {
11019                        return Navigated::No;
11020                    };
11021                    let pane = workspace.read(cx).active_pane().clone();
11022
11023                    let range = target.range.to_point(target.buffer.read(cx));
11024                    let range = editor.range_for_match(&range);
11025                    let range = collapse_multiline_range(range);
11026
11027                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11028                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11029                    } else {
11030                        window.defer(cx, move |window, cx| {
11031                            let target_editor: Entity<Self> =
11032                                workspace.update(cx, |workspace, cx| {
11033                                    let pane = if split {
11034                                        workspace.adjacent_pane(window, cx)
11035                                    } else {
11036                                        workspace.active_pane().clone()
11037                                    };
11038
11039                                    workspace.open_project_item(
11040                                        pane,
11041                                        target.buffer.clone(),
11042                                        true,
11043                                        true,
11044                                        window,
11045                                        cx,
11046                                    )
11047                                });
11048                            target_editor.update(cx, |target_editor, cx| {
11049                                // When selecting a definition in a different buffer, disable the nav history
11050                                // to avoid creating a history entry at the previous cursor location.
11051                                pane.update(cx, |pane, _| pane.disable_history());
11052                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11053                                pane.update(cx, |pane, _| pane.enable_history());
11054                            });
11055                        });
11056                    }
11057                    Navigated::Yes
11058                })
11059            })
11060        } else if !definitions.is_empty() {
11061            cx.spawn_in(window, |editor, mut cx| async move {
11062                let (title, location_tasks, workspace) = editor
11063                    .update_in(&mut cx, |editor, window, cx| {
11064                        let tab_kind = match kind {
11065                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11066                            _ => "Definitions",
11067                        };
11068                        let title = definitions
11069                            .iter()
11070                            .find_map(|definition| match definition {
11071                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11072                                    let buffer = origin.buffer.read(cx);
11073                                    format!(
11074                                        "{} for {}",
11075                                        tab_kind,
11076                                        buffer
11077                                            .text_for_range(origin.range.clone())
11078                                            .collect::<String>()
11079                                    )
11080                                }),
11081                                HoverLink::InlayHint(_, _) => None,
11082                                HoverLink::Url(_) => None,
11083                                HoverLink::File(_) => None,
11084                            })
11085                            .unwrap_or(tab_kind.to_string());
11086                        let location_tasks = definitions
11087                            .into_iter()
11088                            .map(|definition| match definition {
11089                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11090                                HoverLink::InlayHint(lsp_location, server_id) => editor
11091                                    .compute_target_location(lsp_location, server_id, window, cx),
11092                                HoverLink::Url(_) => Task::ready(Ok(None)),
11093                                HoverLink::File(_) => Task::ready(Ok(None)),
11094                            })
11095                            .collect::<Vec<_>>();
11096                        (title, location_tasks, editor.workspace().clone())
11097                    })
11098                    .context("location tasks preparation")?;
11099
11100                let locations = future::join_all(location_tasks)
11101                    .await
11102                    .into_iter()
11103                    .filter_map(|location| location.transpose())
11104                    .collect::<Result<_>>()
11105                    .context("location tasks")?;
11106
11107                let Some(workspace) = workspace else {
11108                    return Ok(Navigated::No);
11109                };
11110                let opened = workspace
11111                    .update_in(&mut cx, |workspace, window, cx| {
11112                        Self::open_locations_in_multibuffer(
11113                            workspace,
11114                            locations,
11115                            title,
11116                            split,
11117                            MultibufferSelectionMode::First,
11118                            window,
11119                            cx,
11120                        )
11121                    })
11122                    .ok();
11123
11124                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11125            })
11126        } else {
11127            Task::ready(Ok(Navigated::No))
11128        }
11129    }
11130
11131    fn compute_target_location(
11132        &self,
11133        lsp_location: lsp::Location,
11134        server_id: LanguageServerId,
11135        window: &mut Window,
11136        cx: &mut Context<Self>,
11137    ) -> Task<anyhow::Result<Option<Location>>> {
11138        let Some(project) = self.project.clone() else {
11139            return Task::ready(Ok(None));
11140        };
11141
11142        cx.spawn_in(window, move |editor, mut cx| async move {
11143            let location_task = editor.update(&mut cx, |_, cx| {
11144                project.update(cx, |project, cx| {
11145                    let language_server_name = project
11146                        .language_server_statuses(cx)
11147                        .find(|(id, _)| server_id == *id)
11148                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11149                    language_server_name.map(|language_server_name| {
11150                        project.open_local_buffer_via_lsp(
11151                            lsp_location.uri.clone(),
11152                            server_id,
11153                            language_server_name,
11154                            cx,
11155                        )
11156                    })
11157                })
11158            })?;
11159            let location = match location_task {
11160                Some(task) => Some({
11161                    let target_buffer_handle = task.await.context("open local buffer")?;
11162                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11163                        let target_start = target_buffer
11164                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11165                        let target_end = target_buffer
11166                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11167                        target_buffer.anchor_after(target_start)
11168                            ..target_buffer.anchor_before(target_end)
11169                    })?;
11170                    Location {
11171                        buffer: target_buffer_handle,
11172                        range,
11173                    }
11174                }),
11175                None => None,
11176            };
11177            Ok(location)
11178        })
11179    }
11180
11181    pub fn find_all_references(
11182        &mut self,
11183        _: &FindAllReferences,
11184        window: &mut Window,
11185        cx: &mut Context<Self>,
11186    ) -> Option<Task<Result<Navigated>>> {
11187        let selection = self.selections.newest::<usize>(cx);
11188        let multi_buffer = self.buffer.read(cx);
11189        let head = selection.head();
11190
11191        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11192        let head_anchor = multi_buffer_snapshot.anchor_at(
11193            head,
11194            if head < selection.tail() {
11195                Bias::Right
11196            } else {
11197                Bias::Left
11198            },
11199        );
11200
11201        match self
11202            .find_all_references_task_sources
11203            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11204        {
11205            Ok(_) => {
11206                log::info!(
11207                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11208                );
11209                return None;
11210            }
11211            Err(i) => {
11212                self.find_all_references_task_sources.insert(i, head_anchor);
11213            }
11214        }
11215
11216        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11217        let workspace = self.workspace()?;
11218        let project = workspace.read(cx).project().clone();
11219        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11220        Some(cx.spawn_in(window, |editor, mut cx| async move {
11221            let _cleanup = defer({
11222                let mut cx = cx.clone();
11223                move || {
11224                    let _ = editor.update(&mut cx, |editor, _| {
11225                        if let Ok(i) =
11226                            editor
11227                                .find_all_references_task_sources
11228                                .binary_search_by(|anchor| {
11229                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11230                                })
11231                        {
11232                            editor.find_all_references_task_sources.remove(i);
11233                        }
11234                    });
11235                }
11236            });
11237
11238            let locations = references.await?;
11239            if locations.is_empty() {
11240                return anyhow::Ok(Navigated::No);
11241            }
11242
11243            workspace.update_in(&mut cx, |workspace, window, cx| {
11244                let title = locations
11245                    .first()
11246                    .as_ref()
11247                    .map(|location| {
11248                        let buffer = location.buffer.read(cx);
11249                        format!(
11250                            "References to `{}`",
11251                            buffer
11252                                .text_for_range(location.range.clone())
11253                                .collect::<String>()
11254                        )
11255                    })
11256                    .unwrap();
11257                Self::open_locations_in_multibuffer(
11258                    workspace,
11259                    locations,
11260                    title,
11261                    false,
11262                    MultibufferSelectionMode::First,
11263                    window,
11264                    cx,
11265                );
11266                Navigated::Yes
11267            })
11268        }))
11269    }
11270
11271    /// Opens a multibuffer with the given project locations in it
11272    pub fn open_locations_in_multibuffer(
11273        workspace: &mut Workspace,
11274        mut locations: Vec<Location>,
11275        title: String,
11276        split: bool,
11277        multibuffer_selection_mode: MultibufferSelectionMode,
11278        window: &mut Window,
11279        cx: &mut Context<Workspace>,
11280    ) {
11281        // If there are multiple definitions, open them in a multibuffer
11282        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11283        let mut locations = locations.into_iter().peekable();
11284        let mut ranges = Vec::new();
11285        let capability = workspace.project().read(cx).capability();
11286
11287        let excerpt_buffer = cx.new(|cx| {
11288            let mut multibuffer = MultiBuffer::new(capability);
11289            while let Some(location) = locations.next() {
11290                let buffer = location.buffer.read(cx);
11291                let mut ranges_for_buffer = Vec::new();
11292                let range = location.range.to_offset(buffer);
11293                ranges_for_buffer.push(range.clone());
11294
11295                while let Some(next_location) = locations.peek() {
11296                    if next_location.buffer == location.buffer {
11297                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11298                        locations.next();
11299                    } else {
11300                        break;
11301                    }
11302                }
11303
11304                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11305                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11306                    location.buffer.clone(),
11307                    ranges_for_buffer,
11308                    DEFAULT_MULTIBUFFER_CONTEXT,
11309                    cx,
11310                ))
11311            }
11312
11313            multibuffer.with_title(title)
11314        });
11315
11316        let editor = cx.new(|cx| {
11317            Editor::for_multibuffer(
11318                excerpt_buffer,
11319                Some(workspace.project().clone()),
11320                true,
11321                window,
11322                cx,
11323            )
11324        });
11325        editor.update(cx, |editor, cx| {
11326            match multibuffer_selection_mode {
11327                MultibufferSelectionMode::First => {
11328                    if let Some(first_range) = ranges.first() {
11329                        editor.change_selections(None, window, cx, |selections| {
11330                            selections.clear_disjoint();
11331                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11332                        });
11333                    }
11334                    editor.highlight_background::<Self>(
11335                        &ranges,
11336                        |theme| theme.editor_highlighted_line_background,
11337                        cx,
11338                    );
11339                }
11340                MultibufferSelectionMode::All => {
11341                    editor.change_selections(None, window, cx, |selections| {
11342                        selections.clear_disjoint();
11343                        selections.select_anchor_ranges(ranges);
11344                    });
11345                }
11346            }
11347            editor.register_buffers_with_language_servers(cx);
11348        });
11349
11350        let item = Box::new(editor);
11351        let item_id = item.item_id();
11352
11353        if split {
11354            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11355        } else {
11356            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11357                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11358                    pane.close_current_preview_item(window, cx)
11359                } else {
11360                    None
11361                }
11362            });
11363            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11364        }
11365        workspace.active_pane().update(cx, |pane, cx| {
11366            pane.set_preview_item_id(Some(item_id), cx);
11367        });
11368    }
11369
11370    pub fn rename(
11371        &mut self,
11372        _: &Rename,
11373        window: &mut Window,
11374        cx: &mut Context<Self>,
11375    ) -> Option<Task<Result<()>>> {
11376        use language::ToOffset as _;
11377
11378        let provider = self.semantics_provider.clone()?;
11379        let selection = self.selections.newest_anchor().clone();
11380        let (cursor_buffer, cursor_buffer_position) = self
11381            .buffer
11382            .read(cx)
11383            .text_anchor_for_position(selection.head(), cx)?;
11384        let (tail_buffer, cursor_buffer_position_end) = self
11385            .buffer
11386            .read(cx)
11387            .text_anchor_for_position(selection.tail(), cx)?;
11388        if tail_buffer != cursor_buffer {
11389            return None;
11390        }
11391
11392        let snapshot = cursor_buffer.read(cx).snapshot();
11393        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11394        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11395        let prepare_rename = provider
11396            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11397            .unwrap_or_else(|| Task::ready(Ok(None)));
11398        drop(snapshot);
11399
11400        Some(cx.spawn_in(window, |this, mut cx| async move {
11401            let rename_range = if let Some(range) = prepare_rename.await? {
11402                Some(range)
11403            } else {
11404                this.update(&mut cx, |this, cx| {
11405                    let buffer = this.buffer.read(cx).snapshot(cx);
11406                    let mut buffer_highlights = this
11407                        .document_highlights_for_position(selection.head(), &buffer)
11408                        .filter(|highlight| {
11409                            highlight.start.excerpt_id == selection.head().excerpt_id
11410                                && highlight.end.excerpt_id == selection.head().excerpt_id
11411                        });
11412                    buffer_highlights
11413                        .next()
11414                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11415                })?
11416            };
11417            if let Some(rename_range) = rename_range {
11418                this.update_in(&mut cx, |this, window, cx| {
11419                    let snapshot = cursor_buffer.read(cx).snapshot();
11420                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11421                    let cursor_offset_in_rename_range =
11422                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11423                    let cursor_offset_in_rename_range_end =
11424                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11425
11426                    this.take_rename(false, window, cx);
11427                    let buffer = this.buffer.read(cx).read(cx);
11428                    let cursor_offset = selection.head().to_offset(&buffer);
11429                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11430                    let rename_end = rename_start + rename_buffer_range.len();
11431                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11432                    let mut old_highlight_id = None;
11433                    let old_name: Arc<str> = buffer
11434                        .chunks(rename_start..rename_end, true)
11435                        .map(|chunk| {
11436                            if old_highlight_id.is_none() {
11437                                old_highlight_id = chunk.syntax_highlight_id;
11438                            }
11439                            chunk.text
11440                        })
11441                        .collect::<String>()
11442                        .into();
11443
11444                    drop(buffer);
11445
11446                    // Position the selection in the rename editor so that it matches the current selection.
11447                    this.show_local_selections = false;
11448                    let rename_editor = cx.new(|cx| {
11449                        let mut editor = Editor::single_line(window, cx);
11450                        editor.buffer.update(cx, |buffer, cx| {
11451                            buffer.edit([(0..0, old_name.clone())], None, cx)
11452                        });
11453                        let rename_selection_range = match cursor_offset_in_rename_range
11454                            .cmp(&cursor_offset_in_rename_range_end)
11455                        {
11456                            Ordering::Equal => {
11457                                editor.select_all(&SelectAll, window, cx);
11458                                return editor;
11459                            }
11460                            Ordering::Less => {
11461                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11462                            }
11463                            Ordering::Greater => {
11464                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11465                            }
11466                        };
11467                        if rename_selection_range.end > old_name.len() {
11468                            editor.select_all(&SelectAll, window, cx);
11469                        } else {
11470                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11471                                s.select_ranges([rename_selection_range]);
11472                            });
11473                        }
11474                        editor
11475                    });
11476                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11477                        if e == &EditorEvent::Focused {
11478                            cx.emit(EditorEvent::FocusedIn)
11479                        }
11480                    })
11481                    .detach();
11482
11483                    let write_highlights =
11484                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11485                    let read_highlights =
11486                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11487                    let ranges = write_highlights
11488                        .iter()
11489                        .flat_map(|(_, ranges)| ranges.iter())
11490                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11491                        .cloned()
11492                        .collect();
11493
11494                    this.highlight_text::<Rename>(
11495                        ranges,
11496                        HighlightStyle {
11497                            fade_out: Some(0.6),
11498                            ..Default::default()
11499                        },
11500                        cx,
11501                    );
11502                    let rename_focus_handle = rename_editor.focus_handle(cx);
11503                    window.focus(&rename_focus_handle);
11504                    let block_id = this.insert_blocks(
11505                        [BlockProperties {
11506                            style: BlockStyle::Flex,
11507                            placement: BlockPlacement::Below(range.start),
11508                            height: 1,
11509                            render: Arc::new({
11510                                let rename_editor = rename_editor.clone();
11511                                move |cx: &mut BlockContext| {
11512                                    let mut text_style = cx.editor_style.text.clone();
11513                                    if let Some(highlight_style) = old_highlight_id
11514                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11515                                    {
11516                                        text_style = text_style.highlight(highlight_style);
11517                                    }
11518                                    div()
11519                                        .block_mouse_down()
11520                                        .pl(cx.anchor_x)
11521                                        .child(EditorElement::new(
11522                                            &rename_editor,
11523                                            EditorStyle {
11524                                                background: cx.theme().system().transparent,
11525                                                local_player: cx.editor_style.local_player,
11526                                                text: text_style,
11527                                                scrollbar_width: cx.editor_style.scrollbar_width,
11528                                                syntax: cx.editor_style.syntax.clone(),
11529                                                status: cx.editor_style.status.clone(),
11530                                                inlay_hints_style: HighlightStyle {
11531                                                    font_weight: Some(FontWeight::BOLD),
11532                                                    ..make_inlay_hints_style(cx.app)
11533                                                },
11534                                                inline_completion_styles: make_suggestion_styles(
11535                                                    cx.app,
11536                                                ),
11537                                                ..EditorStyle::default()
11538                                            },
11539                                        ))
11540                                        .into_any_element()
11541                                }
11542                            }),
11543                            priority: 0,
11544                        }],
11545                        Some(Autoscroll::fit()),
11546                        cx,
11547                    )[0];
11548                    this.pending_rename = Some(RenameState {
11549                        range,
11550                        old_name,
11551                        editor: rename_editor,
11552                        block_id,
11553                    });
11554                })?;
11555            }
11556
11557            Ok(())
11558        }))
11559    }
11560
11561    pub fn confirm_rename(
11562        &mut self,
11563        _: &ConfirmRename,
11564        window: &mut Window,
11565        cx: &mut Context<Self>,
11566    ) -> Option<Task<Result<()>>> {
11567        let rename = self.take_rename(false, window, cx)?;
11568        let workspace = self.workspace()?.downgrade();
11569        let (buffer, start) = self
11570            .buffer
11571            .read(cx)
11572            .text_anchor_for_position(rename.range.start, cx)?;
11573        let (end_buffer, _) = self
11574            .buffer
11575            .read(cx)
11576            .text_anchor_for_position(rename.range.end, cx)?;
11577        if buffer != end_buffer {
11578            return None;
11579        }
11580
11581        let old_name = rename.old_name;
11582        let new_name = rename.editor.read(cx).text(cx);
11583
11584        let rename = self.semantics_provider.as_ref()?.perform_rename(
11585            &buffer,
11586            start,
11587            new_name.clone(),
11588            cx,
11589        )?;
11590
11591        Some(cx.spawn_in(window, |editor, mut cx| async move {
11592            let project_transaction = rename.await?;
11593            Self::open_project_transaction(
11594                &editor,
11595                workspace,
11596                project_transaction,
11597                format!("Rename: {}{}", old_name, new_name),
11598                cx.clone(),
11599            )
11600            .await?;
11601
11602            editor.update(&mut cx, |editor, cx| {
11603                editor.refresh_document_highlights(cx);
11604            })?;
11605            Ok(())
11606        }))
11607    }
11608
11609    fn take_rename(
11610        &mut self,
11611        moving_cursor: bool,
11612        window: &mut Window,
11613        cx: &mut Context<Self>,
11614    ) -> Option<RenameState> {
11615        let rename = self.pending_rename.take()?;
11616        if rename.editor.focus_handle(cx).is_focused(window) {
11617            window.focus(&self.focus_handle);
11618        }
11619
11620        self.remove_blocks(
11621            [rename.block_id].into_iter().collect(),
11622            Some(Autoscroll::fit()),
11623            cx,
11624        );
11625        self.clear_highlights::<Rename>(cx);
11626        self.show_local_selections = true;
11627
11628        if moving_cursor {
11629            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11630                editor.selections.newest::<usize>(cx).head()
11631            });
11632
11633            // Update the selection to match the position of the selection inside
11634            // the rename editor.
11635            let snapshot = self.buffer.read(cx).read(cx);
11636            let rename_range = rename.range.to_offset(&snapshot);
11637            let cursor_in_editor = snapshot
11638                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11639                .min(rename_range.end);
11640            drop(snapshot);
11641
11642            self.change_selections(None, window, cx, |s| {
11643                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11644            });
11645        } else {
11646            self.refresh_document_highlights(cx);
11647        }
11648
11649        Some(rename)
11650    }
11651
11652    pub fn pending_rename(&self) -> Option<&RenameState> {
11653        self.pending_rename.as_ref()
11654    }
11655
11656    fn format(
11657        &mut self,
11658        _: &Format,
11659        window: &mut Window,
11660        cx: &mut Context<Self>,
11661    ) -> Option<Task<Result<()>>> {
11662        let project = match &self.project {
11663            Some(project) => project.clone(),
11664            None => return None,
11665        };
11666
11667        Some(self.perform_format(
11668            project,
11669            FormatTrigger::Manual,
11670            FormatTarget::Buffers,
11671            window,
11672            cx,
11673        ))
11674    }
11675
11676    fn format_selections(
11677        &mut self,
11678        _: &FormatSelections,
11679        window: &mut Window,
11680        cx: &mut Context<Self>,
11681    ) -> Option<Task<Result<()>>> {
11682        let project = match &self.project {
11683            Some(project) => project.clone(),
11684            None => return None,
11685        };
11686
11687        let ranges = self
11688            .selections
11689            .all_adjusted(cx)
11690            .into_iter()
11691            .map(|selection| selection.range())
11692            .collect_vec();
11693
11694        Some(self.perform_format(
11695            project,
11696            FormatTrigger::Manual,
11697            FormatTarget::Ranges(ranges),
11698            window,
11699            cx,
11700        ))
11701    }
11702
11703    fn perform_format(
11704        &mut self,
11705        project: Entity<Project>,
11706        trigger: FormatTrigger,
11707        target: FormatTarget,
11708        window: &mut Window,
11709        cx: &mut Context<Self>,
11710    ) -> Task<Result<()>> {
11711        let buffer = self.buffer.clone();
11712        let (buffers, target) = match target {
11713            FormatTarget::Buffers => {
11714                let mut buffers = buffer.read(cx).all_buffers();
11715                if trigger == FormatTrigger::Save {
11716                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11717                }
11718                (buffers, LspFormatTarget::Buffers)
11719            }
11720            FormatTarget::Ranges(selection_ranges) => {
11721                let multi_buffer = buffer.read(cx);
11722                let snapshot = multi_buffer.read(cx);
11723                let mut buffers = HashSet::default();
11724                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11725                    BTreeMap::new();
11726                for selection_range in selection_ranges {
11727                    for (buffer, buffer_range, _) in
11728                        snapshot.range_to_buffer_ranges(selection_range)
11729                    {
11730                        let buffer_id = buffer.remote_id();
11731                        let start = buffer.anchor_before(buffer_range.start);
11732                        let end = buffer.anchor_after(buffer_range.end);
11733                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11734                        buffer_id_to_ranges
11735                            .entry(buffer_id)
11736                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11737                            .or_insert_with(|| vec![start..end]);
11738                    }
11739                }
11740                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11741            }
11742        };
11743
11744        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11745        let format = project.update(cx, |project, cx| {
11746            project.format(buffers, target, true, trigger, cx)
11747        });
11748
11749        cx.spawn_in(window, |_, mut cx| async move {
11750            let transaction = futures::select_biased! {
11751                () = timeout => {
11752                    log::warn!("timed out waiting for formatting");
11753                    None
11754                }
11755                transaction = format.log_err().fuse() => transaction,
11756            };
11757
11758            buffer
11759                .update(&mut cx, |buffer, cx| {
11760                    if let Some(transaction) = transaction {
11761                        if !buffer.is_singleton() {
11762                            buffer.push_transaction(&transaction.0, cx);
11763                        }
11764                    }
11765
11766                    cx.notify();
11767                })
11768                .ok();
11769
11770            Ok(())
11771        })
11772    }
11773
11774    fn restart_language_server(
11775        &mut self,
11776        _: &RestartLanguageServer,
11777        _: &mut Window,
11778        cx: &mut Context<Self>,
11779    ) {
11780        if let Some(project) = self.project.clone() {
11781            self.buffer.update(cx, |multi_buffer, cx| {
11782                project.update(cx, |project, cx| {
11783                    project.restart_language_servers_for_buffers(
11784                        multi_buffer.all_buffers().into_iter().collect(),
11785                        cx,
11786                    );
11787                });
11788            })
11789        }
11790    }
11791
11792    fn cancel_language_server_work(
11793        workspace: &mut Workspace,
11794        _: &actions::CancelLanguageServerWork,
11795        _: &mut Window,
11796        cx: &mut Context<Workspace>,
11797    ) {
11798        let project = workspace.project();
11799        let buffers = workspace
11800            .active_item(cx)
11801            .and_then(|item| item.act_as::<Editor>(cx))
11802            .map_or(HashSet::default(), |editor| {
11803                editor.read(cx).buffer.read(cx).all_buffers()
11804            });
11805        project.update(cx, |project, cx| {
11806            project.cancel_language_server_work_for_buffers(buffers, cx);
11807        });
11808    }
11809
11810    fn show_character_palette(
11811        &mut self,
11812        _: &ShowCharacterPalette,
11813        window: &mut Window,
11814        _: &mut Context<Self>,
11815    ) {
11816        window.show_character_palette();
11817    }
11818
11819    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11820        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11821            let buffer = self.buffer.read(cx).snapshot(cx);
11822            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11823            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11824            let is_valid = buffer
11825                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11826                .any(|entry| {
11827                    entry.diagnostic.is_primary
11828                        && !entry.range.is_empty()
11829                        && entry.range.start == primary_range_start
11830                        && entry.diagnostic.message == active_diagnostics.primary_message
11831                });
11832
11833            if is_valid != active_diagnostics.is_valid {
11834                active_diagnostics.is_valid = is_valid;
11835                let mut new_styles = HashMap::default();
11836                for (block_id, diagnostic) in &active_diagnostics.blocks {
11837                    new_styles.insert(
11838                        *block_id,
11839                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11840                    );
11841                }
11842                self.display_map.update(cx, |display_map, _cx| {
11843                    display_map.replace_blocks(new_styles)
11844                });
11845            }
11846        }
11847    }
11848
11849    fn activate_diagnostics(
11850        &mut self,
11851        buffer_id: BufferId,
11852        group_id: usize,
11853        window: &mut Window,
11854        cx: &mut Context<Self>,
11855    ) {
11856        self.dismiss_diagnostics(cx);
11857        let snapshot = self.snapshot(window, cx);
11858        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11859            let buffer = self.buffer.read(cx).snapshot(cx);
11860
11861            let mut primary_range = None;
11862            let mut primary_message = None;
11863            let diagnostic_group = buffer
11864                .diagnostic_group(buffer_id, group_id)
11865                .filter_map(|entry| {
11866                    let start = entry.range.start;
11867                    let end = entry.range.end;
11868                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11869                        && (start.row == end.row
11870                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11871                    {
11872                        return None;
11873                    }
11874                    if entry.diagnostic.is_primary {
11875                        primary_range = Some(entry.range.clone());
11876                        primary_message = Some(entry.diagnostic.message.clone());
11877                    }
11878                    Some(entry)
11879                })
11880                .collect::<Vec<_>>();
11881            let primary_range = primary_range?;
11882            let primary_message = primary_message?;
11883
11884            let blocks = display_map
11885                .insert_blocks(
11886                    diagnostic_group.iter().map(|entry| {
11887                        let diagnostic = entry.diagnostic.clone();
11888                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11889                        BlockProperties {
11890                            style: BlockStyle::Fixed,
11891                            placement: BlockPlacement::Below(
11892                                buffer.anchor_after(entry.range.start),
11893                            ),
11894                            height: message_height,
11895                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11896                            priority: 0,
11897                        }
11898                    }),
11899                    cx,
11900                )
11901                .into_iter()
11902                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11903                .collect();
11904
11905            Some(ActiveDiagnosticGroup {
11906                primary_range: buffer.anchor_before(primary_range.start)
11907                    ..buffer.anchor_after(primary_range.end),
11908                primary_message,
11909                group_id,
11910                blocks,
11911                is_valid: true,
11912            })
11913        });
11914    }
11915
11916    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11917        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11918            self.display_map.update(cx, |display_map, cx| {
11919                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11920            });
11921            cx.notify();
11922        }
11923    }
11924
11925    pub fn set_selections_from_remote(
11926        &mut self,
11927        selections: Vec<Selection<Anchor>>,
11928        pending_selection: Option<Selection<Anchor>>,
11929        window: &mut Window,
11930        cx: &mut Context<Self>,
11931    ) {
11932        let old_cursor_position = self.selections.newest_anchor().head();
11933        self.selections.change_with(cx, |s| {
11934            s.select_anchors(selections);
11935            if let Some(pending_selection) = pending_selection {
11936                s.set_pending(pending_selection, SelectMode::Character);
11937            } else {
11938                s.clear_pending();
11939            }
11940        });
11941        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11942    }
11943
11944    fn push_to_selection_history(&mut self) {
11945        self.selection_history.push(SelectionHistoryEntry {
11946            selections: self.selections.disjoint_anchors(),
11947            select_next_state: self.select_next_state.clone(),
11948            select_prev_state: self.select_prev_state.clone(),
11949            add_selections_state: self.add_selections_state.clone(),
11950        });
11951    }
11952
11953    pub fn transact(
11954        &mut self,
11955        window: &mut Window,
11956        cx: &mut Context<Self>,
11957        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11958    ) -> Option<TransactionId> {
11959        self.start_transaction_at(Instant::now(), window, cx);
11960        update(self, window, cx);
11961        self.end_transaction_at(Instant::now(), cx)
11962    }
11963
11964    pub fn start_transaction_at(
11965        &mut self,
11966        now: Instant,
11967        window: &mut Window,
11968        cx: &mut Context<Self>,
11969    ) {
11970        self.end_selection(window, cx);
11971        if let Some(tx_id) = self
11972            .buffer
11973            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11974        {
11975            self.selection_history
11976                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11977            cx.emit(EditorEvent::TransactionBegun {
11978                transaction_id: tx_id,
11979            })
11980        }
11981    }
11982
11983    pub fn end_transaction_at(
11984        &mut self,
11985        now: Instant,
11986        cx: &mut Context<Self>,
11987    ) -> Option<TransactionId> {
11988        if let Some(transaction_id) = self
11989            .buffer
11990            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11991        {
11992            if let Some((_, end_selections)) =
11993                self.selection_history.transaction_mut(transaction_id)
11994            {
11995                *end_selections = Some(self.selections.disjoint_anchors());
11996            } else {
11997                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11998            }
11999
12000            cx.emit(EditorEvent::Edited { transaction_id });
12001            Some(transaction_id)
12002        } else {
12003            None
12004        }
12005    }
12006
12007    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12008        if self.selection_mark_mode {
12009            self.change_selections(None, window, cx, |s| {
12010                s.move_with(|_, sel| {
12011                    sel.collapse_to(sel.head(), SelectionGoal::None);
12012                });
12013            })
12014        }
12015        self.selection_mark_mode = true;
12016        cx.notify();
12017    }
12018
12019    pub fn swap_selection_ends(
12020        &mut self,
12021        _: &actions::SwapSelectionEnds,
12022        window: &mut Window,
12023        cx: &mut Context<Self>,
12024    ) {
12025        self.change_selections(None, window, cx, |s| {
12026            s.move_with(|_, sel| {
12027                if sel.start != sel.end {
12028                    sel.reversed = !sel.reversed
12029                }
12030            });
12031        });
12032        self.request_autoscroll(Autoscroll::newest(), cx);
12033        cx.notify();
12034    }
12035
12036    pub fn toggle_fold(
12037        &mut self,
12038        _: &actions::ToggleFold,
12039        window: &mut Window,
12040        cx: &mut Context<Self>,
12041    ) {
12042        if self.is_singleton(cx) {
12043            let selection = self.selections.newest::<Point>(cx);
12044
12045            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12046            let range = if selection.is_empty() {
12047                let point = selection.head().to_display_point(&display_map);
12048                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12049                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12050                    .to_point(&display_map);
12051                start..end
12052            } else {
12053                selection.range()
12054            };
12055            if display_map.folds_in_range(range).next().is_some() {
12056                self.unfold_lines(&Default::default(), window, cx)
12057            } else {
12058                self.fold(&Default::default(), window, cx)
12059            }
12060        } else {
12061            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12062            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12063                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12064                .map(|(snapshot, _, _)| snapshot.remote_id())
12065                .collect();
12066
12067            for buffer_id in buffer_ids {
12068                if self.is_buffer_folded(buffer_id, cx) {
12069                    self.unfold_buffer(buffer_id, cx);
12070                } else {
12071                    self.fold_buffer(buffer_id, cx);
12072                }
12073            }
12074        }
12075    }
12076
12077    pub fn toggle_fold_recursive(
12078        &mut self,
12079        _: &actions::ToggleFoldRecursive,
12080        window: &mut Window,
12081        cx: &mut Context<Self>,
12082    ) {
12083        let selection = self.selections.newest::<Point>(cx);
12084
12085        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12086        let range = if selection.is_empty() {
12087            let point = selection.head().to_display_point(&display_map);
12088            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12089            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12090                .to_point(&display_map);
12091            start..end
12092        } else {
12093            selection.range()
12094        };
12095        if display_map.folds_in_range(range).next().is_some() {
12096            self.unfold_recursive(&Default::default(), window, cx)
12097        } else {
12098            self.fold_recursive(&Default::default(), window, cx)
12099        }
12100    }
12101
12102    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12103        if self.is_singleton(cx) {
12104            let mut to_fold = Vec::new();
12105            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12106            let selections = self.selections.all_adjusted(cx);
12107
12108            for selection in selections {
12109                let range = selection.range().sorted();
12110                let buffer_start_row = range.start.row;
12111
12112                if range.start.row != range.end.row {
12113                    let mut found = false;
12114                    let mut row = range.start.row;
12115                    while row <= range.end.row {
12116                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12117                        {
12118                            found = true;
12119                            row = crease.range().end.row + 1;
12120                            to_fold.push(crease);
12121                        } else {
12122                            row += 1
12123                        }
12124                    }
12125                    if found {
12126                        continue;
12127                    }
12128                }
12129
12130                for row in (0..=range.start.row).rev() {
12131                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12132                        if crease.range().end.row >= buffer_start_row {
12133                            to_fold.push(crease);
12134                            if row <= range.start.row {
12135                                break;
12136                            }
12137                        }
12138                    }
12139                }
12140            }
12141
12142            self.fold_creases(to_fold, true, window, cx);
12143        } else {
12144            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12145
12146            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12147                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12148                .map(|(snapshot, _, _)| snapshot.remote_id())
12149                .collect();
12150            for buffer_id in buffer_ids {
12151                self.fold_buffer(buffer_id, cx);
12152            }
12153        }
12154    }
12155
12156    fn fold_at_level(
12157        &mut self,
12158        fold_at: &FoldAtLevel,
12159        window: &mut Window,
12160        cx: &mut Context<Self>,
12161    ) {
12162        if !self.buffer.read(cx).is_singleton() {
12163            return;
12164        }
12165
12166        let fold_at_level = fold_at.0;
12167        let snapshot = self.buffer.read(cx).snapshot(cx);
12168        let mut to_fold = Vec::new();
12169        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12170
12171        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12172            while start_row < end_row {
12173                match self
12174                    .snapshot(window, cx)
12175                    .crease_for_buffer_row(MultiBufferRow(start_row))
12176                {
12177                    Some(crease) => {
12178                        let nested_start_row = crease.range().start.row + 1;
12179                        let nested_end_row = crease.range().end.row;
12180
12181                        if current_level < fold_at_level {
12182                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12183                        } else if current_level == fold_at_level {
12184                            to_fold.push(crease);
12185                        }
12186
12187                        start_row = nested_end_row + 1;
12188                    }
12189                    None => start_row += 1,
12190                }
12191            }
12192        }
12193
12194        self.fold_creases(to_fold, true, window, cx);
12195    }
12196
12197    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12198        if self.buffer.read(cx).is_singleton() {
12199            let mut fold_ranges = Vec::new();
12200            let snapshot = self.buffer.read(cx).snapshot(cx);
12201
12202            for row in 0..snapshot.max_row().0 {
12203                if let Some(foldable_range) = self
12204                    .snapshot(window, cx)
12205                    .crease_for_buffer_row(MultiBufferRow(row))
12206                {
12207                    fold_ranges.push(foldable_range);
12208                }
12209            }
12210
12211            self.fold_creases(fold_ranges, true, window, cx);
12212        } else {
12213            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12214                editor
12215                    .update_in(&mut cx, |editor, _, cx| {
12216                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12217                            editor.fold_buffer(buffer_id, cx);
12218                        }
12219                    })
12220                    .ok();
12221            });
12222        }
12223    }
12224
12225    pub fn fold_function_bodies(
12226        &mut self,
12227        _: &actions::FoldFunctionBodies,
12228        window: &mut Window,
12229        cx: &mut Context<Self>,
12230    ) {
12231        let snapshot = self.buffer.read(cx).snapshot(cx);
12232
12233        let ranges = snapshot
12234            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12235            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12236            .collect::<Vec<_>>();
12237
12238        let creases = ranges
12239            .into_iter()
12240            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12241            .collect();
12242
12243        self.fold_creases(creases, true, window, cx);
12244    }
12245
12246    pub fn fold_recursive(
12247        &mut self,
12248        _: &actions::FoldRecursive,
12249        window: &mut Window,
12250        cx: &mut Context<Self>,
12251    ) {
12252        let mut to_fold = Vec::new();
12253        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12254        let selections = self.selections.all_adjusted(cx);
12255
12256        for selection in selections {
12257            let range = selection.range().sorted();
12258            let buffer_start_row = range.start.row;
12259
12260            if range.start.row != range.end.row {
12261                let mut found = false;
12262                for row in range.start.row..=range.end.row {
12263                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12264                        found = true;
12265                        to_fold.push(crease);
12266                    }
12267                }
12268                if found {
12269                    continue;
12270                }
12271            }
12272
12273            for row in (0..=range.start.row).rev() {
12274                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12275                    if crease.range().end.row >= buffer_start_row {
12276                        to_fold.push(crease);
12277                    } else {
12278                        break;
12279                    }
12280                }
12281            }
12282        }
12283
12284        self.fold_creases(to_fold, true, window, cx);
12285    }
12286
12287    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12288        let buffer_row = fold_at.buffer_row;
12289        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12290
12291        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12292            let autoscroll = self
12293                .selections
12294                .all::<Point>(cx)
12295                .iter()
12296                .any(|selection| crease.range().overlaps(&selection.range()));
12297
12298            self.fold_creases(vec![crease], autoscroll, window, cx);
12299        }
12300    }
12301
12302    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12303        if self.is_singleton(cx) {
12304            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12305            let buffer = &display_map.buffer_snapshot;
12306            let selections = self.selections.all::<Point>(cx);
12307            let ranges = selections
12308                .iter()
12309                .map(|s| {
12310                    let range = s.display_range(&display_map).sorted();
12311                    let mut start = range.start.to_point(&display_map);
12312                    let mut end = range.end.to_point(&display_map);
12313                    start.column = 0;
12314                    end.column = buffer.line_len(MultiBufferRow(end.row));
12315                    start..end
12316                })
12317                .collect::<Vec<_>>();
12318
12319            self.unfold_ranges(&ranges, true, true, cx);
12320        } else {
12321            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12322            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12323                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12324                .map(|(snapshot, _, _)| snapshot.remote_id())
12325                .collect();
12326            for buffer_id in buffer_ids {
12327                self.unfold_buffer(buffer_id, cx);
12328            }
12329        }
12330    }
12331
12332    pub fn unfold_recursive(
12333        &mut self,
12334        _: &UnfoldRecursive,
12335        _window: &mut Window,
12336        cx: &mut Context<Self>,
12337    ) {
12338        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12339        let selections = self.selections.all::<Point>(cx);
12340        let ranges = selections
12341            .iter()
12342            .map(|s| {
12343                let mut range = s.display_range(&display_map).sorted();
12344                *range.start.column_mut() = 0;
12345                *range.end.column_mut() = display_map.line_len(range.end.row());
12346                let start = range.start.to_point(&display_map);
12347                let end = range.end.to_point(&display_map);
12348                start..end
12349            })
12350            .collect::<Vec<_>>();
12351
12352        self.unfold_ranges(&ranges, true, true, cx);
12353    }
12354
12355    pub fn unfold_at(
12356        &mut self,
12357        unfold_at: &UnfoldAt,
12358        _window: &mut Window,
12359        cx: &mut Context<Self>,
12360    ) {
12361        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12362
12363        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12364            ..Point::new(
12365                unfold_at.buffer_row.0,
12366                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12367            );
12368
12369        let autoscroll = self
12370            .selections
12371            .all::<Point>(cx)
12372            .iter()
12373            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12374
12375        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12376    }
12377
12378    pub fn unfold_all(
12379        &mut self,
12380        _: &actions::UnfoldAll,
12381        _window: &mut Window,
12382        cx: &mut Context<Self>,
12383    ) {
12384        if self.buffer.read(cx).is_singleton() {
12385            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12386            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12387        } else {
12388            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12389                editor
12390                    .update(&mut cx, |editor, cx| {
12391                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12392                            editor.unfold_buffer(buffer_id, cx);
12393                        }
12394                    })
12395                    .ok();
12396            });
12397        }
12398    }
12399
12400    pub fn fold_selected_ranges(
12401        &mut self,
12402        _: &FoldSelectedRanges,
12403        window: &mut Window,
12404        cx: &mut Context<Self>,
12405    ) {
12406        let selections = self.selections.all::<Point>(cx);
12407        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12408        let line_mode = self.selections.line_mode;
12409        let ranges = selections
12410            .into_iter()
12411            .map(|s| {
12412                if line_mode {
12413                    let start = Point::new(s.start.row, 0);
12414                    let end = Point::new(
12415                        s.end.row,
12416                        display_map
12417                            .buffer_snapshot
12418                            .line_len(MultiBufferRow(s.end.row)),
12419                    );
12420                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12421                } else {
12422                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12423                }
12424            })
12425            .collect::<Vec<_>>();
12426        self.fold_creases(ranges, true, window, cx);
12427    }
12428
12429    pub fn fold_ranges<T: ToOffset + Clone>(
12430        &mut self,
12431        ranges: Vec<Range<T>>,
12432        auto_scroll: bool,
12433        window: &mut Window,
12434        cx: &mut Context<Self>,
12435    ) {
12436        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12437        let ranges = ranges
12438            .into_iter()
12439            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12440            .collect::<Vec<_>>();
12441        self.fold_creases(ranges, auto_scroll, window, cx);
12442    }
12443
12444    pub fn fold_creases<T: ToOffset + Clone>(
12445        &mut self,
12446        creases: Vec<Crease<T>>,
12447        auto_scroll: bool,
12448        window: &mut Window,
12449        cx: &mut Context<Self>,
12450    ) {
12451        if creases.is_empty() {
12452            return;
12453        }
12454
12455        let mut buffers_affected = HashSet::default();
12456        let multi_buffer = self.buffer().read(cx);
12457        for crease in &creases {
12458            if let Some((_, buffer, _)) =
12459                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12460            {
12461                buffers_affected.insert(buffer.read(cx).remote_id());
12462            };
12463        }
12464
12465        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12466
12467        if auto_scroll {
12468            self.request_autoscroll(Autoscroll::fit(), cx);
12469        }
12470
12471        cx.notify();
12472
12473        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12474            // Clear diagnostics block when folding a range that contains it.
12475            let snapshot = self.snapshot(window, cx);
12476            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12477                drop(snapshot);
12478                self.active_diagnostics = Some(active_diagnostics);
12479                self.dismiss_diagnostics(cx);
12480            } else {
12481                self.active_diagnostics = Some(active_diagnostics);
12482            }
12483        }
12484
12485        self.scrollbar_marker_state.dirty = true;
12486    }
12487
12488    /// Removes any folds whose ranges intersect any of the given ranges.
12489    pub fn unfold_ranges<T: ToOffset + Clone>(
12490        &mut self,
12491        ranges: &[Range<T>],
12492        inclusive: bool,
12493        auto_scroll: bool,
12494        cx: &mut Context<Self>,
12495    ) {
12496        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12497            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12498        });
12499    }
12500
12501    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12502        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12503            return;
12504        }
12505        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12506        self.display_map
12507            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12508        cx.emit(EditorEvent::BufferFoldToggled {
12509            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12510            folded: true,
12511        });
12512        cx.notify();
12513    }
12514
12515    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12516        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12517            return;
12518        }
12519        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12520        self.display_map.update(cx, |display_map, cx| {
12521            display_map.unfold_buffer(buffer_id, cx);
12522        });
12523        cx.emit(EditorEvent::BufferFoldToggled {
12524            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12525            folded: false,
12526        });
12527        cx.notify();
12528    }
12529
12530    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12531        self.display_map.read(cx).is_buffer_folded(buffer)
12532    }
12533
12534    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12535        self.display_map.read(cx).folded_buffers()
12536    }
12537
12538    /// Removes any folds with the given ranges.
12539    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12540        &mut self,
12541        ranges: &[Range<T>],
12542        type_id: TypeId,
12543        auto_scroll: bool,
12544        cx: &mut Context<Self>,
12545    ) {
12546        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12547            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12548        });
12549    }
12550
12551    fn remove_folds_with<T: ToOffset + Clone>(
12552        &mut self,
12553        ranges: &[Range<T>],
12554        auto_scroll: bool,
12555        cx: &mut Context<Self>,
12556        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12557    ) {
12558        if ranges.is_empty() {
12559            return;
12560        }
12561
12562        let mut buffers_affected = HashSet::default();
12563        let multi_buffer = self.buffer().read(cx);
12564        for range in ranges {
12565            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12566                buffers_affected.insert(buffer.read(cx).remote_id());
12567            };
12568        }
12569
12570        self.display_map.update(cx, update);
12571
12572        if auto_scroll {
12573            self.request_autoscroll(Autoscroll::fit(), cx);
12574        }
12575
12576        cx.notify();
12577        self.scrollbar_marker_state.dirty = true;
12578        self.active_indent_guides_state.dirty = true;
12579    }
12580
12581    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12582        self.display_map.read(cx).fold_placeholder.clone()
12583    }
12584
12585    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12586        self.buffer.update(cx, |buffer, cx| {
12587            buffer.set_all_diff_hunks_expanded(cx);
12588        });
12589    }
12590
12591    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12592        self.distinguish_unstaged_diff_hunks = true;
12593    }
12594
12595    pub fn expand_all_diff_hunks(
12596        &mut self,
12597        _: &ExpandAllHunkDiffs,
12598        _window: &mut Window,
12599        cx: &mut Context<Self>,
12600    ) {
12601        self.buffer.update(cx, |buffer, cx| {
12602            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12603        });
12604    }
12605
12606    pub fn toggle_selected_diff_hunks(
12607        &mut self,
12608        _: &ToggleSelectedDiffHunks,
12609        _window: &mut Window,
12610        cx: &mut Context<Self>,
12611    ) {
12612        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12613        self.toggle_diff_hunks_in_ranges(ranges, cx);
12614    }
12615
12616    fn diff_hunks_in_ranges<'a>(
12617        &'a self,
12618        ranges: &'a [Range<Anchor>],
12619        buffer: &'a MultiBufferSnapshot,
12620    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12621        ranges.iter().flat_map(move |range| {
12622            let end_excerpt_id = range.end.excerpt_id;
12623            let range = range.to_point(buffer);
12624            let mut peek_end = range.end;
12625            if range.end.row < buffer.max_row().0 {
12626                peek_end = Point::new(range.end.row + 1, 0);
12627            }
12628            buffer
12629                .diff_hunks_in_range(range.start..peek_end)
12630                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12631        })
12632    }
12633
12634    pub fn has_stageable_diff_hunks_in_ranges(
12635        &self,
12636        ranges: &[Range<Anchor>],
12637        snapshot: &MultiBufferSnapshot,
12638    ) -> bool {
12639        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12640        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12641    }
12642
12643    pub fn toggle_staged_selected_diff_hunks(
12644        &mut self,
12645        _: &ToggleStagedSelectedDiffHunks,
12646        _window: &mut Window,
12647        cx: &mut Context<Self>,
12648    ) {
12649        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12650        self.stage_or_unstage_diff_hunks(&ranges, cx);
12651    }
12652
12653    pub fn stage_or_unstage_diff_hunks(
12654        &mut self,
12655        ranges: &[Range<Anchor>],
12656        cx: &mut Context<Self>,
12657    ) {
12658        let Some(project) = &self.project else {
12659            return;
12660        };
12661        let snapshot = self.buffer.read(cx).snapshot(cx);
12662        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12663
12664        let chunk_by = self
12665            .diff_hunks_in_ranges(&ranges, &snapshot)
12666            .chunk_by(|hunk| hunk.buffer_id);
12667        for (buffer_id, hunks) in &chunk_by {
12668            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12669                log::debug!("no buffer for id");
12670                continue;
12671            };
12672            let buffer = buffer.read(cx).snapshot();
12673            let Some((repo, path)) = project
12674                .read(cx)
12675                .repository_and_path_for_buffer_id(buffer_id, cx)
12676            else {
12677                log::debug!("no git repo for buffer id");
12678                continue;
12679            };
12680            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12681                log::debug!("no diff for buffer id");
12682                continue;
12683            };
12684            let Some(secondary_diff) = diff.secondary_diff() else {
12685                log::debug!("no secondary diff for buffer id");
12686                continue;
12687            };
12688
12689            let edits = diff.secondary_edits_for_stage_or_unstage(
12690                stage,
12691                hunks.map(|hunk| {
12692                    (
12693                        hunk.diff_base_byte_range.clone(),
12694                        hunk.secondary_diff_base_byte_range.clone(),
12695                        hunk.buffer_range.clone(),
12696                    )
12697                }),
12698                &buffer,
12699            );
12700
12701            let index_base = secondary_diff.base_text().map_or_else(
12702                || Rope::from(""),
12703                |snapshot| snapshot.text.as_rope().clone(),
12704            );
12705            let index_buffer = cx.new(|cx| {
12706                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12707            });
12708            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12709                index_buffer.edit(edits, None, cx);
12710                index_buffer.snapshot().as_rope().to_string()
12711            });
12712            let new_index_text = if new_index_text.is_empty()
12713                && (diff.is_single_insertion
12714                    || buffer
12715                        .file()
12716                        .map_or(false, |file| file.disk_state() == DiskState::New))
12717            {
12718                log::debug!("removing from index");
12719                None
12720            } else {
12721                Some(new_index_text)
12722            };
12723
12724            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12725        }
12726    }
12727
12728    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12729        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12730        self.buffer
12731            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12732    }
12733
12734    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12735        self.buffer.update(cx, |buffer, cx| {
12736            let ranges = vec![Anchor::min()..Anchor::max()];
12737            if !buffer.all_diff_hunks_expanded()
12738                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12739            {
12740                buffer.collapse_diff_hunks(ranges, cx);
12741                true
12742            } else {
12743                false
12744            }
12745        })
12746    }
12747
12748    fn toggle_diff_hunks_in_ranges(
12749        &mut self,
12750        ranges: Vec<Range<Anchor>>,
12751        cx: &mut Context<'_, Editor>,
12752    ) {
12753        self.buffer.update(cx, |buffer, cx| {
12754            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12755            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12756        })
12757    }
12758
12759    fn toggle_diff_hunks_in_ranges_narrow(
12760        &mut self,
12761        ranges: Vec<Range<Anchor>>,
12762        cx: &mut Context<'_, Editor>,
12763    ) {
12764        self.buffer.update(cx, |buffer, cx| {
12765            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12766            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12767        })
12768    }
12769
12770    pub(crate) fn apply_all_diff_hunks(
12771        &mut self,
12772        _: &ApplyAllDiffHunks,
12773        window: &mut Window,
12774        cx: &mut Context<Self>,
12775    ) {
12776        let buffers = self.buffer.read(cx).all_buffers();
12777        for branch_buffer in buffers {
12778            branch_buffer.update(cx, |branch_buffer, cx| {
12779                branch_buffer.merge_into_base(Vec::new(), cx);
12780            });
12781        }
12782
12783        if let Some(project) = self.project.clone() {
12784            self.save(true, project, window, cx).detach_and_log_err(cx);
12785        }
12786    }
12787
12788    pub(crate) fn apply_selected_diff_hunks(
12789        &mut self,
12790        _: &ApplyDiffHunk,
12791        window: &mut Window,
12792        cx: &mut Context<Self>,
12793    ) {
12794        let snapshot = self.snapshot(window, cx);
12795        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12796        let mut ranges_by_buffer = HashMap::default();
12797        self.transact(window, cx, |editor, _window, cx| {
12798            for hunk in hunks {
12799                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12800                    ranges_by_buffer
12801                        .entry(buffer.clone())
12802                        .or_insert_with(Vec::new)
12803                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12804                }
12805            }
12806
12807            for (buffer, ranges) in ranges_by_buffer {
12808                buffer.update(cx, |buffer, cx| {
12809                    buffer.merge_into_base(ranges, cx);
12810                });
12811            }
12812        });
12813
12814        if let Some(project) = self.project.clone() {
12815            self.save(true, project, window, cx).detach_and_log_err(cx);
12816        }
12817    }
12818
12819    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12820        if hovered != self.gutter_hovered {
12821            self.gutter_hovered = hovered;
12822            cx.notify();
12823        }
12824    }
12825
12826    pub fn insert_blocks(
12827        &mut self,
12828        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12829        autoscroll: Option<Autoscroll>,
12830        cx: &mut Context<Self>,
12831    ) -> Vec<CustomBlockId> {
12832        let blocks = self
12833            .display_map
12834            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12835        if let Some(autoscroll) = autoscroll {
12836            self.request_autoscroll(autoscroll, cx);
12837        }
12838        cx.notify();
12839        blocks
12840    }
12841
12842    pub fn resize_blocks(
12843        &mut self,
12844        heights: HashMap<CustomBlockId, u32>,
12845        autoscroll: Option<Autoscroll>,
12846        cx: &mut Context<Self>,
12847    ) {
12848        self.display_map
12849            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12850        if let Some(autoscroll) = autoscroll {
12851            self.request_autoscroll(autoscroll, cx);
12852        }
12853        cx.notify();
12854    }
12855
12856    pub fn replace_blocks(
12857        &mut self,
12858        renderers: HashMap<CustomBlockId, RenderBlock>,
12859        autoscroll: Option<Autoscroll>,
12860        cx: &mut Context<Self>,
12861    ) {
12862        self.display_map
12863            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12864        if let Some(autoscroll) = autoscroll {
12865            self.request_autoscroll(autoscroll, cx);
12866        }
12867        cx.notify();
12868    }
12869
12870    pub fn remove_blocks(
12871        &mut self,
12872        block_ids: HashSet<CustomBlockId>,
12873        autoscroll: Option<Autoscroll>,
12874        cx: &mut Context<Self>,
12875    ) {
12876        self.display_map.update(cx, |display_map, cx| {
12877            display_map.remove_blocks(block_ids, cx)
12878        });
12879        if let Some(autoscroll) = autoscroll {
12880            self.request_autoscroll(autoscroll, cx);
12881        }
12882        cx.notify();
12883    }
12884
12885    pub fn row_for_block(
12886        &self,
12887        block_id: CustomBlockId,
12888        cx: &mut Context<Self>,
12889    ) -> Option<DisplayRow> {
12890        self.display_map
12891            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12892    }
12893
12894    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12895        self.focused_block = Some(focused_block);
12896    }
12897
12898    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12899        self.focused_block.take()
12900    }
12901
12902    pub fn insert_creases(
12903        &mut self,
12904        creases: impl IntoIterator<Item = Crease<Anchor>>,
12905        cx: &mut Context<Self>,
12906    ) -> Vec<CreaseId> {
12907        self.display_map
12908            .update(cx, |map, cx| map.insert_creases(creases, cx))
12909    }
12910
12911    pub fn remove_creases(
12912        &mut self,
12913        ids: impl IntoIterator<Item = CreaseId>,
12914        cx: &mut Context<Self>,
12915    ) {
12916        self.display_map
12917            .update(cx, |map, cx| map.remove_creases(ids, cx));
12918    }
12919
12920    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12921        self.display_map
12922            .update(cx, |map, cx| map.snapshot(cx))
12923            .longest_row()
12924    }
12925
12926    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12927        self.display_map
12928            .update(cx, |map, cx| map.snapshot(cx))
12929            .max_point()
12930    }
12931
12932    pub fn text(&self, cx: &App) -> String {
12933        self.buffer.read(cx).read(cx).text()
12934    }
12935
12936    pub fn is_empty(&self, cx: &App) -> bool {
12937        self.buffer.read(cx).read(cx).is_empty()
12938    }
12939
12940    pub fn text_option(&self, cx: &App) -> Option<String> {
12941        let text = self.text(cx);
12942        let text = text.trim();
12943
12944        if text.is_empty() {
12945            return None;
12946        }
12947
12948        Some(text.to_string())
12949    }
12950
12951    pub fn set_text(
12952        &mut self,
12953        text: impl Into<Arc<str>>,
12954        window: &mut Window,
12955        cx: &mut Context<Self>,
12956    ) {
12957        self.transact(window, cx, |this, _, cx| {
12958            this.buffer
12959                .read(cx)
12960                .as_singleton()
12961                .expect("you can only call set_text on editors for singleton buffers")
12962                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12963        });
12964    }
12965
12966    pub fn display_text(&self, cx: &mut App) -> String {
12967        self.display_map
12968            .update(cx, |map, cx| map.snapshot(cx))
12969            .text()
12970    }
12971
12972    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12973        let mut wrap_guides = smallvec::smallvec![];
12974
12975        if self.show_wrap_guides == Some(false) {
12976            return wrap_guides;
12977        }
12978
12979        let settings = self.buffer.read(cx).settings_at(0, cx);
12980        if settings.show_wrap_guides {
12981            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12982                wrap_guides.push((soft_wrap as usize, true));
12983            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12984                wrap_guides.push((soft_wrap as usize, true));
12985            }
12986            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12987        }
12988
12989        wrap_guides
12990    }
12991
12992    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12993        let settings = self.buffer.read(cx).settings_at(0, cx);
12994        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12995        match mode {
12996            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12997                SoftWrap::None
12998            }
12999            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13000            language_settings::SoftWrap::PreferredLineLength => {
13001                SoftWrap::Column(settings.preferred_line_length)
13002            }
13003            language_settings::SoftWrap::Bounded => {
13004                SoftWrap::Bounded(settings.preferred_line_length)
13005            }
13006        }
13007    }
13008
13009    pub fn set_soft_wrap_mode(
13010        &mut self,
13011        mode: language_settings::SoftWrap,
13012
13013        cx: &mut Context<Self>,
13014    ) {
13015        self.soft_wrap_mode_override = Some(mode);
13016        cx.notify();
13017    }
13018
13019    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13020        self.text_style_refinement = Some(style);
13021    }
13022
13023    /// called by the Element so we know what style we were most recently rendered with.
13024    pub(crate) fn set_style(
13025        &mut self,
13026        style: EditorStyle,
13027        window: &mut Window,
13028        cx: &mut Context<Self>,
13029    ) {
13030        let rem_size = window.rem_size();
13031        self.display_map.update(cx, |map, cx| {
13032            map.set_font(
13033                style.text.font(),
13034                style.text.font_size.to_pixels(rem_size),
13035                cx,
13036            )
13037        });
13038        self.style = Some(style);
13039    }
13040
13041    pub fn style(&self) -> Option<&EditorStyle> {
13042        self.style.as_ref()
13043    }
13044
13045    // Called by the element. This method is not designed to be called outside of the editor
13046    // element's layout code because it does not notify when rewrapping is computed synchronously.
13047    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13048        self.display_map
13049            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13050    }
13051
13052    pub fn set_soft_wrap(&mut self) {
13053        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13054    }
13055
13056    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13057        if self.soft_wrap_mode_override.is_some() {
13058            self.soft_wrap_mode_override.take();
13059        } else {
13060            let soft_wrap = match self.soft_wrap_mode(cx) {
13061                SoftWrap::GitDiff => return,
13062                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13063                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13064                    language_settings::SoftWrap::None
13065                }
13066            };
13067            self.soft_wrap_mode_override = Some(soft_wrap);
13068        }
13069        cx.notify();
13070    }
13071
13072    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13073        let Some(workspace) = self.workspace() else {
13074            return;
13075        };
13076        let fs = workspace.read(cx).app_state().fs.clone();
13077        let current_show = TabBarSettings::get_global(cx).show;
13078        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13079            setting.show = Some(!current_show);
13080        });
13081    }
13082
13083    pub fn toggle_indent_guides(
13084        &mut self,
13085        _: &ToggleIndentGuides,
13086        _: &mut Window,
13087        cx: &mut Context<Self>,
13088    ) {
13089        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13090            self.buffer
13091                .read(cx)
13092                .settings_at(0, cx)
13093                .indent_guides
13094                .enabled
13095        });
13096        self.show_indent_guides = Some(!currently_enabled);
13097        cx.notify();
13098    }
13099
13100    fn should_show_indent_guides(&self) -> Option<bool> {
13101        self.show_indent_guides
13102    }
13103
13104    pub fn toggle_line_numbers(
13105        &mut self,
13106        _: &ToggleLineNumbers,
13107        _: &mut Window,
13108        cx: &mut Context<Self>,
13109    ) {
13110        let mut editor_settings = EditorSettings::get_global(cx).clone();
13111        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13112        EditorSettings::override_global(editor_settings, cx);
13113    }
13114
13115    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13116        self.use_relative_line_numbers
13117            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13118    }
13119
13120    pub fn toggle_relative_line_numbers(
13121        &mut self,
13122        _: &ToggleRelativeLineNumbers,
13123        _: &mut Window,
13124        cx: &mut Context<Self>,
13125    ) {
13126        let is_relative = self.should_use_relative_line_numbers(cx);
13127        self.set_relative_line_number(Some(!is_relative), cx)
13128    }
13129
13130    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13131        self.use_relative_line_numbers = is_relative;
13132        cx.notify();
13133    }
13134
13135    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13136        self.show_gutter = show_gutter;
13137        cx.notify();
13138    }
13139
13140    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13141        self.show_scrollbars = show_scrollbars;
13142        cx.notify();
13143    }
13144
13145    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13146        self.show_line_numbers = Some(show_line_numbers);
13147        cx.notify();
13148    }
13149
13150    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13151        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13152        cx.notify();
13153    }
13154
13155    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13156        self.show_code_actions = Some(show_code_actions);
13157        cx.notify();
13158    }
13159
13160    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13161        self.show_runnables = Some(show_runnables);
13162        cx.notify();
13163    }
13164
13165    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13166        if self.display_map.read(cx).masked != masked {
13167            self.display_map.update(cx, |map, _| map.masked = masked);
13168        }
13169        cx.notify()
13170    }
13171
13172    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13173        self.show_wrap_guides = Some(show_wrap_guides);
13174        cx.notify();
13175    }
13176
13177    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13178        self.show_indent_guides = Some(show_indent_guides);
13179        cx.notify();
13180    }
13181
13182    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13183        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13184            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13185                if let Some(dir) = file.abs_path(cx).parent() {
13186                    return Some(dir.to_owned());
13187                }
13188            }
13189
13190            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13191                return Some(project_path.path.to_path_buf());
13192            }
13193        }
13194
13195        None
13196    }
13197
13198    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13199        self.active_excerpt(cx)?
13200            .1
13201            .read(cx)
13202            .file()
13203            .and_then(|f| f.as_local())
13204    }
13205
13206    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13207        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13208            let buffer = buffer.read(cx);
13209            if let Some(project_path) = buffer.project_path(cx) {
13210                let project = self.project.as_ref()?.read(cx);
13211                project.absolute_path(&project_path, cx)
13212            } else {
13213                buffer
13214                    .file()
13215                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13216            }
13217        })
13218    }
13219
13220    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13221        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13222            let project_path = buffer.read(cx).project_path(cx)?;
13223            let project = self.project.as_ref()?.read(cx);
13224            let entry = project.entry_for_path(&project_path, cx)?;
13225            let path = entry.path.to_path_buf();
13226            Some(path)
13227        })
13228    }
13229
13230    pub fn reveal_in_finder(
13231        &mut self,
13232        _: &RevealInFileManager,
13233        _window: &mut Window,
13234        cx: &mut Context<Self>,
13235    ) {
13236        if let Some(target) = self.target_file(cx) {
13237            cx.reveal_path(&target.abs_path(cx));
13238        }
13239    }
13240
13241    pub fn copy_path(
13242        &mut self,
13243        _: &zed_actions::workspace::CopyPath,
13244        _window: &mut Window,
13245        cx: &mut Context<Self>,
13246    ) {
13247        if let Some(path) = self.target_file_abs_path(cx) {
13248            if let Some(path) = path.to_str() {
13249                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13250            }
13251        }
13252    }
13253
13254    pub fn copy_relative_path(
13255        &mut self,
13256        _: &zed_actions::workspace::CopyRelativePath,
13257        _window: &mut Window,
13258        cx: &mut Context<Self>,
13259    ) {
13260        if let Some(path) = self.target_file_path(cx) {
13261            if let Some(path) = path.to_str() {
13262                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13263            }
13264        }
13265    }
13266
13267    pub fn copy_file_name_without_extension(
13268        &mut self,
13269        _: &CopyFileNameWithoutExtension,
13270        _: &mut Window,
13271        cx: &mut Context<Self>,
13272    ) {
13273        if let Some(file) = self.target_file(cx) {
13274            if let Some(file_stem) = file.path().file_stem() {
13275                if let Some(name) = file_stem.to_str() {
13276                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13277                }
13278            }
13279        }
13280    }
13281
13282    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13283        if let Some(file) = self.target_file(cx) {
13284            if let Some(file_name) = file.path().file_name() {
13285                if let Some(name) = file_name.to_str() {
13286                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13287                }
13288            }
13289        }
13290    }
13291
13292    pub fn toggle_git_blame(
13293        &mut self,
13294        _: &ToggleGitBlame,
13295        window: &mut Window,
13296        cx: &mut Context<Self>,
13297    ) {
13298        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13299
13300        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13301            self.start_git_blame(true, window, cx);
13302        }
13303
13304        cx.notify();
13305    }
13306
13307    pub fn toggle_git_blame_inline(
13308        &mut self,
13309        _: &ToggleGitBlameInline,
13310        window: &mut Window,
13311        cx: &mut Context<Self>,
13312    ) {
13313        self.toggle_git_blame_inline_internal(true, window, cx);
13314        cx.notify();
13315    }
13316
13317    pub fn git_blame_inline_enabled(&self) -> bool {
13318        self.git_blame_inline_enabled
13319    }
13320
13321    pub fn toggle_selection_menu(
13322        &mut self,
13323        _: &ToggleSelectionMenu,
13324        _: &mut Window,
13325        cx: &mut Context<Self>,
13326    ) {
13327        self.show_selection_menu = self
13328            .show_selection_menu
13329            .map(|show_selections_menu| !show_selections_menu)
13330            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13331
13332        cx.notify();
13333    }
13334
13335    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13336        self.show_selection_menu
13337            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13338    }
13339
13340    fn start_git_blame(
13341        &mut self,
13342        user_triggered: bool,
13343        window: &mut Window,
13344        cx: &mut Context<Self>,
13345    ) {
13346        if let Some(project) = self.project.as_ref() {
13347            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13348                return;
13349            };
13350
13351            if buffer.read(cx).file().is_none() {
13352                return;
13353            }
13354
13355            let focused = self.focus_handle(cx).contains_focused(window, cx);
13356
13357            let project = project.clone();
13358            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13359            self.blame_subscription =
13360                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13361            self.blame = Some(blame);
13362        }
13363    }
13364
13365    fn toggle_git_blame_inline_internal(
13366        &mut self,
13367        user_triggered: bool,
13368        window: &mut Window,
13369        cx: &mut Context<Self>,
13370    ) {
13371        if self.git_blame_inline_enabled {
13372            self.git_blame_inline_enabled = false;
13373            self.show_git_blame_inline = false;
13374            self.show_git_blame_inline_delay_task.take();
13375        } else {
13376            self.git_blame_inline_enabled = true;
13377            self.start_git_blame_inline(user_triggered, window, cx);
13378        }
13379
13380        cx.notify();
13381    }
13382
13383    fn start_git_blame_inline(
13384        &mut self,
13385        user_triggered: bool,
13386        window: &mut Window,
13387        cx: &mut Context<Self>,
13388    ) {
13389        self.start_git_blame(user_triggered, window, cx);
13390
13391        if ProjectSettings::get_global(cx)
13392            .git
13393            .inline_blame_delay()
13394            .is_some()
13395        {
13396            self.start_inline_blame_timer(window, cx);
13397        } else {
13398            self.show_git_blame_inline = true
13399        }
13400    }
13401
13402    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13403        self.blame.as_ref()
13404    }
13405
13406    pub fn show_git_blame_gutter(&self) -> bool {
13407        self.show_git_blame_gutter
13408    }
13409
13410    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13411        self.show_git_blame_gutter && self.has_blame_entries(cx)
13412    }
13413
13414    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13415        self.show_git_blame_inline
13416            && self.focus_handle.is_focused(window)
13417            && !self.newest_selection_head_on_empty_line(cx)
13418            && self.has_blame_entries(cx)
13419    }
13420
13421    fn has_blame_entries(&self, cx: &App) -> bool {
13422        self.blame()
13423            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13424    }
13425
13426    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13427        let cursor_anchor = self.selections.newest_anchor().head();
13428
13429        let snapshot = self.buffer.read(cx).snapshot(cx);
13430        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13431
13432        snapshot.line_len(buffer_row) == 0
13433    }
13434
13435    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13436        let buffer_and_selection = maybe!({
13437            let selection = self.selections.newest::<Point>(cx);
13438            let selection_range = selection.range();
13439
13440            let multi_buffer = self.buffer().read(cx);
13441            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13442            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13443
13444            let (buffer, range, _) = if selection.reversed {
13445                buffer_ranges.first()
13446            } else {
13447                buffer_ranges.last()
13448            }?;
13449
13450            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13451                ..text::ToPoint::to_point(&range.end, &buffer).row;
13452            Some((
13453                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13454                selection,
13455            ))
13456        });
13457
13458        let Some((buffer, selection)) = buffer_and_selection else {
13459            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13460        };
13461
13462        let Some(project) = self.project.as_ref() else {
13463            return Task::ready(Err(anyhow!("editor does not have project")));
13464        };
13465
13466        project.update(cx, |project, cx| {
13467            project.get_permalink_to_line(&buffer, selection, cx)
13468        })
13469    }
13470
13471    pub fn copy_permalink_to_line(
13472        &mut self,
13473        _: &CopyPermalinkToLine,
13474        window: &mut Window,
13475        cx: &mut Context<Self>,
13476    ) {
13477        let permalink_task = self.get_permalink_to_line(cx);
13478        let workspace = self.workspace();
13479
13480        cx.spawn_in(window, |_, mut cx| async move {
13481            match permalink_task.await {
13482                Ok(permalink) => {
13483                    cx.update(|_, cx| {
13484                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13485                    })
13486                    .ok();
13487                }
13488                Err(err) => {
13489                    let message = format!("Failed to copy permalink: {err}");
13490
13491                    Err::<(), anyhow::Error>(err).log_err();
13492
13493                    if let Some(workspace) = workspace {
13494                        workspace
13495                            .update_in(&mut cx, |workspace, _, cx| {
13496                                struct CopyPermalinkToLine;
13497
13498                                workspace.show_toast(
13499                                    Toast::new(
13500                                        NotificationId::unique::<CopyPermalinkToLine>(),
13501                                        message,
13502                                    ),
13503                                    cx,
13504                                )
13505                            })
13506                            .ok();
13507                    }
13508                }
13509            }
13510        })
13511        .detach();
13512    }
13513
13514    pub fn copy_file_location(
13515        &mut self,
13516        _: &CopyFileLocation,
13517        _: &mut Window,
13518        cx: &mut Context<Self>,
13519    ) {
13520        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13521        if let Some(file) = self.target_file(cx) {
13522            if let Some(path) = file.path().to_str() {
13523                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13524            }
13525        }
13526    }
13527
13528    pub fn open_permalink_to_line(
13529        &mut self,
13530        _: &OpenPermalinkToLine,
13531        window: &mut Window,
13532        cx: &mut Context<Self>,
13533    ) {
13534        let permalink_task = self.get_permalink_to_line(cx);
13535        let workspace = self.workspace();
13536
13537        cx.spawn_in(window, |_, mut cx| async move {
13538            match permalink_task.await {
13539                Ok(permalink) => {
13540                    cx.update(|_, cx| {
13541                        cx.open_url(permalink.as_ref());
13542                    })
13543                    .ok();
13544                }
13545                Err(err) => {
13546                    let message = format!("Failed to open permalink: {err}");
13547
13548                    Err::<(), anyhow::Error>(err).log_err();
13549
13550                    if let Some(workspace) = workspace {
13551                        workspace
13552                            .update(&mut cx, |workspace, cx| {
13553                                struct OpenPermalinkToLine;
13554
13555                                workspace.show_toast(
13556                                    Toast::new(
13557                                        NotificationId::unique::<OpenPermalinkToLine>(),
13558                                        message,
13559                                    ),
13560                                    cx,
13561                                )
13562                            })
13563                            .ok();
13564                    }
13565                }
13566            }
13567        })
13568        .detach();
13569    }
13570
13571    pub fn insert_uuid_v4(
13572        &mut self,
13573        _: &InsertUuidV4,
13574        window: &mut Window,
13575        cx: &mut Context<Self>,
13576    ) {
13577        self.insert_uuid(UuidVersion::V4, window, cx);
13578    }
13579
13580    pub fn insert_uuid_v7(
13581        &mut self,
13582        _: &InsertUuidV7,
13583        window: &mut Window,
13584        cx: &mut Context<Self>,
13585    ) {
13586        self.insert_uuid(UuidVersion::V7, window, cx);
13587    }
13588
13589    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13590        self.transact(window, cx, |this, window, cx| {
13591            let edits = this
13592                .selections
13593                .all::<Point>(cx)
13594                .into_iter()
13595                .map(|selection| {
13596                    let uuid = match version {
13597                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13598                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13599                    };
13600
13601                    (selection.range(), uuid.to_string())
13602                });
13603            this.edit(edits, cx);
13604            this.refresh_inline_completion(true, false, window, cx);
13605        });
13606    }
13607
13608    pub fn open_selections_in_multibuffer(
13609        &mut self,
13610        _: &OpenSelectionsInMultibuffer,
13611        window: &mut Window,
13612        cx: &mut Context<Self>,
13613    ) {
13614        let multibuffer = self.buffer.read(cx);
13615
13616        let Some(buffer) = multibuffer.as_singleton() else {
13617            return;
13618        };
13619
13620        let Some(workspace) = self.workspace() else {
13621            return;
13622        };
13623
13624        let locations = self
13625            .selections
13626            .disjoint_anchors()
13627            .iter()
13628            .map(|range| Location {
13629                buffer: buffer.clone(),
13630                range: range.start.text_anchor..range.end.text_anchor,
13631            })
13632            .collect::<Vec<_>>();
13633
13634        let title = multibuffer.title(cx).to_string();
13635
13636        cx.spawn_in(window, |_, mut cx| async move {
13637            workspace.update_in(&mut cx, |workspace, window, cx| {
13638                Self::open_locations_in_multibuffer(
13639                    workspace,
13640                    locations,
13641                    format!("Selections for '{title}'"),
13642                    false,
13643                    MultibufferSelectionMode::All,
13644                    window,
13645                    cx,
13646                );
13647            })
13648        })
13649        .detach();
13650    }
13651
13652    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13653    /// last highlight added will be used.
13654    ///
13655    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13656    pub fn highlight_rows<T: 'static>(
13657        &mut self,
13658        range: Range<Anchor>,
13659        color: Hsla,
13660        should_autoscroll: bool,
13661        cx: &mut Context<Self>,
13662    ) {
13663        let snapshot = self.buffer().read(cx).snapshot(cx);
13664        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13665        let ix = row_highlights.binary_search_by(|highlight| {
13666            Ordering::Equal
13667                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13668                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13669        });
13670
13671        if let Err(mut ix) = ix {
13672            let index = post_inc(&mut self.highlight_order);
13673
13674            // If this range intersects with the preceding highlight, then merge it with
13675            // the preceding highlight. Otherwise insert a new highlight.
13676            let mut merged = false;
13677            if ix > 0 {
13678                let prev_highlight = &mut row_highlights[ix - 1];
13679                if prev_highlight
13680                    .range
13681                    .end
13682                    .cmp(&range.start, &snapshot)
13683                    .is_ge()
13684                {
13685                    ix -= 1;
13686                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13687                        prev_highlight.range.end = range.end;
13688                    }
13689                    merged = true;
13690                    prev_highlight.index = index;
13691                    prev_highlight.color = color;
13692                    prev_highlight.should_autoscroll = should_autoscroll;
13693                }
13694            }
13695
13696            if !merged {
13697                row_highlights.insert(
13698                    ix,
13699                    RowHighlight {
13700                        range: range.clone(),
13701                        index,
13702                        color,
13703                        should_autoscroll,
13704                    },
13705                );
13706            }
13707
13708            // If any of the following highlights intersect with this one, merge them.
13709            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13710                let highlight = &row_highlights[ix];
13711                if next_highlight
13712                    .range
13713                    .start
13714                    .cmp(&highlight.range.end, &snapshot)
13715                    .is_le()
13716                {
13717                    if next_highlight
13718                        .range
13719                        .end
13720                        .cmp(&highlight.range.end, &snapshot)
13721                        .is_gt()
13722                    {
13723                        row_highlights[ix].range.end = next_highlight.range.end;
13724                    }
13725                    row_highlights.remove(ix + 1);
13726                } else {
13727                    break;
13728                }
13729            }
13730        }
13731    }
13732
13733    /// Remove any highlighted row ranges of the given type that intersect the
13734    /// given ranges.
13735    pub fn remove_highlighted_rows<T: 'static>(
13736        &mut self,
13737        ranges_to_remove: Vec<Range<Anchor>>,
13738        cx: &mut Context<Self>,
13739    ) {
13740        let snapshot = self.buffer().read(cx).snapshot(cx);
13741        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13742        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13743        row_highlights.retain(|highlight| {
13744            while let Some(range_to_remove) = ranges_to_remove.peek() {
13745                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13746                    Ordering::Less | Ordering::Equal => {
13747                        ranges_to_remove.next();
13748                    }
13749                    Ordering::Greater => {
13750                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13751                            Ordering::Less | Ordering::Equal => {
13752                                return false;
13753                            }
13754                            Ordering::Greater => break,
13755                        }
13756                    }
13757                }
13758            }
13759
13760            true
13761        })
13762    }
13763
13764    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13765    pub fn clear_row_highlights<T: 'static>(&mut self) {
13766        self.highlighted_rows.remove(&TypeId::of::<T>());
13767    }
13768
13769    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13770    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13771        self.highlighted_rows
13772            .get(&TypeId::of::<T>())
13773            .map_or(&[] as &[_], |vec| vec.as_slice())
13774            .iter()
13775            .map(|highlight| (highlight.range.clone(), highlight.color))
13776    }
13777
13778    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13779    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13780    /// Allows to ignore certain kinds of highlights.
13781    pub fn highlighted_display_rows(
13782        &self,
13783        window: &mut Window,
13784        cx: &mut App,
13785    ) -> BTreeMap<DisplayRow, Background> {
13786        let snapshot = self.snapshot(window, cx);
13787        let mut used_highlight_orders = HashMap::default();
13788        self.highlighted_rows
13789            .iter()
13790            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13791            .fold(
13792                BTreeMap::<DisplayRow, Background>::new(),
13793                |mut unique_rows, highlight| {
13794                    let start = highlight.range.start.to_display_point(&snapshot);
13795                    let end = highlight.range.end.to_display_point(&snapshot);
13796                    let start_row = start.row().0;
13797                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13798                        && end.column() == 0
13799                    {
13800                        end.row().0.saturating_sub(1)
13801                    } else {
13802                        end.row().0
13803                    };
13804                    for row in start_row..=end_row {
13805                        let used_index =
13806                            used_highlight_orders.entry(row).or_insert(highlight.index);
13807                        if highlight.index >= *used_index {
13808                            *used_index = highlight.index;
13809                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13810                        }
13811                    }
13812                    unique_rows
13813                },
13814            )
13815    }
13816
13817    pub fn highlighted_display_row_for_autoscroll(
13818        &self,
13819        snapshot: &DisplaySnapshot,
13820    ) -> Option<DisplayRow> {
13821        self.highlighted_rows
13822            .values()
13823            .flat_map(|highlighted_rows| highlighted_rows.iter())
13824            .filter_map(|highlight| {
13825                if highlight.should_autoscroll {
13826                    Some(highlight.range.start.to_display_point(snapshot).row())
13827                } else {
13828                    None
13829                }
13830            })
13831            .min()
13832    }
13833
13834    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13835        self.highlight_background::<SearchWithinRange>(
13836            ranges,
13837            |colors| colors.editor_document_highlight_read_background,
13838            cx,
13839        )
13840    }
13841
13842    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13843        self.breadcrumb_header = Some(new_header);
13844    }
13845
13846    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13847        self.clear_background_highlights::<SearchWithinRange>(cx);
13848    }
13849
13850    pub fn highlight_background<T: 'static>(
13851        &mut self,
13852        ranges: &[Range<Anchor>],
13853        color_fetcher: fn(&ThemeColors) -> Hsla,
13854        cx: &mut Context<Self>,
13855    ) {
13856        self.background_highlights
13857            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13858        self.scrollbar_marker_state.dirty = true;
13859        cx.notify();
13860    }
13861
13862    pub fn clear_background_highlights<T: 'static>(
13863        &mut self,
13864        cx: &mut Context<Self>,
13865    ) -> Option<BackgroundHighlight> {
13866        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13867        if !text_highlights.1.is_empty() {
13868            self.scrollbar_marker_state.dirty = true;
13869            cx.notify();
13870        }
13871        Some(text_highlights)
13872    }
13873
13874    pub fn highlight_gutter<T: 'static>(
13875        &mut self,
13876        ranges: &[Range<Anchor>],
13877        color_fetcher: fn(&App) -> Hsla,
13878        cx: &mut Context<Self>,
13879    ) {
13880        self.gutter_highlights
13881            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13882        cx.notify();
13883    }
13884
13885    pub fn clear_gutter_highlights<T: 'static>(
13886        &mut self,
13887        cx: &mut Context<Self>,
13888    ) -> Option<GutterHighlight> {
13889        cx.notify();
13890        self.gutter_highlights.remove(&TypeId::of::<T>())
13891    }
13892
13893    #[cfg(feature = "test-support")]
13894    pub fn all_text_background_highlights(
13895        &self,
13896        window: &mut Window,
13897        cx: &mut Context<Self>,
13898    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13899        let snapshot = self.snapshot(window, cx);
13900        let buffer = &snapshot.buffer_snapshot;
13901        let start = buffer.anchor_before(0);
13902        let end = buffer.anchor_after(buffer.len());
13903        let theme = cx.theme().colors();
13904        self.background_highlights_in_range(start..end, &snapshot, theme)
13905    }
13906
13907    #[cfg(feature = "test-support")]
13908    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13909        let snapshot = self.buffer().read(cx).snapshot(cx);
13910
13911        let highlights = self
13912            .background_highlights
13913            .get(&TypeId::of::<items::BufferSearchHighlights>());
13914
13915        if let Some((_color, ranges)) = highlights {
13916            ranges
13917                .iter()
13918                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13919                .collect_vec()
13920        } else {
13921            vec![]
13922        }
13923    }
13924
13925    fn document_highlights_for_position<'a>(
13926        &'a self,
13927        position: Anchor,
13928        buffer: &'a MultiBufferSnapshot,
13929    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13930        let read_highlights = self
13931            .background_highlights
13932            .get(&TypeId::of::<DocumentHighlightRead>())
13933            .map(|h| &h.1);
13934        let write_highlights = self
13935            .background_highlights
13936            .get(&TypeId::of::<DocumentHighlightWrite>())
13937            .map(|h| &h.1);
13938        let left_position = position.bias_left(buffer);
13939        let right_position = position.bias_right(buffer);
13940        read_highlights
13941            .into_iter()
13942            .chain(write_highlights)
13943            .flat_map(move |ranges| {
13944                let start_ix = match ranges.binary_search_by(|probe| {
13945                    let cmp = probe.end.cmp(&left_position, buffer);
13946                    if cmp.is_ge() {
13947                        Ordering::Greater
13948                    } else {
13949                        Ordering::Less
13950                    }
13951                }) {
13952                    Ok(i) | Err(i) => i,
13953                };
13954
13955                ranges[start_ix..]
13956                    .iter()
13957                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13958            })
13959    }
13960
13961    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13962        self.background_highlights
13963            .get(&TypeId::of::<T>())
13964            .map_or(false, |(_, highlights)| !highlights.is_empty())
13965    }
13966
13967    pub fn background_highlights_in_range(
13968        &self,
13969        search_range: Range<Anchor>,
13970        display_snapshot: &DisplaySnapshot,
13971        theme: &ThemeColors,
13972    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13973        let mut results = Vec::new();
13974        for (color_fetcher, ranges) in self.background_highlights.values() {
13975            let color = color_fetcher(theme);
13976            let start_ix = match ranges.binary_search_by(|probe| {
13977                let cmp = probe
13978                    .end
13979                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13980                if cmp.is_gt() {
13981                    Ordering::Greater
13982                } else {
13983                    Ordering::Less
13984                }
13985            }) {
13986                Ok(i) | Err(i) => i,
13987            };
13988            for range in &ranges[start_ix..] {
13989                if range
13990                    .start
13991                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13992                    .is_ge()
13993                {
13994                    break;
13995                }
13996
13997                let start = range.start.to_display_point(display_snapshot);
13998                let end = range.end.to_display_point(display_snapshot);
13999                results.push((start..end, color))
14000            }
14001        }
14002        results
14003    }
14004
14005    pub fn background_highlight_row_ranges<T: 'static>(
14006        &self,
14007        search_range: Range<Anchor>,
14008        display_snapshot: &DisplaySnapshot,
14009        count: usize,
14010    ) -> Vec<RangeInclusive<DisplayPoint>> {
14011        let mut results = Vec::new();
14012        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14013            return vec![];
14014        };
14015
14016        let start_ix = match ranges.binary_search_by(|probe| {
14017            let cmp = probe
14018                .end
14019                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14020            if cmp.is_gt() {
14021                Ordering::Greater
14022            } else {
14023                Ordering::Less
14024            }
14025        }) {
14026            Ok(i) | Err(i) => i,
14027        };
14028        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14029            if let (Some(start_display), Some(end_display)) = (start, end) {
14030                results.push(
14031                    start_display.to_display_point(display_snapshot)
14032                        ..=end_display.to_display_point(display_snapshot),
14033                );
14034            }
14035        };
14036        let mut start_row: Option<Point> = None;
14037        let mut end_row: Option<Point> = None;
14038        if ranges.len() > count {
14039            return Vec::new();
14040        }
14041        for range in &ranges[start_ix..] {
14042            if range
14043                .start
14044                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14045                .is_ge()
14046            {
14047                break;
14048            }
14049            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14050            if let Some(current_row) = &end_row {
14051                if end.row == current_row.row {
14052                    continue;
14053                }
14054            }
14055            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14056            if start_row.is_none() {
14057                assert_eq!(end_row, None);
14058                start_row = Some(start);
14059                end_row = Some(end);
14060                continue;
14061            }
14062            if let Some(current_end) = end_row.as_mut() {
14063                if start.row > current_end.row + 1 {
14064                    push_region(start_row, end_row);
14065                    start_row = Some(start);
14066                    end_row = Some(end);
14067                } else {
14068                    // Merge two hunks.
14069                    *current_end = end;
14070                }
14071            } else {
14072                unreachable!();
14073            }
14074        }
14075        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14076        push_region(start_row, end_row);
14077        results
14078    }
14079
14080    pub fn gutter_highlights_in_range(
14081        &self,
14082        search_range: Range<Anchor>,
14083        display_snapshot: &DisplaySnapshot,
14084        cx: &App,
14085    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14086        let mut results = Vec::new();
14087        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14088            let color = color_fetcher(cx);
14089            let start_ix = match ranges.binary_search_by(|probe| {
14090                let cmp = probe
14091                    .end
14092                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14093                if cmp.is_gt() {
14094                    Ordering::Greater
14095                } else {
14096                    Ordering::Less
14097                }
14098            }) {
14099                Ok(i) | Err(i) => i,
14100            };
14101            for range in &ranges[start_ix..] {
14102                if range
14103                    .start
14104                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14105                    .is_ge()
14106                {
14107                    break;
14108                }
14109
14110                let start = range.start.to_display_point(display_snapshot);
14111                let end = range.end.to_display_point(display_snapshot);
14112                results.push((start..end, color))
14113            }
14114        }
14115        results
14116    }
14117
14118    /// Get the text ranges corresponding to the redaction query
14119    pub fn redacted_ranges(
14120        &self,
14121        search_range: Range<Anchor>,
14122        display_snapshot: &DisplaySnapshot,
14123        cx: &App,
14124    ) -> Vec<Range<DisplayPoint>> {
14125        display_snapshot
14126            .buffer_snapshot
14127            .redacted_ranges(search_range, |file| {
14128                if let Some(file) = file {
14129                    file.is_private()
14130                        && EditorSettings::get(
14131                            Some(SettingsLocation {
14132                                worktree_id: file.worktree_id(cx),
14133                                path: file.path().as_ref(),
14134                            }),
14135                            cx,
14136                        )
14137                        .redact_private_values
14138                } else {
14139                    false
14140                }
14141            })
14142            .map(|range| {
14143                range.start.to_display_point(display_snapshot)
14144                    ..range.end.to_display_point(display_snapshot)
14145            })
14146            .collect()
14147    }
14148
14149    pub fn highlight_text<T: 'static>(
14150        &mut self,
14151        ranges: Vec<Range<Anchor>>,
14152        style: HighlightStyle,
14153        cx: &mut Context<Self>,
14154    ) {
14155        self.display_map.update(cx, |map, _| {
14156            map.highlight_text(TypeId::of::<T>(), ranges, style)
14157        });
14158        cx.notify();
14159    }
14160
14161    pub(crate) fn highlight_inlays<T: 'static>(
14162        &mut self,
14163        highlights: Vec<InlayHighlight>,
14164        style: HighlightStyle,
14165        cx: &mut Context<Self>,
14166    ) {
14167        self.display_map.update(cx, |map, _| {
14168            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14169        });
14170        cx.notify();
14171    }
14172
14173    pub fn text_highlights<'a, T: 'static>(
14174        &'a self,
14175        cx: &'a App,
14176    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14177        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14178    }
14179
14180    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14181        let cleared = self
14182            .display_map
14183            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14184        if cleared {
14185            cx.notify();
14186        }
14187    }
14188
14189    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14190        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14191            && self.focus_handle.is_focused(window)
14192    }
14193
14194    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14195        self.show_cursor_when_unfocused = is_enabled;
14196        cx.notify();
14197    }
14198
14199    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14200        cx.notify();
14201    }
14202
14203    fn on_buffer_event(
14204        &mut self,
14205        multibuffer: &Entity<MultiBuffer>,
14206        event: &multi_buffer::Event,
14207        window: &mut Window,
14208        cx: &mut Context<Self>,
14209    ) {
14210        match event {
14211            multi_buffer::Event::Edited {
14212                singleton_buffer_edited,
14213                edited_buffer: buffer_edited,
14214            } => {
14215                self.scrollbar_marker_state.dirty = true;
14216                self.active_indent_guides_state.dirty = true;
14217                self.refresh_active_diagnostics(cx);
14218                self.refresh_code_actions(window, cx);
14219                if self.has_active_inline_completion() {
14220                    self.update_visible_inline_completion(window, cx);
14221                }
14222                if let Some(buffer) = buffer_edited {
14223                    let buffer_id = buffer.read(cx).remote_id();
14224                    if !self.registered_buffers.contains_key(&buffer_id) {
14225                        if let Some(project) = self.project.as_ref() {
14226                            project.update(cx, |project, cx| {
14227                                self.registered_buffers.insert(
14228                                    buffer_id,
14229                                    project.register_buffer_with_language_servers(&buffer, cx),
14230                                );
14231                            })
14232                        }
14233                    }
14234                }
14235                cx.emit(EditorEvent::BufferEdited);
14236                cx.emit(SearchEvent::MatchesInvalidated);
14237                if *singleton_buffer_edited {
14238                    if let Some(project) = &self.project {
14239                        #[allow(clippy::mutable_key_type)]
14240                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14241                            multibuffer
14242                                .all_buffers()
14243                                .into_iter()
14244                                .filter_map(|buffer| {
14245                                    buffer.update(cx, |buffer, cx| {
14246                                        let language = buffer.language()?;
14247                                        let should_discard = project.update(cx, |project, cx| {
14248                                            project.is_local()
14249                                                && !project.has_language_servers_for(buffer, cx)
14250                                        });
14251                                        should_discard.not().then_some(language.clone())
14252                                    })
14253                                })
14254                                .collect::<HashSet<_>>()
14255                        });
14256                        if !languages_affected.is_empty() {
14257                            self.refresh_inlay_hints(
14258                                InlayHintRefreshReason::BufferEdited(languages_affected),
14259                                cx,
14260                            );
14261                        }
14262                    }
14263                }
14264
14265                let Some(project) = &self.project else { return };
14266                let (telemetry, is_via_ssh) = {
14267                    let project = project.read(cx);
14268                    let telemetry = project.client().telemetry().clone();
14269                    let is_via_ssh = project.is_via_ssh();
14270                    (telemetry, is_via_ssh)
14271                };
14272                refresh_linked_ranges(self, window, cx);
14273                telemetry.log_edit_event("editor", is_via_ssh);
14274            }
14275            multi_buffer::Event::ExcerptsAdded {
14276                buffer,
14277                predecessor,
14278                excerpts,
14279            } => {
14280                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14281                let buffer_id = buffer.read(cx).remote_id();
14282                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14283                    if let Some(project) = &self.project {
14284                        get_uncommitted_diff_for_buffer(
14285                            project,
14286                            [buffer.clone()],
14287                            self.buffer.clone(),
14288                            cx,
14289                        )
14290                        .detach();
14291                    }
14292                }
14293                cx.emit(EditorEvent::ExcerptsAdded {
14294                    buffer: buffer.clone(),
14295                    predecessor: *predecessor,
14296                    excerpts: excerpts.clone(),
14297                });
14298                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14299            }
14300            multi_buffer::Event::ExcerptsRemoved { ids } => {
14301                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14302                let buffer = self.buffer.read(cx);
14303                self.registered_buffers
14304                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14305                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14306            }
14307            multi_buffer::Event::ExcerptsEdited { ids } => {
14308                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14309            }
14310            multi_buffer::Event::ExcerptsExpanded { ids } => {
14311                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14312                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14313            }
14314            multi_buffer::Event::Reparsed(buffer_id) => {
14315                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14316
14317                cx.emit(EditorEvent::Reparsed(*buffer_id));
14318            }
14319            multi_buffer::Event::DiffHunksToggled => {
14320                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14321            }
14322            multi_buffer::Event::LanguageChanged(buffer_id) => {
14323                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14324                cx.emit(EditorEvent::Reparsed(*buffer_id));
14325                cx.notify();
14326            }
14327            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14328            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14329            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14330                cx.emit(EditorEvent::TitleChanged)
14331            }
14332            // multi_buffer::Event::DiffBaseChanged => {
14333            //     self.scrollbar_marker_state.dirty = true;
14334            //     cx.emit(EditorEvent::DiffBaseChanged);
14335            //     cx.notify();
14336            // }
14337            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14338            multi_buffer::Event::DiagnosticsUpdated => {
14339                self.refresh_active_diagnostics(cx);
14340                self.scrollbar_marker_state.dirty = true;
14341                cx.notify();
14342            }
14343            _ => {}
14344        };
14345    }
14346
14347    fn on_display_map_changed(
14348        &mut self,
14349        _: Entity<DisplayMap>,
14350        _: &mut Window,
14351        cx: &mut Context<Self>,
14352    ) {
14353        cx.notify();
14354    }
14355
14356    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14357        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14358        self.refresh_inline_completion(true, false, window, cx);
14359        self.refresh_inlay_hints(
14360            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14361                self.selections.newest_anchor().head(),
14362                &self.buffer.read(cx).snapshot(cx),
14363                cx,
14364            )),
14365            cx,
14366        );
14367
14368        let old_cursor_shape = self.cursor_shape;
14369
14370        {
14371            let editor_settings = EditorSettings::get_global(cx);
14372            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14373            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14374            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14375        }
14376
14377        if old_cursor_shape != self.cursor_shape {
14378            cx.emit(EditorEvent::CursorShapeChanged);
14379        }
14380
14381        let project_settings = ProjectSettings::get_global(cx);
14382        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14383
14384        if self.mode == EditorMode::Full {
14385            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14386            if self.git_blame_inline_enabled != inline_blame_enabled {
14387                self.toggle_git_blame_inline_internal(false, window, cx);
14388            }
14389        }
14390
14391        cx.notify();
14392    }
14393
14394    pub fn set_searchable(&mut self, searchable: bool) {
14395        self.searchable = searchable;
14396    }
14397
14398    pub fn searchable(&self) -> bool {
14399        self.searchable
14400    }
14401
14402    fn open_proposed_changes_editor(
14403        &mut self,
14404        _: &OpenProposedChangesEditor,
14405        window: &mut Window,
14406        cx: &mut Context<Self>,
14407    ) {
14408        let Some(workspace) = self.workspace() else {
14409            cx.propagate();
14410            return;
14411        };
14412
14413        let selections = self.selections.all::<usize>(cx);
14414        let multi_buffer = self.buffer.read(cx);
14415        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14416        let mut new_selections_by_buffer = HashMap::default();
14417        for selection in selections {
14418            for (buffer, range, _) in
14419                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14420            {
14421                let mut range = range.to_point(buffer);
14422                range.start.column = 0;
14423                range.end.column = buffer.line_len(range.end.row);
14424                new_selections_by_buffer
14425                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14426                    .or_insert(Vec::new())
14427                    .push(range)
14428            }
14429        }
14430
14431        let proposed_changes_buffers = new_selections_by_buffer
14432            .into_iter()
14433            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14434            .collect::<Vec<_>>();
14435        let proposed_changes_editor = cx.new(|cx| {
14436            ProposedChangesEditor::new(
14437                "Proposed changes",
14438                proposed_changes_buffers,
14439                self.project.clone(),
14440                window,
14441                cx,
14442            )
14443        });
14444
14445        window.defer(cx, move |window, cx| {
14446            workspace.update(cx, |workspace, cx| {
14447                workspace.active_pane().update(cx, |pane, cx| {
14448                    pane.add_item(
14449                        Box::new(proposed_changes_editor),
14450                        true,
14451                        true,
14452                        None,
14453                        window,
14454                        cx,
14455                    );
14456                });
14457            });
14458        });
14459    }
14460
14461    pub fn open_excerpts_in_split(
14462        &mut self,
14463        _: &OpenExcerptsSplit,
14464        window: &mut Window,
14465        cx: &mut Context<Self>,
14466    ) {
14467        self.open_excerpts_common(None, true, window, cx)
14468    }
14469
14470    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14471        self.open_excerpts_common(None, false, window, cx)
14472    }
14473
14474    fn open_excerpts_common(
14475        &mut self,
14476        jump_data: Option<JumpData>,
14477        split: bool,
14478        window: &mut Window,
14479        cx: &mut Context<Self>,
14480    ) {
14481        let Some(workspace) = self.workspace() else {
14482            cx.propagate();
14483            return;
14484        };
14485
14486        if self.buffer.read(cx).is_singleton() {
14487            cx.propagate();
14488            return;
14489        }
14490
14491        let mut new_selections_by_buffer = HashMap::default();
14492        match &jump_data {
14493            Some(JumpData::MultiBufferPoint {
14494                excerpt_id,
14495                position,
14496                anchor,
14497                line_offset_from_top,
14498            }) => {
14499                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14500                if let Some(buffer) = multi_buffer_snapshot
14501                    .buffer_id_for_excerpt(*excerpt_id)
14502                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14503                {
14504                    let buffer_snapshot = buffer.read(cx).snapshot();
14505                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14506                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14507                    } else {
14508                        buffer_snapshot.clip_point(*position, Bias::Left)
14509                    };
14510                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14511                    new_selections_by_buffer.insert(
14512                        buffer,
14513                        (
14514                            vec![jump_to_offset..jump_to_offset],
14515                            Some(*line_offset_from_top),
14516                        ),
14517                    );
14518                }
14519            }
14520            Some(JumpData::MultiBufferRow {
14521                row,
14522                line_offset_from_top,
14523            }) => {
14524                let point = MultiBufferPoint::new(row.0, 0);
14525                if let Some((buffer, buffer_point, _)) =
14526                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14527                {
14528                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14529                    new_selections_by_buffer
14530                        .entry(buffer)
14531                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14532                        .0
14533                        .push(buffer_offset..buffer_offset)
14534                }
14535            }
14536            None => {
14537                let selections = self.selections.all::<usize>(cx);
14538                let multi_buffer = self.buffer.read(cx);
14539                for selection in selections {
14540                    for (buffer, mut range, _) in multi_buffer
14541                        .snapshot(cx)
14542                        .range_to_buffer_ranges(selection.range())
14543                    {
14544                        // When editing branch buffers, jump to the corresponding location
14545                        // in their base buffer.
14546                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14547                        let buffer = buffer_handle.read(cx);
14548                        if let Some(base_buffer) = buffer.base_buffer() {
14549                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14550                            buffer_handle = base_buffer;
14551                        }
14552
14553                        if selection.reversed {
14554                            mem::swap(&mut range.start, &mut range.end);
14555                        }
14556                        new_selections_by_buffer
14557                            .entry(buffer_handle)
14558                            .or_insert((Vec::new(), None))
14559                            .0
14560                            .push(range)
14561                    }
14562                }
14563            }
14564        }
14565
14566        if new_selections_by_buffer.is_empty() {
14567            return;
14568        }
14569
14570        // We defer the pane interaction because we ourselves are a workspace item
14571        // and activating a new item causes the pane to call a method on us reentrantly,
14572        // which panics if we're on the stack.
14573        window.defer(cx, move |window, cx| {
14574            workspace.update(cx, |workspace, cx| {
14575                let pane = if split {
14576                    workspace.adjacent_pane(window, cx)
14577                } else {
14578                    workspace.active_pane().clone()
14579                };
14580
14581                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14582                    let editor = buffer
14583                        .read(cx)
14584                        .file()
14585                        .is_none()
14586                        .then(|| {
14587                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14588                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14589                            // Instead, we try to activate the existing editor in the pane first.
14590                            let (editor, pane_item_index) =
14591                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14592                                    let editor = item.downcast::<Editor>()?;
14593                                    let singleton_buffer =
14594                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14595                                    if singleton_buffer == buffer {
14596                                        Some((editor, i))
14597                                    } else {
14598                                        None
14599                                    }
14600                                })?;
14601                            pane.update(cx, |pane, cx| {
14602                                pane.activate_item(pane_item_index, true, true, window, cx)
14603                            });
14604                            Some(editor)
14605                        })
14606                        .flatten()
14607                        .unwrap_or_else(|| {
14608                            workspace.open_project_item::<Self>(
14609                                pane.clone(),
14610                                buffer,
14611                                true,
14612                                true,
14613                                window,
14614                                cx,
14615                            )
14616                        });
14617
14618                    editor.update(cx, |editor, cx| {
14619                        let autoscroll = match scroll_offset {
14620                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14621                            None => Autoscroll::newest(),
14622                        };
14623                        let nav_history = editor.nav_history.take();
14624                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14625                            s.select_ranges(ranges);
14626                        });
14627                        editor.nav_history = nav_history;
14628                    });
14629                }
14630            })
14631        });
14632    }
14633
14634    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14635        let snapshot = self.buffer.read(cx).read(cx);
14636        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14637        Some(
14638            ranges
14639                .iter()
14640                .map(move |range| {
14641                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14642                })
14643                .collect(),
14644        )
14645    }
14646
14647    fn selection_replacement_ranges(
14648        &self,
14649        range: Range<OffsetUtf16>,
14650        cx: &mut App,
14651    ) -> Vec<Range<OffsetUtf16>> {
14652        let selections = self.selections.all::<OffsetUtf16>(cx);
14653        let newest_selection = selections
14654            .iter()
14655            .max_by_key(|selection| selection.id)
14656            .unwrap();
14657        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14658        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14659        let snapshot = self.buffer.read(cx).read(cx);
14660        selections
14661            .into_iter()
14662            .map(|mut selection| {
14663                selection.start.0 =
14664                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14665                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14666                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14667                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14668            })
14669            .collect()
14670    }
14671
14672    fn report_editor_event(
14673        &self,
14674        event_type: &'static str,
14675        file_extension: Option<String>,
14676        cx: &App,
14677    ) {
14678        if cfg!(any(test, feature = "test-support")) {
14679            return;
14680        }
14681
14682        let Some(project) = &self.project else { return };
14683
14684        // If None, we are in a file without an extension
14685        let file = self
14686            .buffer
14687            .read(cx)
14688            .as_singleton()
14689            .and_then(|b| b.read(cx).file());
14690        let file_extension = file_extension.or(file
14691            .as_ref()
14692            .and_then(|file| Path::new(file.file_name(cx)).extension())
14693            .and_then(|e| e.to_str())
14694            .map(|a| a.to_string()));
14695
14696        let vim_mode = cx
14697            .global::<SettingsStore>()
14698            .raw_user_settings()
14699            .get("vim_mode")
14700            == Some(&serde_json::Value::Bool(true));
14701
14702        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14703        let copilot_enabled = edit_predictions_provider
14704            == language::language_settings::EditPredictionProvider::Copilot;
14705        let copilot_enabled_for_language = self
14706            .buffer
14707            .read(cx)
14708            .settings_at(0, cx)
14709            .show_edit_predictions;
14710
14711        let project = project.read(cx);
14712        telemetry::event!(
14713            event_type,
14714            file_extension,
14715            vim_mode,
14716            copilot_enabled,
14717            copilot_enabled_for_language,
14718            edit_predictions_provider,
14719            is_via_ssh = project.is_via_ssh(),
14720        );
14721    }
14722
14723    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14724    /// with each line being an array of {text, highlight} objects.
14725    fn copy_highlight_json(
14726        &mut self,
14727        _: &CopyHighlightJson,
14728        window: &mut Window,
14729        cx: &mut Context<Self>,
14730    ) {
14731        #[derive(Serialize)]
14732        struct Chunk<'a> {
14733            text: String,
14734            highlight: Option<&'a str>,
14735        }
14736
14737        let snapshot = self.buffer.read(cx).snapshot(cx);
14738        let range = self
14739            .selected_text_range(false, window, cx)
14740            .and_then(|selection| {
14741                if selection.range.is_empty() {
14742                    None
14743                } else {
14744                    Some(selection.range)
14745                }
14746            })
14747            .unwrap_or_else(|| 0..snapshot.len());
14748
14749        let chunks = snapshot.chunks(range, true);
14750        let mut lines = Vec::new();
14751        let mut line: VecDeque<Chunk> = VecDeque::new();
14752
14753        let Some(style) = self.style.as_ref() else {
14754            return;
14755        };
14756
14757        for chunk in chunks {
14758            let highlight = chunk
14759                .syntax_highlight_id
14760                .and_then(|id| id.name(&style.syntax));
14761            let mut chunk_lines = chunk.text.split('\n').peekable();
14762            while let Some(text) = chunk_lines.next() {
14763                let mut merged_with_last_token = false;
14764                if let Some(last_token) = line.back_mut() {
14765                    if last_token.highlight == highlight {
14766                        last_token.text.push_str(text);
14767                        merged_with_last_token = true;
14768                    }
14769                }
14770
14771                if !merged_with_last_token {
14772                    line.push_back(Chunk {
14773                        text: text.into(),
14774                        highlight,
14775                    });
14776                }
14777
14778                if chunk_lines.peek().is_some() {
14779                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14780                        line.pop_front();
14781                    }
14782                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14783                        line.pop_back();
14784                    }
14785
14786                    lines.push(mem::take(&mut line));
14787                }
14788            }
14789        }
14790
14791        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14792            return;
14793        };
14794        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14795    }
14796
14797    pub fn open_context_menu(
14798        &mut self,
14799        _: &OpenContextMenu,
14800        window: &mut Window,
14801        cx: &mut Context<Self>,
14802    ) {
14803        self.request_autoscroll(Autoscroll::newest(), cx);
14804        let position = self.selections.newest_display(cx).start;
14805        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14806    }
14807
14808    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14809        &self.inlay_hint_cache
14810    }
14811
14812    pub fn replay_insert_event(
14813        &mut self,
14814        text: &str,
14815        relative_utf16_range: Option<Range<isize>>,
14816        window: &mut Window,
14817        cx: &mut Context<Self>,
14818    ) {
14819        if !self.input_enabled {
14820            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14821            return;
14822        }
14823        if let Some(relative_utf16_range) = relative_utf16_range {
14824            let selections = self.selections.all::<OffsetUtf16>(cx);
14825            self.change_selections(None, window, cx, |s| {
14826                let new_ranges = selections.into_iter().map(|range| {
14827                    let start = OffsetUtf16(
14828                        range
14829                            .head()
14830                            .0
14831                            .saturating_add_signed(relative_utf16_range.start),
14832                    );
14833                    let end = OffsetUtf16(
14834                        range
14835                            .head()
14836                            .0
14837                            .saturating_add_signed(relative_utf16_range.end),
14838                    );
14839                    start..end
14840                });
14841                s.select_ranges(new_ranges);
14842            });
14843        }
14844
14845        self.handle_input(text, window, cx);
14846    }
14847
14848    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14849        let Some(provider) = self.semantics_provider.as_ref() else {
14850            return false;
14851        };
14852
14853        let mut supports = false;
14854        self.buffer().update(cx, |this, cx| {
14855            this.for_each_buffer(|buffer| {
14856                supports |= provider.supports_inlay_hints(buffer, cx);
14857            });
14858        });
14859
14860        supports
14861    }
14862
14863    pub fn is_focused(&self, window: &Window) -> bool {
14864        self.focus_handle.is_focused(window)
14865    }
14866
14867    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14868        cx.emit(EditorEvent::Focused);
14869
14870        if let Some(descendant) = self
14871            .last_focused_descendant
14872            .take()
14873            .and_then(|descendant| descendant.upgrade())
14874        {
14875            window.focus(&descendant);
14876        } else {
14877            if let Some(blame) = self.blame.as_ref() {
14878                blame.update(cx, GitBlame::focus)
14879            }
14880
14881            self.blink_manager.update(cx, BlinkManager::enable);
14882            self.show_cursor_names(window, cx);
14883            self.buffer.update(cx, |buffer, cx| {
14884                buffer.finalize_last_transaction(cx);
14885                if self.leader_peer_id.is_none() {
14886                    buffer.set_active_selections(
14887                        &self.selections.disjoint_anchors(),
14888                        self.selections.line_mode,
14889                        self.cursor_shape,
14890                        cx,
14891                    );
14892                }
14893            });
14894        }
14895    }
14896
14897    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14898        cx.emit(EditorEvent::FocusedIn)
14899    }
14900
14901    fn handle_focus_out(
14902        &mut self,
14903        event: FocusOutEvent,
14904        _window: &mut Window,
14905        _cx: &mut Context<Self>,
14906    ) {
14907        if event.blurred != self.focus_handle {
14908            self.last_focused_descendant = Some(event.blurred);
14909        }
14910    }
14911
14912    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14913        self.blink_manager.update(cx, BlinkManager::disable);
14914        self.buffer
14915            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14916
14917        if let Some(blame) = self.blame.as_ref() {
14918            blame.update(cx, GitBlame::blur)
14919        }
14920        if !self.hover_state.focused(window, cx) {
14921            hide_hover(self, cx);
14922        }
14923        if !self
14924            .context_menu
14925            .borrow()
14926            .as_ref()
14927            .is_some_and(|context_menu| context_menu.focused(window, cx))
14928        {
14929            self.hide_context_menu(window, cx);
14930        }
14931        self.discard_inline_completion(false, cx);
14932        cx.emit(EditorEvent::Blurred);
14933        cx.notify();
14934    }
14935
14936    pub fn register_action<A: Action>(
14937        &mut self,
14938        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14939    ) -> Subscription {
14940        let id = self.next_editor_action_id.post_inc();
14941        let listener = Arc::new(listener);
14942        self.editor_actions.borrow_mut().insert(
14943            id,
14944            Box::new(move |window, _| {
14945                let listener = listener.clone();
14946                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14947                    let action = action.downcast_ref().unwrap();
14948                    if phase == DispatchPhase::Bubble {
14949                        listener(action, window, cx)
14950                    }
14951                })
14952            }),
14953        );
14954
14955        let editor_actions = self.editor_actions.clone();
14956        Subscription::new(move || {
14957            editor_actions.borrow_mut().remove(&id);
14958        })
14959    }
14960
14961    pub fn file_header_size(&self) -> u32 {
14962        FILE_HEADER_HEIGHT
14963    }
14964
14965    pub fn revert(
14966        &mut self,
14967        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14968        window: &mut Window,
14969        cx: &mut Context<Self>,
14970    ) {
14971        self.buffer().update(cx, |multi_buffer, cx| {
14972            for (buffer_id, changes) in revert_changes {
14973                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14974                    buffer.update(cx, |buffer, cx| {
14975                        buffer.edit(
14976                            changes.into_iter().map(|(range, text)| {
14977                                (range, text.to_string().map(Arc::<str>::from))
14978                            }),
14979                            None,
14980                            cx,
14981                        );
14982                    });
14983                }
14984            }
14985        });
14986        self.change_selections(None, window, cx, |selections| selections.refresh());
14987    }
14988
14989    pub fn to_pixel_point(
14990        &self,
14991        source: multi_buffer::Anchor,
14992        editor_snapshot: &EditorSnapshot,
14993        window: &mut Window,
14994    ) -> Option<gpui::Point<Pixels>> {
14995        let source_point = source.to_display_point(editor_snapshot);
14996        self.display_to_pixel_point(source_point, editor_snapshot, window)
14997    }
14998
14999    pub fn display_to_pixel_point(
15000        &self,
15001        source: DisplayPoint,
15002        editor_snapshot: &EditorSnapshot,
15003        window: &mut Window,
15004    ) -> Option<gpui::Point<Pixels>> {
15005        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15006        let text_layout_details = self.text_layout_details(window);
15007        let scroll_top = text_layout_details
15008            .scroll_anchor
15009            .scroll_position(editor_snapshot)
15010            .y;
15011
15012        if source.row().as_f32() < scroll_top.floor() {
15013            return None;
15014        }
15015        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15016        let source_y = line_height * (source.row().as_f32() - scroll_top);
15017        Some(gpui::Point::new(source_x, source_y))
15018    }
15019
15020    pub fn has_visible_completions_menu(&self) -> bool {
15021        !self.edit_prediction_preview_is_active()
15022            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15023                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15024            })
15025    }
15026
15027    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15028        self.addons
15029            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15030    }
15031
15032    pub fn unregister_addon<T: Addon>(&mut self) {
15033        self.addons.remove(&std::any::TypeId::of::<T>());
15034    }
15035
15036    pub fn addon<T: Addon>(&self) -> Option<&T> {
15037        let type_id = std::any::TypeId::of::<T>();
15038        self.addons
15039            .get(&type_id)
15040            .and_then(|item| item.to_any().downcast_ref::<T>())
15041    }
15042
15043    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15044        let text_layout_details = self.text_layout_details(window);
15045        let style = &text_layout_details.editor_style;
15046        let font_id = window.text_system().resolve_font(&style.text.font());
15047        let font_size = style.text.font_size.to_pixels(window.rem_size());
15048        let line_height = style.text.line_height_in_pixels(window.rem_size());
15049        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15050
15051        gpui::Size::new(em_width, line_height)
15052    }
15053
15054    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15055        self.load_diff_task.clone()
15056    }
15057
15058    fn read_selections_from_db(
15059        &mut self,
15060        item_id: u64,
15061        workspace_id: WorkspaceId,
15062        window: &mut Window,
15063        cx: &mut Context<Editor>,
15064    ) {
15065        if !self.is_singleton(cx)
15066            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15067        {
15068            return;
15069        }
15070        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15071            return;
15072        };
15073        if selections.is_empty() {
15074            return;
15075        }
15076
15077        let snapshot = self.buffer.read(cx).snapshot(cx);
15078        self.change_selections(None, window, cx, |s| {
15079            s.select_ranges(selections.into_iter().map(|(start, end)| {
15080                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15081            }));
15082        });
15083    }
15084}
15085
15086fn get_uncommitted_diff_for_buffer(
15087    project: &Entity<Project>,
15088    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15089    buffer: Entity<MultiBuffer>,
15090    cx: &mut App,
15091) -> Task<()> {
15092    let mut tasks = Vec::new();
15093    project.update(cx, |project, cx| {
15094        for buffer in buffers {
15095            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15096        }
15097    });
15098    cx.spawn(|mut cx| async move {
15099        let diffs = futures::future::join_all(tasks).await;
15100        buffer
15101            .update(&mut cx, |buffer, cx| {
15102                for diff in diffs.into_iter().flatten() {
15103                    buffer.add_diff(diff, cx);
15104                }
15105            })
15106            .ok();
15107    })
15108}
15109
15110fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15111    let tab_size = tab_size.get() as usize;
15112    let mut width = offset;
15113
15114    for ch in text.chars() {
15115        width += if ch == '\t' {
15116            tab_size - (width % tab_size)
15117        } else {
15118            1
15119        };
15120    }
15121
15122    width - offset
15123}
15124
15125#[cfg(test)]
15126mod tests {
15127    use super::*;
15128
15129    #[test]
15130    fn test_string_size_with_expanded_tabs() {
15131        let nz = |val| NonZeroU32::new(val).unwrap();
15132        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15133        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15134        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15135        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15136        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15137        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15138        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15139        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15140    }
15141}
15142
15143/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15144struct WordBreakingTokenizer<'a> {
15145    input: &'a str,
15146}
15147
15148impl<'a> WordBreakingTokenizer<'a> {
15149    fn new(input: &'a str) -> Self {
15150        Self { input }
15151    }
15152}
15153
15154fn is_char_ideographic(ch: char) -> bool {
15155    use unicode_script::Script::*;
15156    use unicode_script::UnicodeScript;
15157    matches!(ch.script(), Han | Tangut | Yi)
15158}
15159
15160fn is_grapheme_ideographic(text: &str) -> bool {
15161    text.chars().any(is_char_ideographic)
15162}
15163
15164fn is_grapheme_whitespace(text: &str) -> bool {
15165    text.chars().any(|x| x.is_whitespace())
15166}
15167
15168fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15169    text.chars().next().map_or(false, |ch| {
15170        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15171    })
15172}
15173
15174#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15175struct WordBreakToken<'a> {
15176    token: &'a str,
15177    grapheme_len: usize,
15178    is_whitespace: bool,
15179}
15180
15181impl<'a> Iterator for WordBreakingTokenizer<'a> {
15182    /// Yields a span, the count of graphemes in the token, and whether it was
15183    /// whitespace. Note that it also breaks at word boundaries.
15184    type Item = WordBreakToken<'a>;
15185
15186    fn next(&mut self) -> Option<Self::Item> {
15187        use unicode_segmentation::UnicodeSegmentation;
15188        if self.input.is_empty() {
15189            return None;
15190        }
15191
15192        let mut iter = self.input.graphemes(true).peekable();
15193        let mut offset = 0;
15194        let mut graphemes = 0;
15195        if let Some(first_grapheme) = iter.next() {
15196            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15197            offset += first_grapheme.len();
15198            graphemes += 1;
15199            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15200                if let Some(grapheme) = iter.peek().copied() {
15201                    if should_stay_with_preceding_ideograph(grapheme) {
15202                        offset += grapheme.len();
15203                        graphemes += 1;
15204                    }
15205                }
15206            } else {
15207                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15208                let mut next_word_bound = words.peek().copied();
15209                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15210                    next_word_bound = words.next();
15211                }
15212                while let Some(grapheme) = iter.peek().copied() {
15213                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15214                        break;
15215                    };
15216                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15217                        break;
15218                    };
15219                    offset += grapheme.len();
15220                    graphemes += 1;
15221                    iter.next();
15222                }
15223            }
15224            let token = &self.input[..offset];
15225            self.input = &self.input[offset..];
15226            if is_whitespace {
15227                Some(WordBreakToken {
15228                    token: " ",
15229                    grapheme_len: 1,
15230                    is_whitespace: true,
15231                })
15232            } else {
15233                Some(WordBreakToken {
15234                    token,
15235                    grapheme_len: graphemes,
15236                    is_whitespace: false,
15237                })
15238            }
15239        } else {
15240            None
15241        }
15242    }
15243}
15244
15245#[test]
15246fn test_word_breaking_tokenizer() {
15247    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15248        ("", &[]),
15249        ("  ", &[(" ", 1, true)]),
15250        ("Ʒ", &[("Ʒ", 1, false)]),
15251        ("Ǽ", &[("Ǽ", 1, false)]),
15252        ("", &[("", 1, false)]),
15253        ("⋑⋑", &[("⋑⋑", 2, false)]),
15254        (
15255            "原理,进而",
15256            &[
15257                ("", 1, false),
15258                ("理,", 2, false),
15259                ("", 1, false),
15260                ("", 1, false),
15261            ],
15262        ),
15263        (
15264            "hello world",
15265            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15266        ),
15267        (
15268            "hello, world",
15269            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15270        ),
15271        (
15272            "  hello world",
15273            &[
15274                (" ", 1, true),
15275                ("hello", 5, false),
15276                (" ", 1, true),
15277                ("world", 5, false),
15278            ],
15279        ),
15280        (
15281            "这是什么 \n 钢笔",
15282            &[
15283                ("", 1, false),
15284                ("", 1, false),
15285                ("", 1, false),
15286                ("", 1, false),
15287                (" ", 1, true),
15288                ("", 1, false),
15289                ("", 1, false),
15290            ],
15291        ),
15292        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15293    ];
15294
15295    for (input, result) in tests {
15296        assert_eq!(
15297            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15298            result
15299                .iter()
15300                .copied()
15301                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15302                    token,
15303                    grapheme_len,
15304                    is_whitespace,
15305                })
15306                .collect::<Vec<_>>()
15307        );
15308    }
15309}
15310
15311fn wrap_with_prefix(
15312    line_prefix: String,
15313    unwrapped_text: String,
15314    wrap_column: usize,
15315    tab_size: NonZeroU32,
15316) -> String {
15317    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15318    let mut wrapped_text = String::new();
15319    let mut current_line = line_prefix.clone();
15320
15321    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15322    let mut current_line_len = line_prefix_len;
15323    for WordBreakToken {
15324        token,
15325        grapheme_len,
15326        is_whitespace,
15327    } in tokenizer
15328    {
15329        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15330            wrapped_text.push_str(current_line.trim_end());
15331            wrapped_text.push('\n');
15332            current_line.truncate(line_prefix.len());
15333            current_line_len = line_prefix_len;
15334            if !is_whitespace {
15335                current_line.push_str(token);
15336                current_line_len += grapheme_len;
15337            }
15338        } else if !is_whitespace {
15339            current_line.push_str(token);
15340            current_line_len += grapheme_len;
15341        } else if current_line_len != line_prefix_len {
15342            current_line.push(' ');
15343            current_line_len += 1;
15344        }
15345    }
15346
15347    if !current_line.is_empty() {
15348        wrapped_text.push_str(&current_line);
15349    }
15350    wrapped_text
15351}
15352
15353#[test]
15354fn test_wrap_with_prefix() {
15355    assert_eq!(
15356        wrap_with_prefix(
15357            "# ".to_string(),
15358            "abcdefg".to_string(),
15359            4,
15360            NonZeroU32::new(4).unwrap()
15361        ),
15362        "# abcdefg"
15363    );
15364    assert_eq!(
15365        wrap_with_prefix(
15366            "".to_string(),
15367            "\thello world".to_string(),
15368            8,
15369            NonZeroU32::new(4).unwrap()
15370        ),
15371        "hello\nworld"
15372    );
15373    assert_eq!(
15374        wrap_with_prefix(
15375            "// ".to_string(),
15376            "xx \nyy zz aa bb cc".to_string(),
15377            12,
15378            NonZeroU32::new(4).unwrap()
15379        ),
15380        "// xx yy zz\n// aa bb cc"
15381    );
15382    assert_eq!(
15383        wrap_with_prefix(
15384            String::new(),
15385            "这是什么 \n 钢笔".to_string(),
15386            3,
15387            NonZeroU32::new(4).unwrap()
15388        ),
15389        "这是什\n么 钢\n"
15390    );
15391}
15392
15393pub trait CollaborationHub {
15394    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15395    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15396    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15397}
15398
15399impl CollaborationHub for Entity<Project> {
15400    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15401        self.read(cx).collaborators()
15402    }
15403
15404    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15405        self.read(cx).user_store().read(cx).participant_indices()
15406    }
15407
15408    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15409        let this = self.read(cx);
15410        let user_ids = this.collaborators().values().map(|c| c.user_id);
15411        this.user_store().read_with(cx, |user_store, cx| {
15412            user_store.participant_names(user_ids, cx)
15413        })
15414    }
15415}
15416
15417pub trait SemanticsProvider {
15418    fn hover(
15419        &self,
15420        buffer: &Entity<Buffer>,
15421        position: text::Anchor,
15422        cx: &mut App,
15423    ) -> Option<Task<Vec<project::Hover>>>;
15424
15425    fn inlay_hints(
15426        &self,
15427        buffer_handle: Entity<Buffer>,
15428        range: Range<text::Anchor>,
15429        cx: &mut App,
15430    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15431
15432    fn resolve_inlay_hint(
15433        &self,
15434        hint: InlayHint,
15435        buffer_handle: Entity<Buffer>,
15436        server_id: LanguageServerId,
15437        cx: &mut App,
15438    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15439
15440    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15441
15442    fn document_highlights(
15443        &self,
15444        buffer: &Entity<Buffer>,
15445        position: text::Anchor,
15446        cx: &mut App,
15447    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15448
15449    fn definitions(
15450        &self,
15451        buffer: &Entity<Buffer>,
15452        position: text::Anchor,
15453        kind: GotoDefinitionKind,
15454        cx: &mut App,
15455    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15456
15457    fn range_for_rename(
15458        &self,
15459        buffer: &Entity<Buffer>,
15460        position: text::Anchor,
15461        cx: &mut App,
15462    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15463
15464    fn perform_rename(
15465        &self,
15466        buffer: &Entity<Buffer>,
15467        position: text::Anchor,
15468        new_name: String,
15469        cx: &mut App,
15470    ) -> Option<Task<Result<ProjectTransaction>>>;
15471}
15472
15473pub trait CompletionProvider {
15474    fn completions(
15475        &self,
15476        buffer: &Entity<Buffer>,
15477        buffer_position: text::Anchor,
15478        trigger: CompletionContext,
15479        window: &mut Window,
15480        cx: &mut Context<Editor>,
15481    ) -> Task<Result<Vec<Completion>>>;
15482
15483    fn resolve_completions(
15484        &self,
15485        buffer: Entity<Buffer>,
15486        completion_indices: Vec<usize>,
15487        completions: Rc<RefCell<Box<[Completion]>>>,
15488        cx: &mut Context<Editor>,
15489    ) -> Task<Result<bool>>;
15490
15491    fn apply_additional_edits_for_completion(
15492        &self,
15493        _buffer: Entity<Buffer>,
15494        _completions: Rc<RefCell<Box<[Completion]>>>,
15495        _completion_index: usize,
15496        _push_to_history: bool,
15497        _cx: &mut Context<Editor>,
15498    ) -> Task<Result<Option<language::Transaction>>> {
15499        Task::ready(Ok(None))
15500    }
15501
15502    fn is_completion_trigger(
15503        &self,
15504        buffer: &Entity<Buffer>,
15505        position: language::Anchor,
15506        text: &str,
15507        trigger_in_words: bool,
15508        cx: &mut Context<Editor>,
15509    ) -> bool;
15510
15511    fn sort_completions(&self) -> bool {
15512        true
15513    }
15514}
15515
15516pub trait CodeActionProvider {
15517    fn id(&self) -> Arc<str>;
15518
15519    fn code_actions(
15520        &self,
15521        buffer: &Entity<Buffer>,
15522        range: Range<text::Anchor>,
15523        window: &mut Window,
15524        cx: &mut App,
15525    ) -> Task<Result<Vec<CodeAction>>>;
15526
15527    fn apply_code_action(
15528        &self,
15529        buffer_handle: Entity<Buffer>,
15530        action: CodeAction,
15531        excerpt_id: ExcerptId,
15532        push_to_history: bool,
15533        window: &mut Window,
15534        cx: &mut App,
15535    ) -> Task<Result<ProjectTransaction>>;
15536}
15537
15538impl CodeActionProvider for Entity<Project> {
15539    fn id(&self) -> Arc<str> {
15540        "project".into()
15541    }
15542
15543    fn code_actions(
15544        &self,
15545        buffer: &Entity<Buffer>,
15546        range: Range<text::Anchor>,
15547        _window: &mut Window,
15548        cx: &mut App,
15549    ) -> Task<Result<Vec<CodeAction>>> {
15550        self.update(cx, |project, cx| {
15551            project.code_actions(buffer, range, None, cx)
15552        })
15553    }
15554
15555    fn apply_code_action(
15556        &self,
15557        buffer_handle: Entity<Buffer>,
15558        action: CodeAction,
15559        _excerpt_id: ExcerptId,
15560        push_to_history: bool,
15561        _window: &mut Window,
15562        cx: &mut App,
15563    ) -> Task<Result<ProjectTransaction>> {
15564        self.update(cx, |project, cx| {
15565            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15566        })
15567    }
15568}
15569
15570fn snippet_completions(
15571    project: &Project,
15572    buffer: &Entity<Buffer>,
15573    buffer_position: text::Anchor,
15574    cx: &mut App,
15575) -> Task<Result<Vec<Completion>>> {
15576    let language = buffer.read(cx).language_at(buffer_position);
15577    let language_name = language.as_ref().map(|language| language.lsp_id());
15578    let snippet_store = project.snippets().read(cx);
15579    let snippets = snippet_store.snippets_for(language_name, cx);
15580
15581    if snippets.is_empty() {
15582        return Task::ready(Ok(vec![]));
15583    }
15584    let snapshot = buffer.read(cx).text_snapshot();
15585    let chars: String = snapshot
15586        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15587        .collect();
15588
15589    let scope = language.map(|language| language.default_scope());
15590    let executor = cx.background_executor().clone();
15591
15592    cx.background_spawn(async move {
15593        let classifier = CharClassifier::new(scope).for_completion(true);
15594        let mut last_word = chars
15595            .chars()
15596            .take_while(|c| classifier.is_word(*c))
15597            .collect::<String>();
15598        last_word = last_word.chars().rev().collect();
15599
15600        if last_word.is_empty() {
15601            return Ok(vec![]);
15602        }
15603
15604        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15605        let to_lsp = |point: &text::Anchor| {
15606            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15607            point_to_lsp(end)
15608        };
15609        let lsp_end = to_lsp(&buffer_position);
15610
15611        let candidates = snippets
15612            .iter()
15613            .enumerate()
15614            .flat_map(|(ix, snippet)| {
15615                snippet
15616                    .prefix
15617                    .iter()
15618                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15619            })
15620            .collect::<Vec<StringMatchCandidate>>();
15621
15622        let mut matches = fuzzy::match_strings(
15623            &candidates,
15624            &last_word,
15625            last_word.chars().any(|c| c.is_uppercase()),
15626            100,
15627            &Default::default(),
15628            executor,
15629        )
15630        .await;
15631
15632        // Remove all candidates where the query's start does not match the start of any word in the candidate
15633        if let Some(query_start) = last_word.chars().next() {
15634            matches.retain(|string_match| {
15635                split_words(&string_match.string).any(|word| {
15636                    // Check that the first codepoint of the word as lowercase matches the first
15637                    // codepoint of the query as lowercase
15638                    word.chars()
15639                        .flat_map(|codepoint| codepoint.to_lowercase())
15640                        .zip(query_start.to_lowercase())
15641                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15642                })
15643            });
15644        }
15645
15646        let matched_strings = matches
15647            .into_iter()
15648            .map(|m| m.string)
15649            .collect::<HashSet<_>>();
15650
15651        let result: Vec<Completion> = snippets
15652            .into_iter()
15653            .filter_map(|snippet| {
15654                let matching_prefix = snippet
15655                    .prefix
15656                    .iter()
15657                    .find(|prefix| matched_strings.contains(*prefix))?;
15658                let start = as_offset - last_word.len();
15659                let start = snapshot.anchor_before(start);
15660                let range = start..buffer_position;
15661                let lsp_start = to_lsp(&start);
15662                let lsp_range = lsp::Range {
15663                    start: lsp_start,
15664                    end: lsp_end,
15665                };
15666                Some(Completion {
15667                    old_range: range,
15668                    new_text: snippet.body.clone(),
15669                    resolved: false,
15670                    label: CodeLabel {
15671                        text: matching_prefix.clone(),
15672                        runs: vec![],
15673                        filter_range: 0..matching_prefix.len(),
15674                    },
15675                    server_id: LanguageServerId(usize::MAX),
15676                    documentation: snippet
15677                        .description
15678                        .clone()
15679                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
15680                    lsp_completion: lsp::CompletionItem {
15681                        label: snippet.prefix.first().unwrap().clone(),
15682                        kind: Some(CompletionItemKind::SNIPPET),
15683                        label_details: snippet.description.as_ref().map(|description| {
15684                            lsp::CompletionItemLabelDetails {
15685                                detail: Some(description.clone()),
15686                                description: None,
15687                            }
15688                        }),
15689                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15690                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15691                            lsp::InsertReplaceEdit {
15692                                new_text: snippet.body.clone(),
15693                                insert: lsp_range,
15694                                replace: lsp_range,
15695                            },
15696                        )),
15697                        filter_text: Some(snippet.body.clone()),
15698                        sort_text: Some(char::MAX.to_string()),
15699                        ..Default::default()
15700                    },
15701                    confirm: None,
15702                })
15703            })
15704            .collect();
15705
15706        Ok(result)
15707    })
15708}
15709
15710impl CompletionProvider for Entity<Project> {
15711    fn completions(
15712        &self,
15713        buffer: &Entity<Buffer>,
15714        buffer_position: text::Anchor,
15715        options: CompletionContext,
15716        _window: &mut Window,
15717        cx: &mut Context<Editor>,
15718    ) -> Task<Result<Vec<Completion>>> {
15719        self.update(cx, |project, cx| {
15720            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15721            let project_completions = project.completions(buffer, buffer_position, options, cx);
15722            cx.background_spawn(async move {
15723                let mut completions = project_completions.await?;
15724                let snippets_completions = snippets.await?;
15725                completions.extend(snippets_completions);
15726                Ok(completions)
15727            })
15728        })
15729    }
15730
15731    fn resolve_completions(
15732        &self,
15733        buffer: Entity<Buffer>,
15734        completion_indices: Vec<usize>,
15735        completions: Rc<RefCell<Box<[Completion]>>>,
15736        cx: &mut Context<Editor>,
15737    ) -> Task<Result<bool>> {
15738        self.update(cx, |project, cx| {
15739            project.lsp_store().update(cx, |lsp_store, cx| {
15740                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15741            })
15742        })
15743    }
15744
15745    fn apply_additional_edits_for_completion(
15746        &self,
15747        buffer: Entity<Buffer>,
15748        completions: Rc<RefCell<Box<[Completion]>>>,
15749        completion_index: usize,
15750        push_to_history: bool,
15751        cx: &mut Context<Editor>,
15752    ) -> Task<Result<Option<language::Transaction>>> {
15753        self.update(cx, |project, cx| {
15754            project.lsp_store().update(cx, |lsp_store, cx| {
15755                lsp_store.apply_additional_edits_for_completion(
15756                    buffer,
15757                    completions,
15758                    completion_index,
15759                    push_to_history,
15760                    cx,
15761                )
15762            })
15763        })
15764    }
15765
15766    fn is_completion_trigger(
15767        &self,
15768        buffer: &Entity<Buffer>,
15769        position: language::Anchor,
15770        text: &str,
15771        trigger_in_words: bool,
15772        cx: &mut Context<Editor>,
15773    ) -> bool {
15774        let mut chars = text.chars();
15775        let char = if let Some(char) = chars.next() {
15776            char
15777        } else {
15778            return false;
15779        };
15780        if chars.next().is_some() {
15781            return false;
15782        }
15783
15784        let buffer = buffer.read(cx);
15785        let snapshot = buffer.snapshot();
15786        if !snapshot.settings_at(position, cx).show_completions_on_input {
15787            return false;
15788        }
15789        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15790        if trigger_in_words && classifier.is_word(char) {
15791            return true;
15792        }
15793
15794        buffer.completion_triggers().contains(text)
15795    }
15796}
15797
15798impl SemanticsProvider for Entity<Project> {
15799    fn hover(
15800        &self,
15801        buffer: &Entity<Buffer>,
15802        position: text::Anchor,
15803        cx: &mut App,
15804    ) -> Option<Task<Vec<project::Hover>>> {
15805        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15806    }
15807
15808    fn document_highlights(
15809        &self,
15810        buffer: &Entity<Buffer>,
15811        position: text::Anchor,
15812        cx: &mut App,
15813    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15814        Some(self.update(cx, |project, cx| {
15815            project.document_highlights(buffer, position, cx)
15816        }))
15817    }
15818
15819    fn definitions(
15820        &self,
15821        buffer: &Entity<Buffer>,
15822        position: text::Anchor,
15823        kind: GotoDefinitionKind,
15824        cx: &mut App,
15825    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15826        Some(self.update(cx, |project, cx| match kind {
15827            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15828            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15829            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15830            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15831        }))
15832    }
15833
15834    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15835        // TODO: make this work for remote projects
15836        self.update(cx, |this, cx| {
15837            buffer.update(cx, |buffer, cx| {
15838                this.any_language_server_supports_inlay_hints(buffer, cx)
15839            })
15840        })
15841    }
15842
15843    fn inlay_hints(
15844        &self,
15845        buffer_handle: Entity<Buffer>,
15846        range: Range<text::Anchor>,
15847        cx: &mut App,
15848    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15849        Some(self.update(cx, |project, cx| {
15850            project.inlay_hints(buffer_handle, range, cx)
15851        }))
15852    }
15853
15854    fn resolve_inlay_hint(
15855        &self,
15856        hint: InlayHint,
15857        buffer_handle: Entity<Buffer>,
15858        server_id: LanguageServerId,
15859        cx: &mut App,
15860    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15861        Some(self.update(cx, |project, cx| {
15862            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15863        }))
15864    }
15865
15866    fn range_for_rename(
15867        &self,
15868        buffer: &Entity<Buffer>,
15869        position: text::Anchor,
15870        cx: &mut App,
15871    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15872        Some(self.update(cx, |project, cx| {
15873            let buffer = buffer.clone();
15874            let task = project.prepare_rename(buffer.clone(), position, cx);
15875            cx.spawn(|_, mut cx| async move {
15876                Ok(match task.await? {
15877                    PrepareRenameResponse::Success(range) => Some(range),
15878                    PrepareRenameResponse::InvalidPosition => None,
15879                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15880                        // Fallback on using TreeSitter info to determine identifier range
15881                        buffer.update(&mut cx, |buffer, _| {
15882                            let snapshot = buffer.snapshot();
15883                            let (range, kind) = snapshot.surrounding_word(position);
15884                            if kind != Some(CharKind::Word) {
15885                                return None;
15886                            }
15887                            Some(
15888                                snapshot.anchor_before(range.start)
15889                                    ..snapshot.anchor_after(range.end),
15890                            )
15891                        })?
15892                    }
15893                })
15894            })
15895        }))
15896    }
15897
15898    fn perform_rename(
15899        &self,
15900        buffer: &Entity<Buffer>,
15901        position: text::Anchor,
15902        new_name: String,
15903        cx: &mut App,
15904    ) -> Option<Task<Result<ProjectTransaction>>> {
15905        Some(self.update(cx, |project, cx| {
15906            project.perform_rename(buffer.clone(), position, new_name, cx)
15907        }))
15908    }
15909}
15910
15911fn inlay_hint_settings(
15912    location: Anchor,
15913    snapshot: &MultiBufferSnapshot,
15914    cx: &mut Context<Editor>,
15915) -> InlayHintSettings {
15916    let file = snapshot.file_at(location);
15917    let language = snapshot.language_at(location).map(|l| l.name());
15918    language_settings(language, file, cx).inlay_hints
15919}
15920
15921fn consume_contiguous_rows(
15922    contiguous_row_selections: &mut Vec<Selection<Point>>,
15923    selection: &Selection<Point>,
15924    display_map: &DisplaySnapshot,
15925    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15926) -> (MultiBufferRow, MultiBufferRow) {
15927    contiguous_row_selections.push(selection.clone());
15928    let start_row = MultiBufferRow(selection.start.row);
15929    let mut end_row = ending_row(selection, display_map);
15930
15931    while let Some(next_selection) = selections.peek() {
15932        if next_selection.start.row <= end_row.0 {
15933            end_row = ending_row(next_selection, display_map);
15934            contiguous_row_selections.push(selections.next().unwrap().clone());
15935        } else {
15936            break;
15937        }
15938    }
15939    (start_row, end_row)
15940}
15941
15942fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15943    if next_selection.end.column > 0 || next_selection.is_empty() {
15944        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15945    } else {
15946        MultiBufferRow(next_selection.end.row)
15947    }
15948}
15949
15950impl EditorSnapshot {
15951    pub fn remote_selections_in_range<'a>(
15952        &'a self,
15953        range: &'a Range<Anchor>,
15954        collaboration_hub: &dyn CollaborationHub,
15955        cx: &'a App,
15956    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15957        let participant_names = collaboration_hub.user_names(cx);
15958        let participant_indices = collaboration_hub.user_participant_indices(cx);
15959        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15960        let collaborators_by_replica_id = collaborators_by_peer_id
15961            .iter()
15962            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15963            .collect::<HashMap<_, _>>();
15964        self.buffer_snapshot
15965            .selections_in_range(range, false)
15966            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15967                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15968                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15969                let user_name = participant_names.get(&collaborator.user_id).cloned();
15970                Some(RemoteSelection {
15971                    replica_id,
15972                    selection,
15973                    cursor_shape,
15974                    line_mode,
15975                    participant_index,
15976                    peer_id: collaborator.peer_id,
15977                    user_name,
15978                })
15979            })
15980    }
15981
15982    pub fn hunks_for_ranges(
15983        &self,
15984        ranges: impl Iterator<Item = Range<Point>>,
15985    ) -> Vec<MultiBufferDiffHunk> {
15986        let mut hunks = Vec::new();
15987        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15988            HashMap::default();
15989        for query_range in ranges {
15990            let query_rows =
15991                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15992            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15993                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15994            ) {
15995                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15996                // when the caret is just above or just below the deleted hunk.
15997                let allow_adjacent = hunk.status().is_removed();
15998                let related_to_selection = if allow_adjacent {
15999                    hunk.row_range.overlaps(&query_rows)
16000                        || hunk.row_range.start == query_rows.end
16001                        || hunk.row_range.end == query_rows.start
16002                } else {
16003                    hunk.row_range.overlaps(&query_rows)
16004                };
16005                if related_to_selection {
16006                    if !processed_buffer_rows
16007                        .entry(hunk.buffer_id)
16008                        .or_default()
16009                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16010                    {
16011                        continue;
16012                    }
16013                    hunks.push(hunk);
16014                }
16015            }
16016        }
16017
16018        hunks
16019    }
16020
16021    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16022        self.display_snapshot.buffer_snapshot.language_at(position)
16023    }
16024
16025    pub fn is_focused(&self) -> bool {
16026        self.is_focused
16027    }
16028
16029    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16030        self.placeholder_text.as_ref()
16031    }
16032
16033    pub fn scroll_position(&self) -> gpui::Point<f32> {
16034        self.scroll_anchor.scroll_position(&self.display_snapshot)
16035    }
16036
16037    fn gutter_dimensions(
16038        &self,
16039        font_id: FontId,
16040        font_size: Pixels,
16041        max_line_number_width: Pixels,
16042        cx: &App,
16043    ) -> Option<GutterDimensions> {
16044        if !self.show_gutter {
16045            return None;
16046        }
16047
16048        let descent = cx.text_system().descent(font_id, font_size);
16049        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16050        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16051
16052        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16053            matches!(
16054                ProjectSettings::get_global(cx).git.git_gutter,
16055                Some(GitGutterSetting::TrackedFiles)
16056            )
16057        });
16058        let gutter_settings = EditorSettings::get_global(cx).gutter;
16059        let show_line_numbers = self
16060            .show_line_numbers
16061            .unwrap_or(gutter_settings.line_numbers);
16062        let line_gutter_width = if show_line_numbers {
16063            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16064            let min_width_for_number_on_gutter = em_advance * 4.0;
16065            max_line_number_width.max(min_width_for_number_on_gutter)
16066        } else {
16067            0.0.into()
16068        };
16069
16070        let show_code_actions = self
16071            .show_code_actions
16072            .unwrap_or(gutter_settings.code_actions);
16073
16074        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16075
16076        let git_blame_entries_width =
16077            self.git_blame_gutter_max_author_length
16078                .map(|max_author_length| {
16079                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16080
16081                    /// The number of characters to dedicate to gaps and margins.
16082                    const SPACING_WIDTH: usize = 4;
16083
16084                    let max_char_count = max_author_length
16085                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16086                        + ::git::SHORT_SHA_LENGTH
16087                        + MAX_RELATIVE_TIMESTAMP.len()
16088                        + SPACING_WIDTH;
16089
16090                    em_advance * max_char_count
16091                });
16092
16093        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16094        left_padding += if show_code_actions || show_runnables {
16095            em_width * 3.0
16096        } else if show_git_gutter && show_line_numbers {
16097            em_width * 2.0
16098        } else if show_git_gutter || show_line_numbers {
16099            em_width
16100        } else {
16101            px(0.)
16102        };
16103
16104        let right_padding = if gutter_settings.folds && show_line_numbers {
16105            em_width * 4.0
16106        } else if gutter_settings.folds {
16107            em_width * 3.0
16108        } else if show_line_numbers {
16109            em_width
16110        } else {
16111            px(0.)
16112        };
16113
16114        Some(GutterDimensions {
16115            left_padding,
16116            right_padding,
16117            width: line_gutter_width + left_padding + right_padding,
16118            margin: -descent,
16119            git_blame_entries_width,
16120        })
16121    }
16122
16123    pub fn render_crease_toggle(
16124        &self,
16125        buffer_row: MultiBufferRow,
16126        row_contains_cursor: bool,
16127        editor: Entity<Editor>,
16128        window: &mut Window,
16129        cx: &mut App,
16130    ) -> Option<AnyElement> {
16131        let folded = self.is_line_folded(buffer_row);
16132        let mut is_foldable = false;
16133
16134        if let Some(crease) = self
16135            .crease_snapshot
16136            .query_row(buffer_row, &self.buffer_snapshot)
16137        {
16138            is_foldable = true;
16139            match crease {
16140                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16141                    if let Some(render_toggle) = render_toggle {
16142                        let toggle_callback =
16143                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16144                                if folded {
16145                                    editor.update(cx, |editor, cx| {
16146                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16147                                    });
16148                                } else {
16149                                    editor.update(cx, |editor, cx| {
16150                                        editor.unfold_at(
16151                                            &crate::UnfoldAt { buffer_row },
16152                                            window,
16153                                            cx,
16154                                        )
16155                                    });
16156                                }
16157                            });
16158                        return Some((render_toggle)(
16159                            buffer_row,
16160                            folded,
16161                            toggle_callback,
16162                            window,
16163                            cx,
16164                        ));
16165                    }
16166                }
16167            }
16168        }
16169
16170        is_foldable |= self.starts_indent(buffer_row);
16171
16172        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16173            Some(
16174                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16175                    .toggle_state(folded)
16176                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16177                        if folded {
16178                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16179                        } else {
16180                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16181                        }
16182                    }))
16183                    .into_any_element(),
16184            )
16185        } else {
16186            None
16187        }
16188    }
16189
16190    pub fn render_crease_trailer(
16191        &self,
16192        buffer_row: MultiBufferRow,
16193        window: &mut Window,
16194        cx: &mut App,
16195    ) -> Option<AnyElement> {
16196        let folded = self.is_line_folded(buffer_row);
16197        if let Crease::Inline { render_trailer, .. } = self
16198            .crease_snapshot
16199            .query_row(buffer_row, &self.buffer_snapshot)?
16200        {
16201            let render_trailer = render_trailer.as_ref()?;
16202            Some(render_trailer(buffer_row, folded, window, cx))
16203        } else {
16204            None
16205        }
16206    }
16207}
16208
16209impl Deref for EditorSnapshot {
16210    type Target = DisplaySnapshot;
16211
16212    fn deref(&self) -> &Self::Target {
16213        &self.display_snapshot
16214    }
16215}
16216
16217#[derive(Clone, Debug, PartialEq, Eq)]
16218pub enum EditorEvent {
16219    InputIgnored {
16220        text: Arc<str>,
16221    },
16222    InputHandled {
16223        utf16_range_to_replace: Option<Range<isize>>,
16224        text: Arc<str>,
16225    },
16226    ExcerptsAdded {
16227        buffer: Entity<Buffer>,
16228        predecessor: ExcerptId,
16229        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16230    },
16231    ExcerptsRemoved {
16232        ids: Vec<ExcerptId>,
16233    },
16234    BufferFoldToggled {
16235        ids: Vec<ExcerptId>,
16236        folded: bool,
16237    },
16238    ExcerptsEdited {
16239        ids: Vec<ExcerptId>,
16240    },
16241    ExcerptsExpanded {
16242        ids: Vec<ExcerptId>,
16243    },
16244    BufferEdited,
16245    Edited {
16246        transaction_id: clock::Lamport,
16247    },
16248    Reparsed(BufferId),
16249    Focused,
16250    FocusedIn,
16251    Blurred,
16252    DirtyChanged,
16253    Saved,
16254    TitleChanged,
16255    DiffBaseChanged,
16256    SelectionsChanged {
16257        local: bool,
16258    },
16259    ScrollPositionChanged {
16260        local: bool,
16261        autoscroll: bool,
16262    },
16263    Closed,
16264    TransactionUndone {
16265        transaction_id: clock::Lamport,
16266    },
16267    TransactionBegun {
16268        transaction_id: clock::Lamport,
16269    },
16270    Reloaded,
16271    CursorShapeChanged,
16272}
16273
16274impl EventEmitter<EditorEvent> for Editor {}
16275
16276impl Focusable for Editor {
16277    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16278        self.focus_handle.clone()
16279    }
16280}
16281
16282impl Render for Editor {
16283    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16284        let settings = ThemeSettings::get_global(cx);
16285
16286        let mut text_style = match self.mode {
16287            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16288                color: cx.theme().colors().editor_foreground,
16289                font_family: settings.ui_font.family.clone(),
16290                font_features: settings.ui_font.features.clone(),
16291                font_fallbacks: settings.ui_font.fallbacks.clone(),
16292                font_size: rems(0.875).into(),
16293                font_weight: settings.ui_font.weight,
16294                line_height: relative(settings.buffer_line_height.value()),
16295                ..Default::default()
16296            },
16297            EditorMode::Full => TextStyle {
16298                color: cx.theme().colors().editor_foreground,
16299                font_family: settings.buffer_font.family.clone(),
16300                font_features: settings.buffer_font.features.clone(),
16301                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16302                font_size: settings.buffer_font_size(cx).into(),
16303                font_weight: settings.buffer_font.weight,
16304                line_height: relative(settings.buffer_line_height.value()),
16305                ..Default::default()
16306            },
16307        };
16308        if let Some(text_style_refinement) = &self.text_style_refinement {
16309            text_style.refine(text_style_refinement)
16310        }
16311
16312        let background = match self.mode {
16313            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16314            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16315            EditorMode::Full => cx.theme().colors().editor_background,
16316        };
16317
16318        EditorElement::new(
16319            &cx.entity(),
16320            EditorStyle {
16321                background,
16322                local_player: cx.theme().players().local(),
16323                text: text_style,
16324                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16325                syntax: cx.theme().syntax().clone(),
16326                status: cx.theme().status().clone(),
16327                inlay_hints_style: make_inlay_hints_style(cx),
16328                inline_completion_styles: make_suggestion_styles(cx),
16329                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16330            },
16331        )
16332    }
16333}
16334
16335impl EntityInputHandler for Editor {
16336    fn text_for_range(
16337        &mut self,
16338        range_utf16: Range<usize>,
16339        adjusted_range: &mut Option<Range<usize>>,
16340        _: &mut Window,
16341        cx: &mut Context<Self>,
16342    ) -> Option<String> {
16343        let snapshot = self.buffer.read(cx).read(cx);
16344        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16345        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16346        if (start.0..end.0) != range_utf16 {
16347            adjusted_range.replace(start.0..end.0);
16348        }
16349        Some(snapshot.text_for_range(start..end).collect())
16350    }
16351
16352    fn selected_text_range(
16353        &mut self,
16354        ignore_disabled_input: bool,
16355        _: &mut Window,
16356        cx: &mut Context<Self>,
16357    ) -> Option<UTF16Selection> {
16358        // Prevent the IME menu from appearing when holding down an alphabetic key
16359        // while input is disabled.
16360        if !ignore_disabled_input && !self.input_enabled {
16361            return None;
16362        }
16363
16364        let selection = self.selections.newest::<OffsetUtf16>(cx);
16365        let range = selection.range();
16366
16367        Some(UTF16Selection {
16368            range: range.start.0..range.end.0,
16369            reversed: selection.reversed,
16370        })
16371    }
16372
16373    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16374        let snapshot = self.buffer.read(cx).read(cx);
16375        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16376        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16377    }
16378
16379    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16380        self.clear_highlights::<InputComposition>(cx);
16381        self.ime_transaction.take();
16382    }
16383
16384    fn replace_text_in_range(
16385        &mut self,
16386        range_utf16: Option<Range<usize>>,
16387        text: &str,
16388        window: &mut Window,
16389        cx: &mut Context<Self>,
16390    ) {
16391        if !self.input_enabled {
16392            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16393            return;
16394        }
16395
16396        self.transact(window, cx, |this, window, cx| {
16397            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16398                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16399                Some(this.selection_replacement_ranges(range_utf16, cx))
16400            } else {
16401                this.marked_text_ranges(cx)
16402            };
16403
16404            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16405                let newest_selection_id = this.selections.newest_anchor().id;
16406                this.selections
16407                    .all::<OffsetUtf16>(cx)
16408                    .iter()
16409                    .zip(ranges_to_replace.iter())
16410                    .find_map(|(selection, range)| {
16411                        if selection.id == newest_selection_id {
16412                            Some(
16413                                (range.start.0 as isize - selection.head().0 as isize)
16414                                    ..(range.end.0 as isize - selection.head().0 as isize),
16415                            )
16416                        } else {
16417                            None
16418                        }
16419                    })
16420            });
16421
16422            cx.emit(EditorEvent::InputHandled {
16423                utf16_range_to_replace: range_to_replace,
16424                text: text.into(),
16425            });
16426
16427            if let Some(new_selected_ranges) = new_selected_ranges {
16428                this.change_selections(None, window, cx, |selections| {
16429                    selections.select_ranges(new_selected_ranges)
16430                });
16431                this.backspace(&Default::default(), window, cx);
16432            }
16433
16434            this.handle_input(text, window, cx);
16435        });
16436
16437        if let Some(transaction) = self.ime_transaction {
16438            self.buffer.update(cx, |buffer, cx| {
16439                buffer.group_until_transaction(transaction, cx);
16440            });
16441        }
16442
16443        self.unmark_text(window, cx);
16444    }
16445
16446    fn replace_and_mark_text_in_range(
16447        &mut self,
16448        range_utf16: Option<Range<usize>>,
16449        text: &str,
16450        new_selected_range_utf16: Option<Range<usize>>,
16451        window: &mut Window,
16452        cx: &mut Context<Self>,
16453    ) {
16454        if !self.input_enabled {
16455            return;
16456        }
16457
16458        let transaction = self.transact(window, cx, |this, window, cx| {
16459            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16460                let snapshot = this.buffer.read(cx).read(cx);
16461                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16462                    for marked_range in &mut marked_ranges {
16463                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16464                        marked_range.start.0 += relative_range_utf16.start;
16465                        marked_range.start =
16466                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16467                        marked_range.end =
16468                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16469                    }
16470                }
16471                Some(marked_ranges)
16472            } else if let Some(range_utf16) = range_utf16 {
16473                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16474                Some(this.selection_replacement_ranges(range_utf16, cx))
16475            } else {
16476                None
16477            };
16478
16479            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16480                let newest_selection_id = this.selections.newest_anchor().id;
16481                this.selections
16482                    .all::<OffsetUtf16>(cx)
16483                    .iter()
16484                    .zip(ranges_to_replace.iter())
16485                    .find_map(|(selection, range)| {
16486                        if selection.id == newest_selection_id {
16487                            Some(
16488                                (range.start.0 as isize - selection.head().0 as isize)
16489                                    ..(range.end.0 as isize - selection.head().0 as isize),
16490                            )
16491                        } else {
16492                            None
16493                        }
16494                    })
16495            });
16496
16497            cx.emit(EditorEvent::InputHandled {
16498                utf16_range_to_replace: range_to_replace,
16499                text: text.into(),
16500            });
16501
16502            if let Some(ranges) = ranges_to_replace {
16503                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16504            }
16505
16506            let marked_ranges = {
16507                let snapshot = this.buffer.read(cx).read(cx);
16508                this.selections
16509                    .disjoint_anchors()
16510                    .iter()
16511                    .map(|selection| {
16512                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16513                    })
16514                    .collect::<Vec<_>>()
16515            };
16516
16517            if text.is_empty() {
16518                this.unmark_text(window, cx);
16519            } else {
16520                this.highlight_text::<InputComposition>(
16521                    marked_ranges.clone(),
16522                    HighlightStyle {
16523                        underline: Some(UnderlineStyle {
16524                            thickness: px(1.),
16525                            color: None,
16526                            wavy: false,
16527                        }),
16528                        ..Default::default()
16529                    },
16530                    cx,
16531                );
16532            }
16533
16534            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16535            let use_autoclose = this.use_autoclose;
16536            let use_auto_surround = this.use_auto_surround;
16537            this.set_use_autoclose(false);
16538            this.set_use_auto_surround(false);
16539            this.handle_input(text, window, cx);
16540            this.set_use_autoclose(use_autoclose);
16541            this.set_use_auto_surround(use_auto_surround);
16542
16543            if let Some(new_selected_range) = new_selected_range_utf16 {
16544                let snapshot = this.buffer.read(cx).read(cx);
16545                let new_selected_ranges = marked_ranges
16546                    .into_iter()
16547                    .map(|marked_range| {
16548                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16549                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16550                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16551                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16552                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16553                    })
16554                    .collect::<Vec<_>>();
16555
16556                drop(snapshot);
16557                this.change_selections(None, window, cx, |selections| {
16558                    selections.select_ranges(new_selected_ranges)
16559                });
16560            }
16561        });
16562
16563        self.ime_transaction = self.ime_transaction.or(transaction);
16564        if let Some(transaction) = self.ime_transaction {
16565            self.buffer.update(cx, |buffer, cx| {
16566                buffer.group_until_transaction(transaction, cx);
16567            });
16568        }
16569
16570        if self.text_highlights::<InputComposition>(cx).is_none() {
16571            self.ime_transaction.take();
16572        }
16573    }
16574
16575    fn bounds_for_range(
16576        &mut self,
16577        range_utf16: Range<usize>,
16578        element_bounds: gpui::Bounds<Pixels>,
16579        window: &mut Window,
16580        cx: &mut Context<Self>,
16581    ) -> Option<gpui::Bounds<Pixels>> {
16582        let text_layout_details = self.text_layout_details(window);
16583        let gpui::Size {
16584            width: em_width,
16585            height: line_height,
16586        } = self.character_size(window);
16587
16588        let snapshot = self.snapshot(window, cx);
16589        let scroll_position = snapshot.scroll_position();
16590        let scroll_left = scroll_position.x * em_width;
16591
16592        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16593        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16594            + self.gutter_dimensions.width
16595            + self.gutter_dimensions.margin;
16596        let y = line_height * (start.row().as_f32() - scroll_position.y);
16597
16598        Some(Bounds {
16599            origin: element_bounds.origin + point(x, y),
16600            size: size(em_width, line_height),
16601        })
16602    }
16603
16604    fn character_index_for_point(
16605        &mut self,
16606        point: gpui::Point<Pixels>,
16607        _window: &mut Window,
16608        _cx: &mut Context<Self>,
16609    ) -> Option<usize> {
16610        let position_map = self.last_position_map.as_ref()?;
16611        if !position_map.text_hitbox.contains(&point) {
16612            return None;
16613        }
16614        let display_point = position_map.point_for_position(point).previous_valid;
16615        let anchor = position_map
16616            .snapshot
16617            .display_point_to_anchor(display_point, Bias::Left);
16618        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16619        Some(utf16_offset.0)
16620    }
16621}
16622
16623trait SelectionExt {
16624    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16625    fn spanned_rows(
16626        &self,
16627        include_end_if_at_line_start: bool,
16628        map: &DisplaySnapshot,
16629    ) -> Range<MultiBufferRow>;
16630}
16631
16632impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16633    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16634        let start = self
16635            .start
16636            .to_point(&map.buffer_snapshot)
16637            .to_display_point(map);
16638        let end = self
16639            .end
16640            .to_point(&map.buffer_snapshot)
16641            .to_display_point(map);
16642        if self.reversed {
16643            end..start
16644        } else {
16645            start..end
16646        }
16647    }
16648
16649    fn spanned_rows(
16650        &self,
16651        include_end_if_at_line_start: bool,
16652        map: &DisplaySnapshot,
16653    ) -> Range<MultiBufferRow> {
16654        let start = self.start.to_point(&map.buffer_snapshot);
16655        let mut end = self.end.to_point(&map.buffer_snapshot);
16656        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16657            end.row -= 1;
16658        }
16659
16660        let buffer_start = map.prev_line_boundary(start).0;
16661        let buffer_end = map.next_line_boundary(end).0;
16662        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16663    }
16664}
16665
16666impl<T: InvalidationRegion> InvalidationStack<T> {
16667    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16668    where
16669        S: Clone + ToOffset,
16670    {
16671        while let Some(region) = self.last() {
16672            let all_selections_inside_invalidation_ranges =
16673                if selections.len() == region.ranges().len() {
16674                    selections
16675                        .iter()
16676                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16677                        .all(|(selection, invalidation_range)| {
16678                            let head = selection.head().to_offset(buffer);
16679                            invalidation_range.start <= head && invalidation_range.end >= head
16680                        })
16681                } else {
16682                    false
16683                };
16684
16685            if all_selections_inside_invalidation_ranges {
16686                break;
16687            } else {
16688                self.pop();
16689            }
16690        }
16691    }
16692}
16693
16694impl<T> Default for InvalidationStack<T> {
16695    fn default() -> Self {
16696        Self(Default::default())
16697    }
16698}
16699
16700impl<T> Deref for InvalidationStack<T> {
16701    type Target = Vec<T>;
16702
16703    fn deref(&self) -> &Self::Target {
16704        &self.0
16705    }
16706}
16707
16708impl<T> DerefMut for InvalidationStack<T> {
16709    fn deref_mut(&mut self) -> &mut Self::Target {
16710        &mut self.0
16711    }
16712}
16713
16714impl InvalidationRegion for SnippetState {
16715    fn ranges(&self) -> &[Range<Anchor>] {
16716        &self.ranges[self.active_index]
16717    }
16718}
16719
16720pub fn diagnostic_block_renderer(
16721    diagnostic: Diagnostic,
16722    max_message_rows: Option<u8>,
16723    allow_closing: bool,
16724    _is_valid: bool,
16725) -> RenderBlock {
16726    let (text_without_backticks, code_ranges) =
16727        highlight_diagnostic_message(&diagnostic, max_message_rows);
16728
16729    Arc::new(move |cx: &mut BlockContext| {
16730        let group_id: SharedString = cx.block_id.to_string().into();
16731
16732        let mut text_style = cx.window.text_style().clone();
16733        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16734        let theme_settings = ThemeSettings::get_global(cx);
16735        text_style.font_family = theme_settings.buffer_font.family.clone();
16736        text_style.font_style = theme_settings.buffer_font.style;
16737        text_style.font_features = theme_settings.buffer_font.features.clone();
16738        text_style.font_weight = theme_settings.buffer_font.weight;
16739
16740        let multi_line_diagnostic = diagnostic.message.contains('\n');
16741
16742        let buttons = |diagnostic: &Diagnostic| {
16743            if multi_line_diagnostic {
16744                v_flex()
16745            } else {
16746                h_flex()
16747            }
16748            .when(allow_closing, |div| {
16749                div.children(diagnostic.is_primary.then(|| {
16750                    IconButton::new("close-block", IconName::XCircle)
16751                        .icon_color(Color::Muted)
16752                        .size(ButtonSize::Compact)
16753                        .style(ButtonStyle::Transparent)
16754                        .visible_on_hover(group_id.clone())
16755                        .on_click(move |_click, window, cx| {
16756                            window.dispatch_action(Box::new(Cancel), cx)
16757                        })
16758                        .tooltip(|window, cx| {
16759                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16760                        })
16761                }))
16762            })
16763            .child(
16764                IconButton::new("copy-block", IconName::Copy)
16765                    .icon_color(Color::Muted)
16766                    .size(ButtonSize::Compact)
16767                    .style(ButtonStyle::Transparent)
16768                    .visible_on_hover(group_id.clone())
16769                    .on_click({
16770                        let message = diagnostic.message.clone();
16771                        move |_click, _, cx| {
16772                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16773                        }
16774                    })
16775                    .tooltip(Tooltip::text("Copy diagnostic message")),
16776            )
16777        };
16778
16779        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16780            AvailableSpace::min_size(),
16781            cx.window,
16782            cx.app,
16783        );
16784
16785        h_flex()
16786            .id(cx.block_id)
16787            .group(group_id.clone())
16788            .relative()
16789            .size_full()
16790            .block_mouse_down()
16791            .pl(cx.gutter_dimensions.width)
16792            .w(cx.max_width - cx.gutter_dimensions.full_width())
16793            .child(
16794                div()
16795                    .flex()
16796                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16797                    .flex_shrink(),
16798            )
16799            .child(buttons(&diagnostic))
16800            .child(div().flex().flex_shrink_0().child(
16801                StyledText::new(text_without_backticks.clone()).with_highlights(
16802                    &text_style,
16803                    code_ranges.iter().map(|range| {
16804                        (
16805                            range.clone(),
16806                            HighlightStyle {
16807                                font_weight: Some(FontWeight::BOLD),
16808                                ..Default::default()
16809                            },
16810                        )
16811                    }),
16812                ),
16813            ))
16814            .into_any_element()
16815    })
16816}
16817
16818fn inline_completion_edit_text(
16819    current_snapshot: &BufferSnapshot,
16820    edits: &[(Range<Anchor>, String)],
16821    edit_preview: &EditPreview,
16822    include_deletions: bool,
16823    cx: &App,
16824) -> HighlightedText {
16825    let edits = edits
16826        .iter()
16827        .map(|(anchor, text)| {
16828            (
16829                anchor.start.text_anchor..anchor.end.text_anchor,
16830                text.clone(),
16831            )
16832        })
16833        .collect::<Vec<_>>();
16834
16835    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16836}
16837
16838pub fn highlight_diagnostic_message(
16839    diagnostic: &Diagnostic,
16840    mut max_message_rows: Option<u8>,
16841) -> (SharedString, Vec<Range<usize>>) {
16842    let mut text_without_backticks = String::new();
16843    let mut code_ranges = Vec::new();
16844
16845    if let Some(source) = &diagnostic.source {
16846        text_without_backticks.push_str(source);
16847        code_ranges.push(0..source.len());
16848        text_without_backticks.push_str(": ");
16849    }
16850
16851    let mut prev_offset = 0;
16852    let mut in_code_block = false;
16853    let has_row_limit = max_message_rows.is_some();
16854    let mut newline_indices = diagnostic
16855        .message
16856        .match_indices('\n')
16857        .filter(|_| has_row_limit)
16858        .map(|(ix, _)| ix)
16859        .fuse()
16860        .peekable();
16861
16862    for (quote_ix, _) in diagnostic
16863        .message
16864        .match_indices('`')
16865        .chain([(diagnostic.message.len(), "")])
16866    {
16867        let mut first_newline_ix = None;
16868        let mut last_newline_ix = None;
16869        while let Some(newline_ix) = newline_indices.peek() {
16870            if *newline_ix < quote_ix {
16871                if first_newline_ix.is_none() {
16872                    first_newline_ix = Some(*newline_ix);
16873                }
16874                last_newline_ix = Some(*newline_ix);
16875
16876                if let Some(rows_left) = &mut max_message_rows {
16877                    if *rows_left == 0 {
16878                        break;
16879                    } else {
16880                        *rows_left -= 1;
16881                    }
16882                }
16883                let _ = newline_indices.next();
16884            } else {
16885                break;
16886            }
16887        }
16888        let prev_len = text_without_backticks.len();
16889        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16890        text_without_backticks.push_str(new_text);
16891        if in_code_block {
16892            code_ranges.push(prev_len..text_without_backticks.len());
16893        }
16894        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16895        in_code_block = !in_code_block;
16896        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16897            text_without_backticks.push_str("...");
16898            break;
16899        }
16900    }
16901
16902    (text_without_backticks.into(), code_ranges)
16903}
16904
16905fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16906    match severity {
16907        DiagnosticSeverity::ERROR => colors.error,
16908        DiagnosticSeverity::WARNING => colors.warning,
16909        DiagnosticSeverity::INFORMATION => colors.info,
16910        DiagnosticSeverity::HINT => colors.info,
16911        _ => colors.ignored,
16912    }
16913}
16914
16915pub fn styled_runs_for_code_label<'a>(
16916    label: &'a CodeLabel,
16917    syntax_theme: &'a theme::SyntaxTheme,
16918) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16919    let fade_out = HighlightStyle {
16920        fade_out: Some(0.35),
16921        ..Default::default()
16922    };
16923
16924    let mut prev_end = label.filter_range.end;
16925    label
16926        .runs
16927        .iter()
16928        .enumerate()
16929        .flat_map(move |(ix, (range, highlight_id))| {
16930            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16931                style
16932            } else {
16933                return Default::default();
16934            };
16935            let mut muted_style = style;
16936            muted_style.highlight(fade_out);
16937
16938            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16939            if range.start >= label.filter_range.end {
16940                if range.start > prev_end {
16941                    runs.push((prev_end..range.start, fade_out));
16942                }
16943                runs.push((range.clone(), muted_style));
16944            } else if range.end <= label.filter_range.end {
16945                runs.push((range.clone(), style));
16946            } else {
16947                runs.push((range.start..label.filter_range.end, style));
16948                runs.push((label.filter_range.end..range.end, muted_style));
16949            }
16950            prev_end = cmp::max(prev_end, range.end);
16951
16952            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16953                runs.push((prev_end..label.text.len(), fade_out));
16954            }
16955
16956            runs
16957        })
16958}
16959
16960pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16961    let mut prev_index = 0;
16962    let mut prev_codepoint: Option<char> = None;
16963    text.char_indices()
16964        .chain([(text.len(), '\0')])
16965        .filter_map(move |(index, codepoint)| {
16966            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16967            let is_boundary = index == text.len()
16968                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16969                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16970            if is_boundary {
16971                let chunk = &text[prev_index..index];
16972                prev_index = index;
16973                Some(chunk)
16974            } else {
16975                None
16976            }
16977        })
16978}
16979
16980pub trait RangeToAnchorExt: Sized {
16981    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16982
16983    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16984        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16985        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16986    }
16987}
16988
16989impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16990    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16991        let start_offset = self.start.to_offset(snapshot);
16992        let end_offset = self.end.to_offset(snapshot);
16993        if start_offset == end_offset {
16994            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16995        } else {
16996            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16997        }
16998    }
16999}
17000
17001pub trait RowExt {
17002    fn as_f32(&self) -> f32;
17003
17004    fn next_row(&self) -> Self;
17005
17006    fn previous_row(&self) -> Self;
17007
17008    fn minus(&self, other: Self) -> u32;
17009}
17010
17011impl RowExt for DisplayRow {
17012    fn as_f32(&self) -> f32 {
17013        self.0 as f32
17014    }
17015
17016    fn next_row(&self) -> Self {
17017        Self(self.0 + 1)
17018    }
17019
17020    fn previous_row(&self) -> Self {
17021        Self(self.0.saturating_sub(1))
17022    }
17023
17024    fn minus(&self, other: Self) -> u32 {
17025        self.0 - other.0
17026    }
17027}
17028
17029impl RowExt for MultiBufferRow {
17030    fn as_f32(&self) -> f32 {
17031        self.0 as f32
17032    }
17033
17034    fn next_row(&self) -> Self {
17035        Self(self.0 + 1)
17036    }
17037
17038    fn previous_row(&self) -> Self {
17039        Self(self.0.saturating_sub(1))
17040    }
17041
17042    fn minus(&self, other: Self) -> u32 {
17043        self.0 - other.0
17044    }
17045}
17046
17047trait RowRangeExt {
17048    type Row;
17049
17050    fn len(&self) -> usize;
17051
17052    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17053}
17054
17055impl RowRangeExt for Range<MultiBufferRow> {
17056    type Row = MultiBufferRow;
17057
17058    fn len(&self) -> usize {
17059        (self.end.0 - self.start.0) as usize
17060    }
17061
17062    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17063        (self.start.0..self.end.0).map(MultiBufferRow)
17064    }
17065}
17066
17067impl RowRangeExt for Range<DisplayRow> {
17068    type Row = DisplayRow;
17069
17070    fn len(&self) -> usize {
17071        (self.end.0 - self.start.0) as usize
17072    }
17073
17074    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17075        (self.start.0..self.end.0).map(DisplayRow)
17076    }
17077}
17078
17079/// If select range has more than one line, we
17080/// just point the cursor to range.start.
17081fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17082    if range.start.row == range.end.row {
17083        range
17084    } else {
17085        range.start..range.start
17086    }
17087}
17088pub struct KillRing(ClipboardItem);
17089impl Global for KillRing {}
17090
17091const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17092
17093fn all_edits_insertions_or_deletions(
17094    edits: &Vec<(Range<Anchor>, String)>,
17095    snapshot: &MultiBufferSnapshot,
17096) -> bool {
17097    let mut all_insertions = true;
17098    let mut all_deletions = true;
17099
17100    for (range, new_text) in edits.iter() {
17101        let range_is_empty = range.to_offset(&snapshot).is_empty();
17102        let text_is_empty = new_text.is_empty();
17103
17104        if range_is_empty != text_is_empty {
17105            if range_is_empty {
17106                all_deletions = false;
17107            } else {
17108                all_insertions = false;
17109            }
17110        } else {
17111            return false;
17112        }
17113
17114        if !all_insertions && !all_deletions {
17115            return false;
17116        }
17117    }
17118    all_insertions || all_deletions
17119}