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    CompletionDocumentation, CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview,
  103    HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
  104    SelectionGoal, TextObject, 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::{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            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2207        {
 2208            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2209                let background_executor = cx.background_executor().clone();
 2210                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2211                let snapshot = self.buffer().read(cx).snapshot(cx);
 2212                let selections = selections.clone();
 2213                self.serialize_selections = cx.background_spawn(async move {
 2214                    background_executor.timer(Duration::from_millis(100)).await;
 2215                    let selections = selections
 2216                        .iter()
 2217                        .map(|selection| {
 2218                            (
 2219                                selection.start.to_offset(&snapshot),
 2220                                selection.end.to_offset(&snapshot),
 2221                            )
 2222                        })
 2223                        .collect();
 2224                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2225                        .await
 2226                        .context("persisting editor selections")
 2227                        .log_err();
 2228                });
 2229            }
 2230        }
 2231
 2232        cx.notify();
 2233    }
 2234
 2235    pub fn change_selections<R>(
 2236        &mut self,
 2237        autoscroll: Option<Autoscroll>,
 2238        window: &mut Window,
 2239        cx: &mut Context<Self>,
 2240        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2241    ) -> R {
 2242        self.change_selections_inner(autoscroll, true, window, cx, change)
 2243    }
 2244
 2245    fn change_selections_inner<R>(
 2246        &mut self,
 2247        autoscroll: Option<Autoscroll>,
 2248        request_completions: bool,
 2249        window: &mut Window,
 2250        cx: &mut Context<Self>,
 2251        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2252    ) -> R {
 2253        let old_cursor_position = self.selections.newest_anchor().head();
 2254        self.push_to_selection_history();
 2255
 2256        let (changed, result) = self.selections.change_with(cx, change);
 2257
 2258        if changed {
 2259            if let Some(autoscroll) = autoscroll {
 2260                self.request_autoscroll(autoscroll, cx);
 2261            }
 2262            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2263
 2264            if self.should_open_signature_help_automatically(
 2265                &old_cursor_position,
 2266                self.signature_help_state.backspace_pressed(),
 2267                cx,
 2268            ) {
 2269                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2270            }
 2271            self.signature_help_state.set_backspace_pressed(false);
 2272        }
 2273
 2274        result
 2275    }
 2276
 2277    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2278    where
 2279        I: IntoIterator<Item = (Range<S>, T)>,
 2280        S: ToOffset,
 2281        T: Into<Arc<str>>,
 2282    {
 2283        if self.read_only(cx) {
 2284            return;
 2285        }
 2286
 2287        self.buffer
 2288            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2289    }
 2290
 2291    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2292    where
 2293        I: IntoIterator<Item = (Range<S>, T)>,
 2294        S: ToOffset,
 2295        T: Into<Arc<str>>,
 2296    {
 2297        if self.read_only(cx) {
 2298            return;
 2299        }
 2300
 2301        self.buffer.update(cx, |buffer, cx| {
 2302            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2303        });
 2304    }
 2305
 2306    pub fn edit_with_block_indent<I, S, T>(
 2307        &mut self,
 2308        edits: I,
 2309        original_indent_columns: Vec<u32>,
 2310        cx: &mut Context<Self>,
 2311    ) where
 2312        I: IntoIterator<Item = (Range<S>, T)>,
 2313        S: ToOffset,
 2314        T: Into<Arc<str>>,
 2315    {
 2316        if self.read_only(cx) {
 2317            return;
 2318        }
 2319
 2320        self.buffer.update(cx, |buffer, cx| {
 2321            buffer.edit(
 2322                edits,
 2323                Some(AutoindentMode::Block {
 2324                    original_indent_columns,
 2325                }),
 2326                cx,
 2327            )
 2328        });
 2329    }
 2330
 2331    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2332        self.hide_context_menu(window, cx);
 2333
 2334        match phase {
 2335            SelectPhase::Begin {
 2336                position,
 2337                add,
 2338                click_count,
 2339            } => self.begin_selection(position, add, click_count, window, cx),
 2340            SelectPhase::BeginColumnar {
 2341                position,
 2342                goal_column,
 2343                reset,
 2344            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2345            SelectPhase::Extend {
 2346                position,
 2347                click_count,
 2348            } => self.extend_selection(position, click_count, window, cx),
 2349            SelectPhase::Update {
 2350                position,
 2351                goal_column,
 2352                scroll_delta,
 2353            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2354            SelectPhase::End => self.end_selection(window, cx),
 2355        }
 2356    }
 2357
 2358    fn extend_selection(
 2359        &mut self,
 2360        position: DisplayPoint,
 2361        click_count: usize,
 2362        window: &mut Window,
 2363        cx: &mut Context<Self>,
 2364    ) {
 2365        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2366        let tail = self.selections.newest::<usize>(cx).tail();
 2367        self.begin_selection(position, false, click_count, window, cx);
 2368
 2369        let position = position.to_offset(&display_map, Bias::Left);
 2370        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2371
 2372        let mut pending_selection = self
 2373            .selections
 2374            .pending_anchor()
 2375            .expect("extend_selection not called with pending selection");
 2376        if position >= tail {
 2377            pending_selection.start = tail_anchor;
 2378        } else {
 2379            pending_selection.end = tail_anchor;
 2380            pending_selection.reversed = true;
 2381        }
 2382
 2383        let mut pending_mode = self.selections.pending_mode().unwrap();
 2384        match &mut pending_mode {
 2385            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2386            _ => {}
 2387        }
 2388
 2389        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2390            s.set_pending(pending_selection, pending_mode)
 2391        });
 2392    }
 2393
 2394    fn begin_selection(
 2395        &mut self,
 2396        position: DisplayPoint,
 2397        add: bool,
 2398        click_count: usize,
 2399        window: &mut Window,
 2400        cx: &mut Context<Self>,
 2401    ) {
 2402        if !self.focus_handle.is_focused(window) {
 2403            self.last_focused_descendant = None;
 2404            window.focus(&self.focus_handle);
 2405        }
 2406
 2407        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2408        let buffer = &display_map.buffer_snapshot;
 2409        let newest_selection = self.selections.newest_anchor().clone();
 2410        let position = display_map.clip_point(position, Bias::Left);
 2411
 2412        let start;
 2413        let end;
 2414        let mode;
 2415        let mut auto_scroll;
 2416        match click_count {
 2417            1 => {
 2418                start = buffer.anchor_before(position.to_point(&display_map));
 2419                end = start;
 2420                mode = SelectMode::Character;
 2421                auto_scroll = true;
 2422            }
 2423            2 => {
 2424                let range = movement::surrounding_word(&display_map, position);
 2425                start = buffer.anchor_before(range.start.to_point(&display_map));
 2426                end = buffer.anchor_before(range.end.to_point(&display_map));
 2427                mode = SelectMode::Word(start..end);
 2428                auto_scroll = true;
 2429            }
 2430            3 => {
 2431                let position = display_map
 2432                    .clip_point(position, Bias::Left)
 2433                    .to_point(&display_map);
 2434                let line_start = display_map.prev_line_boundary(position).0;
 2435                let next_line_start = buffer.clip_point(
 2436                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2437                    Bias::Left,
 2438                );
 2439                start = buffer.anchor_before(line_start);
 2440                end = buffer.anchor_before(next_line_start);
 2441                mode = SelectMode::Line(start..end);
 2442                auto_scroll = true;
 2443            }
 2444            _ => {
 2445                start = buffer.anchor_before(0);
 2446                end = buffer.anchor_before(buffer.len());
 2447                mode = SelectMode::All;
 2448                auto_scroll = false;
 2449            }
 2450        }
 2451        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2452
 2453        let point_to_delete: Option<usize> = {
 2454            let selected_points: Vec<Selection<Point>> =
 2455                self.selections.disjoint_in_range(start..end, cx);
 2456
 2457            if !add || click_count > 1 {
 2458                None
 2459            } else if !selected_points.is_empty() {
 2460                Some(selected_points[0].id)
 2461            } else {
 2462                let clicked_point_already_selected =
 2463                    self.selections.disjoint.iter().find(|selection| {
 2464                        selection.start.to_point(buffer) == start.to_point(buffer)
 2465                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2466                    });
 2467
 2468                clicked_point_already_selected.map(|selection| selection.id)
 2469            }
 2470        };
 2471
 2472        let selections_count = self.selections.count();
 2473
 2474        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2475            if let Some(point_to_delete) = point_to_delete {
 2476                s.delete(point_to_delete);
 2477
 2478                if selections_count == 1 {
 2479                    s.set_pending_anchor_range(start..end, mode);
 2480                }
 2481            } else {
 2482                if !add {
 2483                    s.clear_disjoint();
 2484                } else if click_count > 1 {
 2485                    s.delete(newest_selection.id)
 2486                }
 2487
 2488                s.set_pending_anchor_range(start..end, mode);
 2489            }
 2490        });
 2491    }
 2492
 2493    fn begin_columnar_selection(
 2494        &mut self,
 2495        position: DisplayPoint,
 2496        goal_column: u32,
 2497        reset: bool,
 2498        window: &mut Window,
 2499        cx: &mut Context<Self>,
 2500    ) {
 2501        if !self.focus_handle.is_focused(window) {
 2502            self.last_focused_descendant = None;
 2503            window.focus(&self.focus_handle);
 2504        }
 2505
 2506        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2507
 2508        if reset {
 2509            let pointer_position = display_map
 2510                .buffer_snapshot
 2511                .anchor_before(position.to_point(&display_map));
 2512
 2513            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2514                s.clear_disjoint();
 2515                s.set_pending_anchor_range(
 2516                    pointer_position..pointer_position,
 2517                    SelectMode::Character,
 2518                );
 2519            });
 2520        }
 2521
 2522        let tail = self.selections.newest::<Point>(cx).tail();
 2523        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2524
 2525        if !reset {
 2526            self.select_columns(
 2527                tail.to_display_point(&display_map),
 2528                position,
 2529                goal_column,
 2530                &display_map,
 2531                window,
 2532                cx,
 2533            );
 2534        }
 2535    }
 2536
 2537    fn update_selection(
 2538        &mut self,
 2539        position: DisplayPoint,
 2540        goal_column: u32,
 2541        scroll_delta: gpui::Point<f32>,
 2542        window: &mut Window,
 2543        cx: &mut Context<Self>,
 2544    ) {
 2545        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2546
 2547        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2548            let tail = tail.to_display_point(&display_map);
 2549            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2550        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2551            let buffer = self.buffer.read(cx).snapshot(cx);
 2552            let head;
 2553            let tail;
 2554            let mode = self.selections.pending_mode().unwrap();
 2555            match &mode {
 2556                SelectMode::Character => {
 2557                    head = position.to_point(&display_map);
 2558                    tail = pending.tail().to_point(&buffer);
 2559                }
 2560                SelectMode::Word(original_range) => {
 2561                    let original_display_range = original_range.start.to_display_point(&display_map)
 2562                        ..original_range.end.to_display_point(&display_map);
 2563                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2564                        ..original_display_range.end.to_point(&display_map);
 2565                    if movement::is_inside_word(&display_map, position)
 2566                        || original_display_range.contains(&position)
 2567                    {
 2568                        let word_range = movement::surrounding_word(&display_map, position);
 2569                        if word_range.start < original_display_range.start {
 2570                            head = word_range.start.to_point(&display_map);
 2571                        } else {
 2572                            head = word_range.end.to_point(&display_map);
 2573                        }
 2574                    } else {
 2575                        head = position.to_point(&display_map);
 2576                    }
 2577
 2578                    if head <= original_buffer_range.start {
 2579                        tail = original_buffer_range.end;
 2580                    } else {
 2581                        tail = original_buffer_range.start;
 2582                    }
 2583                }
 2584                SelectMode::Line(original_range) => {
 2585                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2586
 2587                    let position = display_map
 2588                        .clip_point(position, Bias::Left)
 2589                        .to_point(&display_map);
 2590                    let line_start = display_map.prev_line_boundary(position).0;
 2591                    let next_line_start = buffer.clip_point(
 2592                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2593                        Bias::Left,
 2594                    );
 2595
 2596                    if line_start < original_range.start {
 2597                        head = line_start
 2598                    } else {
 2599                        head = next_line_start
 2600                    }
 2601
 2602                    if head <= original_range.start {
 2603                        tail = original_range.end;
 2604                    } else {
 2605                        tail = original_range.start;
 2606                    }
 2607                }
 2608                SelectMode::All => {
 2609                    return;
 2610                }
 2611            };
 2612
 2613            if head < tail {
 2614                pending.start = buffer.anchor_before(head);
 2615                pending.end = buffer.anchor_before(tail);
 2616                pending.reversed = true;
 2617            } else {
 2618                pending.start = buffer.anchor_before(tail);
 2619                pending.end = buffer.anchor_before(head);
 2620                pending.reversed = false;
 2621            }
 2622
 2623            self.change_selections(None, window, cx, |s| {
 2624                s.set_pending(pending, mode);
 2625            });
 2626        } else {
 2627            log::error!("update_selection dispatched with no pending selection");
 2628            return;
 2629        }
 2630
 2631        self.apply_scroll_delta(scroll_delta, window, cx);
 2632        cx.notify();
 2633    }
 2634
 2635    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2636        self.columnar_selection_tail.take();
 2637        if self.selections.pending_anchor().is_some() {
 2638            let selections = self.selections.all::<usize>(cx);
 2639            self.change_selections(None, window, cx, |s| {
 2640                s.select(selections);
 2641                s.clear_pending();
 2642            });
 2643        }
 2644    }
 2645
 2646    fn select_columns(
 2647        &mut self,
 2648        tail: DisplayPoint,
 2649        head: DisplayPoint,
 2650        goal_column: u32,
 2651        display_map: &DisplaySnapshot,
 2652        window: &mut Window,
 2653        cx: &mut Context<Self>,
 2654    ) {
 2655        let start_row = cmp::min(tail.row(), head.row());
 2656        let end_row = cmp::max(tail.row(), head.row());
 2657        let start_column = cmp::min(tail.column(), goal_column);
 2658        let end_column = cmp::max(tail.column(), goal_column);
 2659        let reversed = start_column < tail.column();
 2660
 2661        let selection_ranges = (start_row.0..=end_row.0)
 2662            .map(DisplayRow)
 2663            .filter_map(|row| {
 2664                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2665                    let start = display_map
 2666                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2667                        .to_point(display_map);
 2668                    let end = display_map
 2669                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2670                        .to_point(display_map);
 2671                    if reversed {
 2672                        Some(end..start)
 2673                    } else {
 2674                        Some(start..end)
 2675                    }
 2676                } else {
 2677                    None
 2678                }
 2679            })
 2680            .collect::<Vec<_>>();
 2681
 2682        self.change_selections(None, window, cx, |s| {
 2683            s.select_ranges(selection_ranges);
 2684        });
 2685        cx.notify();
 2686    }
 2687
 2688    pub fn has_pending_nonempty_selection(&self) -> bool {
 2689        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2690            Some(Selection { start, end, .. }) => start != end,
 2691            None => false,
 2692        };
 2693
 2694        pending_nonempty_selection
 2695            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2696    }
 2697
 2698    pub fn has_pending_selection(&self) -> bool {
 2699        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2700    }
 2701
 2702    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2703        self.selection_mark_mode = false;
 2704
 2705        if self.clear_expanded_diff_hunks(cx) {
 2706            cx.notify();
 2707            return;
 2708        }
 2709        if self.dismiss_menus_and_popups(true, window, cx) {
 2710            return;
 2711        }
 2712
 2713        if self.mode == EditorMode::Full
 2714            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2715        {
 2716            return;
 2717        }
 2718
 2719        cx.propagate();
 2720    }
 2721
 2722    pub fn dismiss_menus_and_popups(
 2723        &mut self,
 2724        is_user_requested: bool,
 2725        window: &mut Window,
 2726        cx: &mut Context<Self>,
 2727    ) -> bool {
 2728        if self.take_rename(false, window, cx).is_some() {
 2729            return true;
 2730        }
 2731
 2732        if hide_hover(self, cx) {
 2733            return true;
 2734        }
 2735
 2736        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2737            return true;
 2738        }
 2739
 2740        if self.hide_context_menu(window, cx).is_some() {
 2741            return true;
 2742        }
 2743
 2744        if self.mouse_context_menu.take().is_some() {
 2745            return true;
 2746        }
 2747
 2748        if is_user_requested && self.discard_inline_completion(true, cx) {
 2749            return true;
 2750        }
 2751
 2752        if self.snippet_stack.pop().is_some() {
 2753            return true;
 2754        }
 2755
 2756        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2757            self.dismiss_diagnostics(cx);
 2758            return true;
 2759        }
 2760
 2761        false
 2762    }
 2763
 2764    fn linked_editing_ranges_for(
 2765        &self,
 2766        selection: Range<text::Anchor>,
 2767        cx: &App,
 2768    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2769        if self.linked_edit_ranges.is_empty() {
 2770            return None;
 2771        }
 2772        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2773            selection.end.buffer_id.and_then(|end_buffer_id| {
 2774                if selection.start.buffer_id != Some(end_buffer_id) {
 2775                    return None;
 2776                }
 2777                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2778                let snapshot = buffer.read(cx).snapshot();
 2779                self.linked_edit_ranges
 2780                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2781                    .map(|ranges| (ranges, snapshot, buffer))
 2782            })?;
 2783        use text::ToOffset as TO;
 2784        // find offset from the start of current range to current cursor position
 2785        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2786
 2787        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2788        let start_difference = start_offset - start_byte_offset;
 2789        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2790        let end_difference = end_offset - start_byte_offset;
 2791        // Current range has associated linked ranges.
 2792        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2793        for range in linked_ranges.iter() {
 2794            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2795            let end_offset = start_offset + end_difference;
 2796            let start_offset = start_offset + start_difference;
 2797            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2798                continue;
 2799            }
 2800            if self.selections.disjoint_anchor_ranges().any(|s| {
 2801                if s.start.buffer_id != selection.start.buffer_id
 2802                    || s.end.buffer_id != selection.end.buffer_id
 2803                {
 2804                    return false;
 2805                }
 2806                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2807                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2808            }) {
 2809                continue;
 2810            }
 2811            let start = buffer_snapshot.anchor_after(start_offset);
 2812            let end = buffer_snapshot.anchor_after(end_offset);
 2813            linked_edits
 2814                .entry(buffer.clone())
 2815                .or_default()
 2816                .push(start..end);
 2817        }
 2818        Some(linked_edits)
 2819    }
 2820
 2821    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2822        let text: Arc<str> = text.into();
 2823
 2824        if self.read_only(cx) {
 2825            return;
 2826        }
 2827
 2828        let selections = self.selections.all_adjusted(cx);
 2829        let mut bracket_inserted = false;
 2830        let mut edits = Vec::new();
 2831        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2832        let mut new_selections = Vec::with_capacity(selections.len());
 2833        let mut new_autoclose_regions = Vec::new();
 2834        let snapshot = self.buffer.read(cx).read(cx);
 2835
 2836        for (selection, autoclose_region) in
 2837            self.selections_with_autoclose_regions(selections, &snapshot)
 2838        {
 2839            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2840                // Determine if the inserted text matches the opening or closing
 2841                // bracket of any of this language's bracket pairs.
 2842                let mut bracket_pair = None;
 2843                let mut is_bracket_pair_start = false;
 2844                let mut is_bracket_pair_end = false;
 2845                if !text.is_empty() {
 2846                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2847                    //  and they are removing the character that triggered IME popup.
 2848                    for (pair, enabled) in scope.brackets() {
 2849                        if !pair.close && !pair.surround {
 2850                            continue;
 2851                        }
 2852
 2853                        if enabled && pair.start.ends_with(text.as_ref()) {
 2854                            let prefix_len = pair.start.len() - text.len();
 2855                            let preceding_text_matches_prefix = prefix_len == 0
 2856                                || (selection.start.column >= (prefix_len as u32)
 2857                                    && snapshot.contains_str_at(
 2858                                        Point::new(
 2859                                            selection.start.row,
 2860                                            selection.start.column - (prefix_len as u32),
 2861                                        ),
 2862                                        &pair.start[..prefix_len],
 2863                                    ));
 2864                            if preceding_text_matches_prefix {
 2865                                bracket_pair = Some(pair.clone());
 2866                                is_bracket_pair_start = true;
 2867                                break;
 2868                            }
 2869                        }
 2870                        if pair.end.as_str() == text.as_ref() {
 2871                            bracket_pair = Some(pair.clone());
 2872                            is_bracket_pair_end = true;
 2873                            break;
 2874                        }
 2875                    }
 2876                }
 2877
 2878                if let Some(bracket_pair) = bracket_pair {
 2879                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2880                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2881                    let auto_surround =
 2882                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2883                    if selection.is_empty() {
 2884                        if is_bracket_pair_start {
 2885                            // If the inserted text is a suffix of an opening bracket and the
 2886                            // selection is preceded by the rest of the opening bracket, then
 2887                            // insert the closing bracket.
 2888                            let following_text_allows_autoclose = snapshot
 2889                                .chars_at(selection.start)
 2890                                .next()
 2891                                .map_or(true, |c| scope.should_autoclose_before(c));
 2892
 2893                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2894                                && bracket_pair.start.len() == 1
 2895                            {
 2896                                let target = bracket_pair.start.chars().next().unwrap();
 2897                                let current_line_count = snapshot
 2898                                    .reversed_chars_at(selection.start)
 2899                                    .take_while(|&c| c != '\n')
 2900                                    .filter(|&c| c == target)
 2901                                    .count();
 2902                                current_line_count % 2 == 1
 2903                            } else {
 2904                                false
 2905                            };
 2906
 2907                            if autoclose
 2908                                && bracket_pair.close
 2909                                && following_text_allows_autoclose
 2910                                && !is_closing_quote
 2911                            {
 2912                                let anchor = snapshot.anchor_before(selection.end);
 2913                                new_selections.push((selection.map(|_| anchor), text.len()));
 2914                                new_autoclose_regions.push((
 2915                                    anchor,
 2916                                    text.len(),
 2917                                    selection.id,
 2918                                    bracket_pair.clone(),
 2919                                ));
 2920                                edits.push((
 2921                                    selection.range(),
 2922                                    format!("{}{}", text, bracket_pair.end).into(),
 2923                                ));
 2924                                bracket_inserted = true;
 2925                                continue;
 2926                            }
 2927                        }
 2928
 2929                        if let Some(region) = autoclose_region {
 2930                            // If the selection is followed by an auto-inserted closing bracket,
 2931                            // then don't insert that closing bracket again; just move the selection
 2932                            // past the closing bracket.
 2933                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2934                                && text.as_ref() == region.pair.end.as_str();
 2935                            if should_skip {
 2936                                let anchor = snapshot.anchor_after(selection.end);
 2937                                new_selections
 2938                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2939                                continue;
 2940                            }
 2941                        }
 2942
 2943                        let always_treat_brackets_as_autoclosed = snapshot
 2944                            .settings_at(selection.start, cx)
 2945                            .always_treat_brackets_as_autoclosed;
 2946                        if always_treat_brackets_as_autoclosed
 2947                            && is_bracket_pair_end
 2948                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2949                        {
 2950                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2951                            // and the inserted text is a closing bracket and the selection is followed
 2952                            // by the closing bracket then move the selection past the closing bracket.
 2953                            let anchor = snapshot.anchor_after(selection.end);
 2954                            new_selections.push((selection.map(|_| anchor), text.len()));
 2955                            continue;
 2956                        }
 2957                    }
 2958                    // If an opening bracket is 1 character long and is typed while
 2959                    // text is selected, then surround that text with the bracket pair.
 2960                    else if auto_surround
 2961                        && bracket_pair.surround
 2962                        && is_bracket_pair_start
 2963                        && bracket_pair.start.chars().count() == 1
 2964                    {
 2965                        edits.push((selection.start..selection.start, text.clone()));
 2966                        edits.push((
 2967                            selection.end..selection.end,
 2968                            bracket_pair.end.as_str().into(),
 2969                        ));
 2970                        bracket_inserted = true;
 2971                        new_selections.push((
 2972                            Selection {
 2973                                id: selection.id,
 2974                                start: snapshot.anchor_after(selection.start),
 2975                                end: snapshot.anchor_before(selection.end),
 2976                                reversed: selection.reversed,
 2977                                goal: selection.goal,
 2978                            },
 2979                            0,
 2980                        ));
 2981                        continue;
 2982                    }
 2983                }
 2984            }
 2985
 2986            if self.auto_replace_emoji_shortcode
 2987                && selection.is_empty()
 2988                && text.as_ref().ends_with(':')
 2989            {
 2990                if let Some(possible_emoji_short_code) =
 2991                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2992                {
 2993                    if !possible_emoji_short_code.is_empty() {
 2994                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2995                            let emoji_shortcode_start = Point::new(
 2996                                selection.start.row,
 2997                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2998                            );
 2999
 3000                            // Remove shortcode from buffer
 3001                            edits.push((
 3002                                emoji_shortcode_start..selection.start,
 3003                                "".to_string().into(),
 3004                            ));
 3005                            new_selections.push((
 3006                                Selection {
 3007                                    id: selection.id,
 3008                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3009                                    end: snapshot.anchor_before(selection.start),
 3010                                    reversed: selection.reversed,
 3011                                    goal: selection.goal,
 3012                                },
 3013                                0,
 3014                            ));
 3015
 3016                            // Insert emoji
 3017                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3018                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3019                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3020
 3021                            continue;
 3022                        }
 3023                    }
 3024                }
 3025            }
 3026
 3027            // If not handling any auto-close operation, then just replace the selected
 3028            // text with the given input and move the selection to the end of the
 3029            // newly inserted text.
 3030            let anchor = snapshot.anchor_after(selection.end);
 3031            if !self.linked_edit_ranges.is_empty() {
 3032                let start_anchor = snapshot.anchor_before(selection.start);
 3033
 3034                let is_word_char = text.chars().next().map_or(true, |char| {
 3035                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3036                    classifier.is_word(char)
 3037                });
 3038
 3039                if is_word_char {
 3040                    if let Some(ranges) = self
 3041                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3042                    {
 3043                        for (buffer, edits) in ranges {
 3044                            linked_edits
 3045                                .entry(buffer.clone())
 3046                                .or_default()
 3047                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3048                        }
 3049                    }
 3050                }
 3051            }
 3052
 3053            new_selections.push((selection.map(|_| anchor), 0));
 3054            edits.push((selection.start..selection.end, text.clone()));
 3055        }
 3056
 3057        drop(snapshot);
 3058
 3059        self.transact(window, cx, |this, window, cx| {
 3060            this.buffer.update(cx, |buffer, cx| {
 3061                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3062            });
 3063            for (buffer, edits) in linked_edits {
 3064                buffer.update(cx, |buffer, cx| {
 3065                    let snapshot = buffer.snapshot();
 3066                    let edits = edits
 3067                        .into_iter()
 3068                        .map(|(range, text)| {
 3069                            use text::ToPoint as TP;
 3070                            let end_point = TP::to_point(&range.end, &snapshot);
 3071                            let start_point = TP::to_point(&range.start, &snapshot);
 3072                            (start_point..end_point, text)
 3073                        })
 3074                        .sorted_by_key(|(range, _)| range.start)
 3075                        .collect::<Vec<_>>();
 3076                    buffer.edit(edits, None, cx);
 3077                })
 3078            }
 3079            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3080            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3081            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3082            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3083                .zip(new_selection_deltas)
 3084                .map(|(selection, delta)| Selection {
 3085                    id: selection.id,
 3086                    start: selection.start + delta,
 3087                    end: selection.end + delta,
 3088                    reversed: selection.reversed,
 3089                    goal: SelectionGoal::None,
 3090                })
 3091                .collect::<Vec<_>>();
 3092
 3093            let mut i = 0;
 3094            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3095                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3096                let start = map.buffer_snapshot.anchor_before(position);
 3097                let end = map.buffer_snapshot.anchor_after(position);
 3098                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3099                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3100                        Ordering::Less => i += 1,
 3101                        Ordering::Greater => break,
 3102                        Ordering::Equal => {
 3103                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3104                                Ordering::Less => i += 1,
 3105                                Ordering::Equal => break,
 3106                                Ordering::Greater => break,
 3107                            }
 3108                        }
 3109                    }
 3110                }
 3111                this.autoclose_regions.insert(
 3112                    i,
 3113                    AutocloseRegion {
 3114                        selection_id,
 3115                        range: start..end,
 3116                        pair,
 3117                    },
 3118                );
 3119            }
 3120
 3121            let had_active_inline_completion = this.has_active_inline_completion();
 3122            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3123                s.select(new_selections)
 3124            });
 3125
 3126            if !bracket_inserted {
 3127                if let Some(on_type_format_task) =
 3128                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3129                {
 3130                    on_type_format_task.detach_and_log_err(cx);
 3131                }
 3132            }
 3133
 3134            let editor_settings = EditorSettings::get_global(cx);
 3135            if bracket_inserted
 3136                && (editor_settings.auto_signature_help
 3137                    || editor_settings.show_signature_help_after_edits)
 3138            {
 3139                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3140            }
 3141
 3142            let trigger_in_words =
 3143                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3144            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3145            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3146            this.refresh_inline_completion(true, false, window, cx);
 3147        });
 3148    }
 3149
 3150    fn find_possible_emoji_shortcode_at_position(
 3151        snapshot: &MultiBufferSnapshot,
 3152        position: Point,
 3153    ) -> Option<String> {
 3154        let mut chars = Vec::new();
 3155        let mut found_colon = false;
 3156        for char in snapshot.reversed_chars_at(position).take(100) {
 3157            // Found a possible emoji shortcode in the middle of the buffer
 3158            if found_colon {
 3159                if char.is_whitespace() {
 3160                    chars.reverse();
 3161                    return Some(chars.iter().collect());
 3162                }
 3163                // If the previous character is not a whitespace, we are in the middle of a word
 3164                // and we only want to complete the shortcode if the word is made up of other emojis
 3165                let mut containing_word = String::new();
 3166                for ch in snapshot
 3167                    .reversed_chars_at(position)
 3168                    .skip(chars.len() + 1)
 3169                    .take(100)
 3170                {
 3171                    if ch.is_whitespace() {
 3172                        break;
 3173                    }
 3174                    containing_word.push(ch);
 3175                }
 3176                let containing_word = containing_word.chars().rev().collect::<String>();
 3177                if util::word_consists_of_emojis(containing_word.as_str()) {
 3178                    chars.reverse();
 3179                    return Some(chars.iter().collect());
 3180                }
 3181            }
 3182
 3183            if char.is_whitespace() || !char.is_ascii() {
 3184                return None;
 3185            }
 3186            if char == ':' {
 3187                found_colon = true;
 3188            } else {
 3189                chars.push(char);
 3190            }
 3191        }
 3192        // Found a possible emoji shortcode at the beginning of the buffer
 3193        chars.reverse();
 3194        Some(chars.iter().collect())
 3195    }
 3196
 3197    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3198        self.transact(window, cx, |this, window, cx| {
 3199            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3200                let selections = this.selections.all::<usize>(cx);
 3201                let multi_buffer = this.buffer.read(cx);
 3202                let buffer = multi_buffer.snapshot(cx);
 3203                selections
 3204                    .iter()
 3205                    .map(|selection| {
 3206                        let start_point = selection.start.to_point(&buffer);
 3207                        let mut indent =
 3208                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3209                        indent.len = cmp::min(indent.len, start_point.column);
 3210                        let start = selection.start;
 3211                        let end = selection.end;
 3212                        let selection_is_empty = start == end;
 3213                        let language_scope = buffer.language_scope_at(start);
 3214                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3215                            &language_scope
 3216                        {
 3217                            let leading_whitespace_len = buffer
 3218                                .reversed_chars_at(start)
 3219                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3220                                .map(|c| c.len_utf8())
 3221                                .sum::<usize>();
 3222
 3223                            let trailing_whitespace_len = buffer
 3224                                .chars_at(end)
 3225                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3226                                .map(|c| c.len_utf8())
 3227                                .sum::<usize>();
 3228
 3229                            let insert_extra_newline =
 3230                                language.brackets().any(|(pair, enabled)| {
 3231                                    let pair_start = pair.start.trim_end();
 3232                                    let pair_end = pair.end.trim_start();
 3233
 3234                                    enabled
 3235                                        && pair.newline
 3236                                        && buffer.contains_str_at(
 3237                                            end + trailing_whitespace_len,
 3238                                            pair_end,
 3239                                        )
 3240                                        && buffer.contains_str_at(
 3241                                            (start - leading_whitespace_len)
 3242                                                .saturating_sub(pair_start.len()),
 3243                                            pair_start,
 3244                                        )
 3245                                });
 3246
 3247                            // Comment extension on newline is allowed only for cursor selections
 3248                            let comment_delimiter = maybe!({
 3249                                if !selection_is_empty {
 3250                                    return None;
 3251                                }
 3252
 3253                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3254                                    return None;
 3255                                }
 3256
 3257                                let delimiters = language.line_comment_prefixes();
 3258                                let max_len_of_delimiter =
 3259                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3260                                let (snapshot, range) =
 3261                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3262
 3263                                let mut index_of_first_non_whitespace = 0;
 3264                                let comment_candidate = snapshot
 3265                                    .chars_for_range(range)
 3266                                    .skip_while(|c| {
 3267                                        let should_skip = c.is_whitespace();
 3268                                        if should_skip {
 3269                                            index_of_first_non_whitespace += 1;
 3270                                        }
 3271                                        should_skip
 3272                                    })
 3273                                    .take(max_len_of_delimiter)
 3274                                    .collect::<String>();
 3275                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3276                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3277                                })?;
 3278                                let cursor_is_placed_after_comment_marker =
 3279                                    index_of_first_non_whitespace + comment_prefix.len()
 3280                                        <= start_point.column as usize;
 3281                                if cursor_is_placed_after_comment_marker {
 3282                                    Some(comment_prefix.clone())
 3283                                } else {
 3284                                    None
 3285                                }
 3286                            });
 3287                            (comment_delimiter, insert_extra_newline)
 3288                        } else {
 3289                            (None, false)
 3290                        };
 3291
 3292                        let capacity_for_delimiter = comment_delimiter
 3293                            .as_deref()
 3294                            .map(str::len)
 3295                            .unwrap_or_default();
 3296                        let mut new_text =
 3297                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3298                        new_text.push('\n');
 3299                        new_text.extend(indent.chars());
 3300                        if let Some(delimiter) = &comment_delimiter {
 3301                            new_text.push_str(delimiter);
 3302                        }
 3303                        if insert_extra_newline {
 3304                            new_text = new_text.repeat(2);
 3305                        }
 3306
 3307                        let anchor = buffer.anchor_after(end);
 3308                        let new_selection = selection.map(|_| anchor);
 3309                        (
 3310                            (start..end, new_text),
 3311                            (insert_extra_newline, new_selection),
 3312                        )
 3313                    })
 3314                    .unzip()
 3315            };
 3316
 3317            this.edit_with_autoindent(edits, cx);
 3318            let buffer = this.buffer.read(cx).snapshot(cx);
 3319            let new_selections = selection_fixup_info
 3320                .into_iter()
 3321                .map(|(extra_newline_inserted, new_selection)| {
 3322                    let mut cursor = new_selection.end.to_point(&buffer);
 3323                    if extra_newline_inserted {
 3324                        cursor.row -= 1;
 3325                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3326                    }
 3327                    new_selection.map(|_| cursor)
 3328                })
 3329                .collect();
 3330
 3331            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3332                s.select(new_selections)
 3333            });
 3334            this.refresh_inline_completion(true, false, window, cx);
 3335        });
 3336    }
 3337
 3338    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3339        let buffer = self.buffer.read(cx);
 3340        let snapshot = buffer.snapshot(cx);
 3341
 3342        let mut edits = Vec::new();
 3343        let mut rows = Vec::new();
 3344
 3345        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3346            let cursor = selection.head();
 3347            let row = cursor.row;
 3348
 3349            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3350
 3351            let newline = "\n".to_string();
 3352            edits.push((start_of_line..start_of_line, newline));
 3353
 3354            rows.push(row + rows_inserted as u32);
 3355        }
 3356
 3357        self.transact(window, cx, |editor, window, cx| {
 3358            editor.edit(edits, cx);
 3359
 3360            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3361                let mut index = 0;
 3362                s.move_cursors_with(|map, _, _| {
 3363                    let row = rows[index];
 3364                    index += 1;
 3365
 3366                    let point = Point::new(row, 0);
 3367                    let boundary = map.next_line_boundary(point).1;
 3368                    let clipped = map.clip_point(boundary, Bias::Left);
 3369
 3370                    (clipped, SelectionGoal::None)
 3371                });
 3372            });
 3373
 3374            let mut indent_edits = Vec::new();
 3375            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3376            for row in rows {
 3377                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3378                for (row, indent) in indents {
 3379                    if indent.len == 0 {
 3380                        continue;
 3381                    }
 3382
 3383                    let text = match indent.kind {
 3384                        IndentKind::Space => " ".repeat(indent.len as usize),
 3385                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3386                    };
 3387                    let point = Point::new(row.0, 0);
 3388                    indent_edits.push((point..point, text));
 3389                }
 3390            }
 3391            editor.edit(indent_edits, cx);
 3392        });
 3393    }
 3394
 3395    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3396        let buffer = self.buffer.read(cx);
 3397        let snapshot = buffer.snapshot(cx);
 3398
 3399        let mut edits = Vec::new();
 3400        let mut rows = Vec::new();
 3401        let mut rows_inserted = 0;
 3402
 3403        for selection in self.selections.all_adjusted(cx) {
 3404            let cursor = selection.head();
 3405            let row = cursor.row;
 3406
 3407            let point = Point::new(row + 1, 0);
 3408            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3409
 3410            let newline = "\n".to_string();
 3411            edits.push((start_of_line..start_of_line, newline));
 3412
 3413            rows_inserted += 1;
 3414            rows.push(row + rows_inserted);
 3415        }
 3416
 3417        self.transact(window, cx, |editor, window, cx| {
 3418            editor.edit(edits, cx);
 3419
 3420            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3421                let mut index = 0;
 3422                s.move_cursors_with(|map, _, _| {
 3423                    let row = rows[index];
 3424                    index += 1;
 3425
 3426                    let point = Point::new(row, 0);
 3427                    let boundary = map.next_line_boundary(point).1;
 3428                    let clipped = map.clip_point(boundary, Bias::Left);
 3429
 3430                    (clipped, SelectionGoal::None)
 3431                });
 3432            });
 3433
 3434            let mut indent_edits = Vec::new();
 3435            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3436            for row in rows {
 3437                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3438                for (row, indent) in indents {
 3439                    if indent.len == 0 {
 3440                        continue;
 3441                    }
 3442
 3443                    let text = match indent.kind {
 3444                        IndentKind::Space => " ".repeat(indent.len as usize),
 3445                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3446                    };
 3447                    let point = Point::new(row.0, 0);
 3448                    indent_edits.push((point..point, text));
 3449                }
 3450            }
 3451            editor.edit(indent_edits, cx);
 3452        });
 3453    }
 3454
 3455    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3456        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3457            original_indent_columns: Vec::new(),
 3458        });
 3459        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3460    }
 3461
 3462    fn insert_with_autoindent_mode(
 3463        &mut self,
 3464        text: &str,
 3465        autoindent_mode: Option<AutoindentMode>,
 3466        window: &mut Window,
 3467        cx: &mut Context<Self>,
 3468    ) {
 3469        if self.read_only(cx) {
 3470            return;
 3471        }
 3472
 3473        let text: Arc<str> = text.into();
 3474        self.transact(window, cx, |this, window, cx| {
 3475            let old_selections = this.selections.all_adjusted(cx);
 3476            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3477                let anchors = {
 3478                    let snapshot = buffer.read(cx);
 3479                    old_selections
 3480                        .iter()
 3481                        .map(|s| {
 3482                            let anchor = snapshot.anchor_after(s.head());
 3483                            s.map(|_| anchor)
 3484                        })
 3485                        .collect::<Vec<_>>()
 3486                };
 3487                buffer.edit(
 3488                    old_selections
 3489                        .iter()
 3490                        .map(|s| (s.start..s.end, text.clone())),
 3491                    autoindent_mode,
 3492                    cx,
 3493                );
 3494                anchors
 3495            });
 3496
 3497            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3498                s.select_anchors(selection_anchors);
 3499            });
 3500
 3501            cx.notify();
 3502        });
 3503    }
 3504
 3505    fn trigger_completion_on_input(
 3506        &mut self,
 3507        text: &str,
 3508        trigger_in_words: bool,
 3509        window: &mut Window,
 3510        cx: &mut Context<Self>,
 3511    ) {
 3512        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3513            self.show_completions(
 3514                &ShowCompletions {
 3515                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3516                },
 3517                window,
 3518                cx,
 3519            );
 3520        } else {
 3521            self.hide_context_menu(window, cx);
 3522        }
 3523    }
 3524
 3525    fn is_completion_trigger(
 3526        &self,
 3527        text: &str,
 3528        trigger_in_words: bool,
 3529        cx: &mut Context<Self>,
 3530    ) -> bool {
 3531        let position = self.selections.newest_anchor().head();
 3532        let multibuffer = self.buffer.read(cx);
 3533        let Some(buffer) = position
 3534            .buffer_id
 3535            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3536        else {
 3537            return false;
 3538        };
 3539
 3540        if let Some(completion_provider) = &self.completion_provider {
 3541            completion_provider.is_completion_trigger(
 3542                &buffer,
 3543                position.text_anchor,
 3544                text,
 3545                trigger_in_words,
 3546                cx,
 3547            )
 3548        } else {
 3549            false
 3550        }
 3551    }
 3552
 3553    /// If any empty selections is touching the start of its innermost containing autoclose
 3554    /// region, expand it to select the brackets.
 3555    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3556        let selections = self.selections.all::<usize>(cx);
 3557        let buffer = self.buffer.read(cx).read(cx);
 3558        let new_selections = self
 3559            .selections_with_autoclose_regions(selections, &buffer)
 3560            .map(|(mut selection, region)| {
 3561                if !selection.is_empty() {
 3562                    return selection;
 3563                }
 3564
 3565                if let Some(region) = region {
 3566                    let mut range = region.range.to_offset(&buffer);
 3567                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3568                        range.start -= region.pair.start.len();
 3569                        if buffer.contains_str_at(range.start, &region.pair.start)
 3570                            && buffer.contains_str_at(range.end, &region.pair.end)
 3571                        {
 3572                            range.end += region.pair.end.len();
 3573                            selection.start = range.start;
 3574                            selection.end = range.end;
 3575
 3576                            return selection;
 3577                        }
 3578                    }
 3579                }
 3580
 3581                let always_treat_brackets_as_autoclosed = buffer
 3582                    .settings_at(selection.start, cx)
 3583                    .always_treat_brackets_as_autoclosed;
 3584
 3585                if !always_treat_brackets_as_autoclosed {
 3586                    return selection;
 3587                }
 3588
 3589                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3590                    for (pair, enabled) in scope.brackets() {
 3591                        if !enabled || !pair.close {
 3592                            continue;
 3593                        }
 3594
 3595                        if buffer.contains_str_at(selection.start, &pair.end) {
 3596                            let pair_start_len = pair.start.len();
 3597                            if buffer.contains_str_at(
 3598                                selection.start.saturating_sub(pair_start_len),
 3599                                &pair.start,
 3600                            ) {
 3601                                selection.start -= pair_start_len;
 3602                                selection.end += pair.end.len();
 3603
 3604                                return selection;
 3605                            }
 3606                        }
 3607                    }
 3608                }
 3609
 3610                selection
 3611            })
 3612            .collect();
 3613
 3614        drop(buffer);
 3615        self.change_selections(None, window, cx, |selections| {
 3616            selections.select(new_selections)
 3617        });
 3618    }
 3619
 3620    /// Iterate the given selections, and for each one, find the smallest surrounding
 3621    /// autoclose region. This uses the ordering of the selections and the autoclose
 3622    /// regions to avoid repeated comparisons.
 3623    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3624        &'a self,
 3625        selections: impl IntoIterator<Item = Selection<D>>,
 3626        buffer: &'a MultiBufferSnapshot,
 3627    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3628        let mut i = 0;
 3629        let mut regions = self.autoclose_regions.as_slice();
 3630        selections.into_iter().map(move |selection| {
 3631            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3632
 3633            let mut enclosing = None;
 3634            while let Some(pair_state) = regions.get(i) {
 3635                if pair_state.range.end.to_offset(buffer) < range.start {
 3636                    regions = &regions[i + 1..];
 3637                    i = 0;
 3638                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3639                    break;
 3640                } else {
 3641                    if pair_state.selection_id == selection.id {
 3642                        enclosing = Some(pair_state);
 3643                    }
 3644                    i += 1;
 3645                }
 3646            }
 3647
 3648            (selection, enclosing)
 3649        })
 3650    }
 3651
 3652    /// Remove any autoclose regions that no longer contain their selection.
 3653    fn invalidate_autoclose_regions(
 3654        &mut self,
 3655        mut selections: &[Selection<Anchor>],
 3656        buffer: &MultiBufferSnapshot,
 3657    ) {
 3658        self.autoclose_regions.retain(|state| {
 3659            let mut i = 0;
 3660            while let Some(selection) = selections.get(i) {
 3661                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3662                    selections = &selections[1..];
 3663                    continue;
 3664                }
 3665                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3666                    break;
 3667                }
 3668                if selection.id == state.selection_id {
 3669                    return true;
 3670                } else {
 3671                    i += 1;
 3672                }
 3673            }
 3674            false
 3675        });
 3676    }
 3677
 3678    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3679        let offset = position.to_offset(buffer);
 3680        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3681        if offset > word_range.start && kind == Some(CharKind::Word) {
 3682            Some(
 3683                buffer
 3684                    .text_for_range(word_range.start..offset)
 3685                    .collect::<String>(),
 3686            )
 3687        } else {
 3688            None
 3689        }
 3690    }
 3691
 3692    pub fn toggle_inlay_hints(
 3693        &mut self,
 3694        _: &ToggleInlayHints,
 3695        _: &mut Window,
 3696        cx: &mut Context<Self>,
 3697    ) {
 3698        self.refresh_inlay_hints(
 3699            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3700            cx,
 3701        );
 3702    }
 3703
 3704    pub fn inlay_hints_enabled(&self) -> bool {
 3705        self.inlay_hint_cache.enabled
 3706    }
 3707
 3708    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3709        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3710            return;
 3711        }
 3712
 3713        let reason_description = reason.description();
 3714        let ignore_debounce = matches!(
 3715            reason,
 3716            InlayHintRefreshReason::SettingsChange(_)
 3717                | InlayHintRefreshReason::Toggle(_)
 3718                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3719        );
 3720        let (invalidate_cache, required_languages) = match reason {
 3721            InlayHintRefreshReason::Toggle(enabled) => {
 3722                self.inlay_hint_cache.enabled = enabled;
 3723                if enabled {
 3724                    (InvalidationStrategy::RefreshRequested, None)
 3725                } else {
 3726                    self.inlay_hint_cache.clear();
 3727                    self.splice_inlays(
 3728                        &self
 3729                            .visible_inlay_hints(cx)
 3730                            .iter()
 3731                            .map(|inlay| inlay.id)
 3732                            .collect::<Vec<InlayId>>(),
 3733                        Vec::new(),
 3734                        cx,
 3735                    );
 3736                    return;
 3737                }
 3738            }
 3739            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3740                match self.inlay_hint_cache.update_settings(
 3741                    &self.buffer,
 3742                    new_settings,
 3743                    self.visible_inlay_hints(cx),
 3744                    cx,
 3745                ) {
 3746                    ControlFlow::Break(Some(InlaySplice {
 3747                        to_remove,
 3748                        to_insert,
 3749                    })) => {
 3750                        self.splice_inlays(&to_remove, to_insert, cx);
 3751                        return;
 3752                    }
 3753                    ControlFlow::Break(None) => return,
 3754                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3755                }
 3756            }
 3757            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3758                if let Some(InlaySplice {
 3759                    to_remove,
 3760                    to_insert,
 3761                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3762                {
 3763                    self.splice_inlays(&to_remove, to_insert, cx);
 3764                }
 3765                return;
 3766            }
 3767            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3768            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3769                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3770            }
 3771            InlayHintRefreshReason::RefreshRequested => {
 3772                (InvalidationStrategy::RefreshRequested, None)
 3773            }
 3774        };
 3775
 3776        if let Some(InlaySplice {
 3777            to_remove,
 3778            to_insert,
 3779        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3780            reason_description,
 3781            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3782            invalidate_cache,
 3783            ignore_debounce,
 3784            cx,
 3785        ) {
 3786            self.splice_inlays(&to_remove, to_insert, cx);
 3787        }
 3788    }
 3789
 3790    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3791        self.display_map
 3792            .read(cx)
 3793            .current_inlays()
 3794            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3795            .cloned()
 3796            .collect()
 3797    }
 3798
 3799    pub fn excerpts_for_inlay_hints_query(
 3800        &self,
 3801        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3802        cx: &mut Context<Editor>,
 3803    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3804        let Some(project) = self.project.as_ref() else {
 3805            return HashMap::default();
 3806        };
 3807        let project = project.read(cx);
 3808        let multi_buffer = self.buffer().read(cx);
 3809        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3810        let multi_buffer_visible_start = self
 3811            .scroll_manager
 3812            .anchor()
 3813            .anchor
 3814            .to_point(&multi_buffer_snapshot);
 3815        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3816            multi_buffer_visible_start
 3817                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3818            Bias::Left,
 3819        );
 3820        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3821        multi_buffer_snapshot
 3822            .range_to_buffer_ranges(multi_buffer_visible_range)
 3823            .into_iter()
 3824            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3825            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3826                let buffer_file = project::File::from_dyn(buffer.file())?;
 3827                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3828                let worktree_entry = buffer_worktree
 3829                    .read(cx)
 3830                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3831                if worktree_entry.is_ignored {
 3832                    return None;
 3833                }
 3834
 3835                let language = buffer.language()?;
 3836                if let Some(restrict_to_languages) = restrict_to_languages {
 3837                    if !restrict_to_languages.contains(language) {
 3838                        return None;
 3839                    }
 3840                }
 3841                Some((
 3842                    excerpt_id,
 3843                    (
 3844                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3845                        buffer.version().clone(),
 3846                        excerpt_visible_range,
 3847                    ),
 3848                ))
 3849            })
 3850            .collect()
 3851    }
 3852
 3853    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3854        TextLayoutDetails {
 3855            text_system: window.text_system().clone(),
 3856            editor_style: self.style.clone().unwrap(),
 3857            rem_size: window.rem_size(),
 3858            scroll_anchor: self.scroll_manager.anchor(),
 3859            visible_rows: self.visible_line_count(),
 3860            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3861        }
 3862    }
 3863
 3864    pub fn splice_inlays(
 3865        &self,
 3866        to_remove: &[InlayId],
 3867        to_insert: Vec<Inlay>,
 3868        cx: &mut Context<Self>,
 3869    ) {
 3870        self.display_map.update(cx, |display_map, cx| {
 3871            display_map.splice_inlays(to_remove, to_insert, cx)
 3872        });
 3873        cx.notify();
 3874    }
 3875
 3876    fn trigger_on_type_formatting(
 3877        &self,
 3878        input: String,
 3879        window: &mut Window,
 3880        cx: &mut Context<Self>,
 3881    ) -> Option<Task<Result<()>>> {
 3882        if input.len() != 1 {
 3883            return None;
 3884        }
 3885
 3886        let project = self.project.as_ref()?;
 3887        let position = self.selections.newest_anchor().head();
 3888        let (buffer, buffer_position) = self
 3889            .buffer
 3890            .read(cx)
 3891            .text_anchor_for_position(position, cx)?;
 3892
 3893        let settings = language_settings::language_settings(
 3894            buffer
 3895                .read(cx)
 3896                .language_at(buffer_position)
 3897                .map(|l| l.name()),
 3898            buffer.read(cx).file(),
 3899            cx,
 3900        );
 3901        if !settings.use_on_type_format {
 3902            return None;
 3903        }
 3904
 3905        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3906        // hence we do LSP request & edit on host side only — add formats to host's history.
 3907        let push_to_lsp_host_history = true;
 3908        // If this is not the host, append its history with new edits.
 3909        let push_to_client_history = project.read(cx).is_via_collab();
 3910
 3911        let on_type_formatting = project.update(cx, |project, cx| {
 3912            project.on_type_format(
 3913                buffer.clone(),
 3914                buffer_position,
 3915                input,
 3916                push_to_lsp_host_history,
 3917                cx,
 3918            )
 3919        });
 3920        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3921            if let Some(transaction) = on_type_formatting.await? {
 3922                if push_to_client_history {
 3923                    buffer
 3924                        .update(&mut cx, |buffer, _| {
 3925                            buffer.push_transaction(transaction, Instant::now());
 3926                        })
 3927                        .ok();
 3928                }
 3929                editor.update(&mut cx, |editor, cx| {
 3930                    editor.refresh_document_highlights(cx);
 3931                })?;
 3932            }
 3933            Ok(())
 3934        }))
 3935    }
 3936
 3937    pub fn show_completions(
 3938        &mut self,
 3939        options: &ShowCompletions,
 3940        window: &mut Window,
 3941        cx: &mut Context<Self>,
 3942    ) {
 3943        if self.pending_rename.is_some() {
 3944            return;
 3945        }
 3946
 3947        let Some(provider) = self.completion_provider.as_ref() else {
 3948            return;
 3949        };
 3950
 3951        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3952            return;
 3953        }
 3954
 3955        let position = self.selections.newest_anchor().head();
 3956        if position.diff_base_anchor.is_some() {
 3957            return;
 3958        }
 3959        let (buffer, buffer_position) =
 3960            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3961                output
 3962            } else {
 3963                return;
 3964            };
 3965        let show_completion_documentation = buffer
 3966            .read(cx)
 3967            .snapshot()
 3968            .settings_at(buffer_position, cx)
 3969            .show_completion_documentation;
 3970
 3971        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3972
 3973        let trigger_kind = match &options.trigger {
 3974            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3975                CompletionTriggerKind::TRIGGER_CHARACTER
 3976            }
 3977            _ => CompletionTriggerKind::INVOKED,
 3978        };
 3979        let completion_context = CompletionContext {
 3980            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3981                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3982                    Some(String::from(trigger))
 3983                } else {
 3984                    None
 3985                }
 3986            }),
 3987            trigger_kind,
 3988        };
 3989        let completions =
 3990            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3991        let sort_completions = provider.sort_completions();
 3992
 3993        let id = post_inc(&mut self.next_completion_id);
 3994        let task = cx.spawn_in(window, |editor, mut cx| {
 3995            async move {
 3996                editor.update(&mut cx, |this, _| {
 3997                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3998                })?;
 3999                let completions = completions.await.log_err();
 4000                let menu = if let Some(completions) = completions {
 4001                    let mut menu = CompletionsMenu::new(
 4002                        id,
 4003                        sort_completions,
 4004                        show_completion_documentation,
 4005                        position,
 4006                        buffer.clone(),
 4007                        completions.into(),
 4008                    );
 4009
 4010                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4011                        .await;
 4012
 4013                    menu.visible().then_some(menu)
 4014                } else {
 4015                    None
 4016                };
 4017
 4018                editor.update_in(&mut cx, |editor, window, cx| {
 4019                    match editor.context_menu.borrow().as_ref() {
 4020                        None => {}
 4021                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4022                            if prev_menu.id > id {
 4023                                return;
 4024                            }
 4025                        }
 4026                        _ => return,
 4027                    }
 4028
 4029                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4030                        let mut menu = menu.unwrap();
 4031                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4032
 4033                        *editor.context_menu.borrow_mut() =
 4034                            Some(CodeContextMenu::Completions(menu));
 4035
 4036                        if editor.show_edit_predictions_in_menu() {
 4037                            editor.update_visible_inline_completion(window, cx);
 4038                        } else {
 4039                            editor.discard_inline_completion(false, cx);
 4040                        }
 4041
 4042                        cx.notify();
 4043                    } else if editor.completion_tasks.len() <= 1 {
 4044                        // If there are no more completion tasks and the last menu was
 4045                        // empty, we should hide it.
 4046                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4047                        // If it was already hidden and we don't show inline
 4048                        // completions in the menu, we should also show the
 4049                        // inline-completion when available.
 4050                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4051                            editor.update_visible_inline_completion(window, cx);
 4052                        }
 4053                    }
 4054                })?;
 4055
 4056                Ok::<_, anyhow::Error>(())
 4057            }
 4058            .log_err()
 4059        });
 4060
 4061        self.completion_tasks.push((id, task));
 4062    }
 4063
 4064    pub fn confirm_completion(
 4065        &mut self,
 4066        action: &ConfirmCompletion,
 4067        window: &mut Window,
 4068        cx: &mut Context<Self>,
 4069    ) -> Option<Task<Result<()>>> {
 4070        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4071    }
 4072
 4073    pub fn compose_completion(
 4074        &mut self,
 4075        action: &ComposeCompletion,
 4076        window: &mut Window,
 4077        cx: &mut Context<Self>,
 4078    ) -> Option<Task<Result<()>>> {
 4079        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4080    }
 4081
 4082    fn do_completion(
 4083        &mut self,
 4084        item_ix: Option<usize>,
 4085        intent: CompletionIntent,
 4086        window: &mut Window,
 4087        cx: &mut Context<Editor>,
 4088    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4089        use language::ToOffset as _;
 4090
 4091        let completions_menu =
 4092            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4093                menu
 4094            } else {
 4095                return None;
 4096            };
 4097
 4098        let entries = completions_menu.entries.borrow();
 4099        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4100        if self.show_edit_predictions_in_menu() {
 4101            self.discard_inline_completion(true, cx);
 4102        }
 4103        let candidate_id = mat.candidate_id;
 4104        drop(entries);
 4105
 4106        let buffer_handle = completions_menu.buffer;
 4107        let completion = completions_menu
 4108            .completions
 4109            .borrow()
 4110            .get(candidate_id)?
 4111            .clone();
 4112        cx.stop_propagation();
 4113
 4114        let snippet;
 4115        let text;
 4116
 4117        if completion.is_snippet() {
 4118            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4119            text = snippet.as_ref().unwrap().text.clone();
 4120        } else {
 4121            snippet = None;
 4122            text = completion.new_text.clone();
 4123        };
 4124        let selections = self.selections.all::<usize>(cx);
 4125        let buffer = buffer_handle.read(cx);
 4126        let old_range = completion.old_range.to_offset(buffer);
 4127        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4128
 4129        let newest_selection = self.selections.newest_anchor();
 4130        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4131            return None;
 4132        }
 4133
 4134        let lookbehind = newest_selection
 4135            .start
 4136            .text_anchor
 4137            .to_offset(buffer)
 4138            .saturating_sub(old_range.start);
 4139        let lookahead = old_range
 4140            .end
 4141            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4142        let mut common_prefix_len = old_text
 4143            .bytes()
 4144            .zip(text.bytes())
 4145            .take_while(|(a, b)| a == b)
 4146            .count();
 4147
 4148        let snapshot = self.buffer.read(cx).snapshot(cx);
 4149        let mut range_to_replace: Option<Range<isize>> = None;
 4150        let mut ranges = Vec::new();
 4151        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4152        for selection in &selections {
 4153            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4154                let start = selection.start.saturating_sub(lookbehind);
 4155                let end = selection.end + lookahead;
 4156                if selection.id == newest_selection.id {
 4157                    range_to_replace = Some(
 4158                        ((start + common_prefix_len) as isize - selection.start as isize)
 4159                            ..(end as isize - selection.start as isize),
 4160                    );
 4161                }
 4162                ranges.push(start + common_prefix_len..end);
 4163            } else {
 4164                common_prefix_len = 0;
 4165                ranges.clear();
 4166                ranges.extend(selections.iter().map(|s| {
 4167                    if s.id == newest_selection.id {
 4168                        range_to_replace = Some(
 4169                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4170                                - selection.start as isize
 4171                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4172                                    - selection.start as isize,
 4173                        );
 4174                        old_range.clone()
 4175                    } else {
 4176                        s.start..s.end
 4177                    }
 4178                }));
 4179                break;
 4180            }
 4181            if !self.linked_edit_ranges.is_empty() {
 4182                let start_anchor = snapshot.anchor_before(selection.head());
 4183                let end_anchor = snapshot.anchor_after(selection.tail());
 4184                if let Some(ranges) = self
 4185                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4186                {
 4187                    for (buffer, edits) in ranges {
 4188                        linked_edits.entry(buffer.clone()).or_default().extend(
 4189                            edits
 4190                                .into_iter()
 4191                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4192                        );
 4193                    }
 4194                }
 4195            }
 4196        }
 4197        let text = &text[common_prefix_len..];
 4198
 4199        cx.emit(EditorEvent::InputHandled {
 4200            utf16_range_to_replace: range_to_replace,
 4201            text: text.into(),
 4202        });
 4203
 4204        self.transact(window, cx, |this, window, cx| {
 4205            if let Some(mut snippet) = snippet {
 4206                snippet.text = text.to_string();
 4207                for tabstop in snippet
 4208                    .tabstops
 4209                    .iter_mut()
 4210                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4211                {
 4212                    tabstop.start -= common_prefix_len as isize;
 4213                    tabstop.end -= common_prefix_len as isize;
 4214                }
 4215
 4216                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4217            } else {
 4218                this.buffer.update(cx, |buffer, cx| {
 4219                    buffer.edit(
 4220                        ranges.iter().map(|range| (range.clone(), text)),
 4221                        this.autoindent_mode.clone(),
 4222                        cx,
 4223                    );
 4224                });
 4225            }
 4226            for (buffer, edits) in linked_edits {
 4227                buffer.update(cx, |buffer, cx| {
 4228                    let snapshot = buffer.snapshot();
 4229                    let edits = edits
 4230                        .into_iter()
 4231                        .map(|(range, text)| {
 4232                            use text::ToPoint as TP;
 4233                            let end_point = TP::to_point(&range.end, &snapshot);
 4234                            let start_point = TP::to_point(&range.start, &snapshot);
 4235                            (start_point..end_point, text)
 4236                        })
 4237                        .sorted_by_key(|(range, _)| range.start)
 4238                        .collect::<Vec<_>>();
 4239                    buffer.edit(edits, None, cx);
 4240                })
 4241            }
 4242
 4243            this.refresh_inline_completion(true, false, window, cx);
 4244        });
 4245
 4246        let show_new_completions_on_confirm = completion
 4247            .confirm
 4248            .as_ref()
 4249            .map_or(false, |confirm| confirm(intent, window, cx));
 4250        if show_new_completions_on_confirm {
 4251            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4252        }
 4253
 4254        let provider = self.completion_provider.as_ref()?;
 4255        drop(completion);
 4256        let apply_edits = provider.apply_additional_edits_for_completion(
 4257            buffer_handle,
 4258            completions_menu.completions.clone(),
 4259            candidate_id,
 4260            true,
 4261            cx,
 4262        );
 4263
 4264        let editor_settings = EditorSettings::get_global(cx);
 4265        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4266            // After the code completion is finished, users often want to know what signatures are needed.
 4267            // so we should automatically call signature_help
 4268            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4269        }
 4270
 4271        Some(cx.foreground_executor().spawn(async move {
 4272            apply_edits.await?;
 4273            Ok(())
 4274        }))
 4275    }
 4276
 4277    pub fn toggle_code_actions(
 4278        &mut self,
 4279        action: &ToggleCodeActions,
 4280        window: &mut Window,
 4281        cx: &mut Context<Self>,
 4282    ) {
 4283        let mut context_menu = self.context_menu.borrow_mut();
 4284        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4285            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4286                // Toggle if we're selecting the same one
 4287                *context_menu = None;
 4288                cx.notify();
 4289                return;
 4290            } else {
 4291                // Otherwise, clear it and start a new one
 4292                *context_menu = None;
 4293                cx.notify();
 4294            }
 4295        }
 4296        drop(context_menu);
 4297        let snapshot = self.snapshot(window, cx);
 4298        let deployed_from_indicator = action.deployed_from_indicator;
 4299        let mut task = self.code_actions_task.take();
 4300        let action = action.clone();
 4301        cx.spawn_in(window, |editor, mut cx| async move {
 4302            while let Some(prev_task) = task {
 4303                prev_task.await.log_err();
 4304                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4305            }
 4306
 4307            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4308                if editor.focus_handle.is_focused(window) {
 4309                    let multibuffer_point = action
 4310                        .deployed_from_indicator
 4311                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4312                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4313                    let (buffer, buffer_row) = snapshot
 4314                        .buffer_snapshot
 4315                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4316                        .and_then(|(buffer_snapshot, range)| {
 4317                            editor
 4318                                .buffer
 4319                                .read(cx)
 4320                                .buffer(buffer_snapshot.remote_id())
 4321                                .map(|buffer| (buffer, range.start.row))
 4322                        })?;
 4323                    let (_, code_actions) = editor
 4324                        .available_code_actions
 4325                        .clone()
 4326                        .and_then(|(location, code_actions)| {
 4327                            let snapshot = location.buffer.read(cx).snapshot();
 4328                            let point_range = location.range.to_point(&snapshot);
 4329                            let point_range = point_range.start.row..=point_range.end.row;
 4330                            if point_range.contains(&buffer_row) {
 4331                                Some((location, code_actions))
 4332                            } else {
 4333                                None
 4334                            }
 4335                        })
 4336                        .unzip();
 4337                    let buffer_id = buffer.read(cx).remote_id();
 4338                    let tasks = editor
 4339                        .tasks
 4340                        .get(&(buffer_id, buffer_row))
 4341                        .map(|t| Arc::new(t.to_owned()));
 4342                    if tasks.is_none() && code_actions.is_none() {
 4343                        return None;
 4344                    }
 4345
 4346                    editor.completion_tasks.clear();
 4347                    editor.discard_inline_completion(false, cx);
 4348                    let task_context =
 4349                        tasks
 4350                            .as_ref()
 4351                            .zip(editor.project.clone())
 4352                            .map(|(tasks, project)| {
 4353                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4354                            });
 4355
 4356                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4357                        let task_context = match task_context {
 4358                            Some(task_context) => task_context.await,
 4359                            None => None,
 4360                        };
 4361                        let resolved_tasks =
 4362                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4363                                Rc::new(ResolvedTasks {
 4364                                    templates: tasks.resolve(&task_context).collect(),
 4365                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4366                                        multibuffer_point.row,
 4367                                        tasks.column,
 4368                                    )),
 4369                                })
 4370                            });
 4371                        let spawn_straight_away = resolved_tasks
 4372                            .as_ref()
 4373                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4374                            && code_actions
 4375                                .as_ref()
 4376                                .map_or(true, |actions| actions.is_empty());
 4377                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4378                            *editor.context_menu.borrow_mut() =
 4379                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4380                                    buffer,
 4381                                    actions: CodeActionContents {
 4382                                        tasks: resolved_tasks,
 4383                                        actions: code_actions,
 4384                                    },
 4385                                    selected_item: Default::default(),
 4386                                    scroll_handle: UniformListScrollHandle::default(),
 4387                                    deployed_from_indicator,
 4388                                }));
 4389                            if spawn_straight_away {
 4390                                if let Some(task) = editor.confirm_code_action(
 4391                                    &ConfirmCodeAction { item_ix: Some(0) },
 4392                                    window,
 4393                                    cx,
 4394                                ) {
 4395                                    cx.notify();
 4396                                    return task;
 4397                                }
 4398                            }
 4399                            cx.notify();
 4400                            Task::ready(Ok(()))
 4401                        }) {
 4402                            task.await
 4403                        } else {
 4404                            Ok(())
 4405                        }
 4406                    }))
 4407                } else {
 4408                    Some(Task::ready(Ok(())))
 4409                }
 4410            })?;
 4411            if let Some(task) = spawned_test_task {
 4412                task.await?;
 4413            }
 4414
 4415            Ok::<_, anyhow::Error>(())
 4416        })
 4417        .detach_and_log_err(cx);
 4418    }
 4419
 4420    pub fn confirm_code_action(
 4421        &mut self,
 4422        action: &ConfirmCodeAction,
 4423        window: &mut Window,
 4424        cx: &mut Context<Self>,
 4425    ) -> Option<Task<Result<()>>> {
 4426        let actions_menu =
 4427            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4428                menu
 4429            } else {
 4430                return None;
 4431            };
 4432        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4433        let action = actions_menu.actions.get(action_ix)?;
 4434        let title = action.label();
 4435        let buffer = actions_menu.buffer;
 4436        let workspace = self.workspace()?;
 4437
 4438        match action {
 4439            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4440                workspace.update(cx, |workspace, cx| {
 4441                    workspace::tasks::schedule_resolved_task(
 4442                        workspace,
 4443                        task_source_kind,
 4444                        resolved_task,
 4445                        false,
 4446                        cx,
 4447                    );
 4448
 4449                    Some(Task::ready(Ok(())))
 4450                })
 4451            }
 4452            CodeActionsItem::CodeAction {
 4453                excerpt_id,
 4454                action,
 4455                provider,
 4456            } => {
 4457                let apply_code_action =
 4458                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4459                let workspace = workspace.downgrade();
 4460                Some(cx.spawn_in(window, |editor, cx| async move {
 4461                    let project_transaction = apply_code_action.await?;
 4462                    Self::open_project_transaction(
 4463                        &editor,
 4464                        workspace,
 4465                        project_transaction,
 4466                        title,
 4467                        cx,
 4468                    )
 4469                    .await
 4470                }))
 4471            }
 4472        }
 4473    }
 4474
 4475    pub async fn open_project_transaction(
 4476        this: &WeakEntity<Editor>,
 4477        workspace: WeakEntity<Workspace>,
 4478        transaction: ProjectTransaction,
 4479        title: String,
 4480        mut cx: AsyncWindowContext,
 4481    ) -> Result<()> {
 4482        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4483        cx.update(|_, cx| {
 4484            entries.sort_unstable_by_key(|(buffer, _)| {
 4485                buffer.read(cx).file().map(|f| f.path().clone())
 4486            });
 4487        })?;
 4488
 4489        // If the project transaction's edits are all contained within this editor, then
 4490        // avoid opening a new editor to display them.
 4491
 4492        if let Some((buffer, transaction)) = entries.first() {
 4493            if entries.len() == 1 {
 4494                let excerpt = this.update(&mut cx, |editor, cx| {
 4495                    editor
 4496                        .buffer()
 4497                        .read(cx)
 4498                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4499                })?;
 4500                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4501                    if excerpted_buffer == *buffer {
 4502                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4503                            let excerpt_range = excerpt_range.to_offset(buffer);
 4504                            buffer
 4505                                .edited_ranges_for_transaction::<usize>(transaction)
 4506                                .all(|range| {
 4507                                    excerpt_range.start <= range.start
 4508                                        && excerpt_range.end >= range.end
 4509                                })
 4510                        })?;
 4511
 4512                        if all_edits_within_excerpt {
 4513                            return Ok(());
 4514                        }
 4515                    }
 4516                }
 4517            }
 4518        } else {
 4519            return Ok(());
 4520        }
 4521
 4522        let mut ranges_to_highlight = Vec::new();
 4523        let excerpt_buffer = cx.new(|cx| {
 4524            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4525            for (buffer_handle, transaction) in &entries {
 4526                let buffer = buffer_handle.read(cx);
 4527                ranges_to_highlight.extend(
 4528                    multibuffer.push_excerpts_with_context_lines(
 4529                        buffer_handle.clone(),
 4530                        buffer
 4531                            .edited_ranges_for_transaction::<usize>(transaction)
 4532                            .collect(),
 4533                        DEFAULT_MULTIBUFFER_CONTEXT,
 4534                        cx,
 4535                    ),
 4536                );
 4537            }
 4538            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4539            multibuffer
 4540        })?;
 4541
 4542        workspace.update_in(&mut cx, |workspace, window, cx| {
 4543            let project = workspace.project().clone();
 4544            let editor = cx
 4545                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4546            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4547            editor.update(cx, |editor, cx| {
 4548                editor.highlight_background::<Self>(
 4549                    &ranges_to_highlight,
 4550                    |theme| theme.editor_highlighted_line_background,
 4551                    cx,
 4552                );
 4553            });
 4554        })?;
 4555
 4556        Ok(())
 4557    }
 4558
 4559    pub fn clear_code_action_providers(&mut self) {
 4560        self.code_action_providers.clear();
 4561        self.available_code_actions.take();
 4562    }
 4563
 4564    pub fn add_code_action_provider(
 4565        &mut self,
 4566        provider: Rc<dyn CodeActionProvider>,
 4567        window: &mut Window,
 4568        cx: &mut Context<Self>,
 4569    ) {
 4570        if self
 4571            .code_action_providers
 4572            .iter()
 4573            .any(|existing_provider| existing_provider.id() == provider.id())
 4574        {
 4575            return;
 4576        }
 4577
 4578        self.code_action_providers.push(provider);
 4579        self.refresh_code_actions(window, cx);
 4580    }
 4581
 4582    pub fn remove_code_action_provider(
 4583        &mut self,
 4584        id: Arc<str>,
 4585        window: &mut Window,
 4586        cx: &mut Context<Self>,
 4587    ) {
 4588        self.code_action_providers
 4589            .retain(|provider| provider.id() != id);
 4590        self.refresh_code_actions(window, cx);
 4591    }
 4592
 4593    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4594        let buffer = self.buffer.read(cx);
 4595        let newest_selection = self.selections.newest_anchor().clone();
 4596        if newest_selection.head().diff_base_anchor.is_some() {
 4597            return None;
 4598        }
 4599        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4600        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4601        if start_buffer != end_buffer {
 4602            return None;
 4603        }
 4604
 4605        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4606            cx.background_executor()
 4607                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4608                .await;
 4609
 4610            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4611                let providers = this.code_action_providers.clone();
 4612                let tasks = this
 4613                    .code_action_providers
 4614                    .iter()
 4615                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4616                    .collect::<Vec<_>>();
 4617                (providers, tasks)
 4618            })?;
 4619
 4620            let mut actions = Vec::new();
 4621            for (provider, provider_actions) in
 4622                providers.into_iter().zip(future::join_all(tasks).await)
 4623            {
 4624                if let Some(provider_actions) = provider_actions.log_err() {
 4625                    actions.extend(provider_actions.into_iter().map(|action| {
 4626                        AvailableCodeAction {
 4627                            excerpt_id: newest_selection.start.excerpt_id,
 4628                            action,
 4629                            provider: provider.clone(),
 4630                        }
 4631                    }));
 4632                }
 4633            }
 4634
 4635            this.update(&mut cx, |this, cx| {
 4636                this.available_code_actions = if actions.is_empty() {
 4637                    None
 4638                } else {
 4639                    Some((
 4640                        Location {
 4641                            buffer: start_buffer,
 4642                            range: start..end,
 4643                        },
 4644                        actions.into(),
 4645                    ))
 4646                };
 4647                cx.notify();
 4648            })
 4649        }));
 4650        None
 4651    }
 4652
 4653    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4654        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4655            self.show_git_blame_inline = false;
 4656
 4657            self.show_git_blame_inline_delay_task =
 4658                Some(cx.spawn_in(window, |this, mut cx| async move {
 4659                    cx.background_executor().timer(delay).await;
 4660
 4661                    this.update(&mut cx, |this, cx| {
 4662                        this.show_git_blame_inline = true;
 4663                        cx.notify();
 4664                    })
 4665                    .log_err();
 4666                }));
 4667        }
 4668    }
 4669
 4670    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4671        if self.pending_rename.is_some() {
 4672            return None;
 4673        }
 4674
 4675        let provider = self.semantics_provider.clone()?;
 4676        let buffer = self.buffer.read(cx);
 4677        let newest_selection = self.selections.newest_anchor().clone();
 4678        let cursor_position = newest_selection.head();
 4679        let (cursor_buffer, cursor_buffer_position) =
 4680            buffer.text_anchor_for_position(cursor_position, cx)?;
 4681        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4682        if cursor_buffer != tail_buffer {
 4683            return None;
 4684        }
 4685        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4686        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4687            cx.background_executor()
 4688                .timer(Duration::from_millis(debounce))
 4689                .await;
 4690
 4691            let highlights = if let Some(highlights) = cx
 4692                .update(|cx| {
 4693                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4694                })
 4695                .ok()
 4696                .flatten()
 4697            {
 4698                highlights.await.log_err()
 4699            } else {
 4700                None
 4701            };
 4702
 4703            if let Some(highlights) = highlights {
 4704                this.update(&mut cx, |this, cx| {
 4705                    if this.pending_rename.is_some() {
 4706                        return;
 4707                    }
 4708
 4709                    let buffer_id = cursor_position.buffer_id;
 4710                    let buffer = this.buffer.read(cx);
 4711                    if !buffer
 4712                        .text_anchor_for_position(cursor_position, cx)
 4713                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4714                    {
 4715                        return;
 4716                    }
 4717
 4718                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4719                    let mut write_ranges = Vec::new();
 4720                    let mut read_ranges = Vec::new();
 4721                    for highlight in highlights {
 4722                        for (excerpt_id, excerpt_range) in
 4723                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4724                        {
 4725                            let start = highlight
 4726                                .range
 4727                                .start
 4728                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4729                            let end = highlight
 4730                                .range
 4731                                .end
 4732                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4733                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4734                                continue;
 4735                            }
 4736
 4737                            let range = Anchor {
 4738                                buffer_id,
 4739                                excerpt_id,
 4740                                text_anchor: start,
 4741                                diff_base_anchor: None,
 4742                            }..Anchor {
 4743                                buffer_id,
 4744                                excerpt_id,
 4745                                text_anchor: end,
 4746                                diff_base_anchor: None,
 4747                            };
 4748                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4749                                write_ranges.push(range);
 4750                            } else {
 4751                                read_ranges.push(range);
 4752                            }
 4753                        }
 4754                    }
 4755
 4756                    this.highlight_background::<DocumentHighlightRead>(
 4757                        &read_ranges,
 4758                        |theme| theme.editor_document_highlight_read_background,
 4759                        cx,
 4760                    );
 4761                    this.highlight_background::<DocumentHighlightWrite>(
 4762                        &write_ranges,
 4763                        |theme| theme.editor_document_highlight_write_background,
 4764                        cx,
 4765                    );
 4766                    cx.notify();
 4767                })
 4768                .log_err();
 4769            }
 4770        }));
 4771        None
 4772    }
 4773
 4774    pub fn refresh_selected_text_highlights(
 4775        &mut self,
 4776        window: &mut Window,
 4777        cx: &mut Context<Editor>,
 4778    ) {
 4779        self.selection_highlight_task.take();
 4780        if !EditorSettings::get_global(cx).selection_highlight {
 4781            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4782            return;
 4783        }
 4784        if self.selections.count() != 1 || self.selections.line_mode {
 4785            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4786            return;
 4787        }
 4788        let selection = self.selections.newest::<Point>(cx);
 4789        if selection.is_empty() || selection.start.row != selection.end.row {
 4790            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4791            return;
 4792        }
 4793        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4794        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4795            cx.background_executor()
 4796                .timer(Duration::from_millis(debounce))
 4797                .await;
 4798            let Some(matches_task) = editor
 4799                .read_with(&mut cx, |editor, cx| {
 4800                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4801                    cx.background_spawn(async move {
 4802                        let mut ranges = Vec::new();
 4803                        let buffer_ranges =
 4804                            vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())];
 4805                        let query = buffer.text_for_range(selection.range()).collect::<String>();
 4806                        for range in buffer_ranges {
 4807                            for (search_buffer, search_range, excerpt_id) in
 4808                                buffer.range_to_buffer_ranges(range)
 4809                            {
 4810                                ranges.extend(
 4811                                    project::search::SearchQuery::text(
 4812                                        query.clone(),
 4813                                        false,
 4814                                        false,
 4815                                        false,
 4816                                        Default::default(),
 4817                                        Default::default(),
 4818                                        None,
 4819                                    )
 4820                                    .unwrap()
 4821                                    .search(search_buffer, Some(search_range.clone()))
 4822                                    .await
 4823                                    .into_iter()
 4824                                    .map(|match_range| {
 4825                                        let start = search_buffer
 4826                                            .anchor_after(search_range.start + match_range.start);
 4827                                        let end = search_buffer
 4828                                            .anchor_before(search_range.start + match_range.end);
 4829                                        Anchor::range_in_buffer(
 4830                                            excerpt_id,
 4831                                            search_buffer.remote_id(),
 4832                                            start..end,
 4833                                        )
 4834                                    }),
 4835                                );
 4836                            }
 4837                        }
 4838                        ranges
 4839                    })
 4840                })
 4841                .log_err()
 4842            else {
 4843                return;
 4844            };
 4845            let matches = matches_task.await;
 4846            editor
 4847                .update_in(&mut cx, |editor, _, cx| {
 4848                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4849                    if !matches.is_empty() {
 4850                        editor.highlight_background::<SelectedTextHighlight>(
 4851                            &matches,
 4852                            |theme| theme.editor_document_highlight_bracket_background,
 4853                            cx,
 4854                        )
 4855                    }
 4856                })
 4857                .log_err();
 4858        }));
 4859    }
 4860
 4861    pub fn refresh_inline_completion(
 4862        &mut self,
 4863        debounce: bool,
 4864        user_requested: bool,
 4865        window: &mut Window,
 4866        cx: &mut Context<Self>,
 4867    ) -> Option<()> {
 4868        let provider = self.edit_prediction_provider()?;
 4869        let cursor = self.selections.newest_anchor().head();
 4870        let (buffer, cursor_buffer_position) =
 4871            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4872
 4873        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4874            self.discard_inline_completion(false, cx);
 4875            return None;
 4876        }
 4877
 4878        if !user_requested
 4879            && (!self.should_show_edit_predictions()
 4880                || !self.is_focused(window)
 4881                || buffer.read(cx).is_empty())
 4882        {
 4883            self.discard_inline_completion(false, cx);
 4884            return None;
 4885        }
 4886
 4887        self.update_visible_inline_completion(window, cx);
 4888        provider.refresh(
 4889            self.project.clone(),
 4890            buffer,
 4891            cursor_buffer_position,
 4892            debounce,
 4893            cx,
 4894        );
 4895        Some(())
 4896    }
 4897
 4898    fn show_edit_predictions_in_menu(&self) -> bool {
 4899        match self.edit_prediction_settings {
 4900            EditPredictionSettings::Disabled => false,
 4901            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4902        }
 4903    }
 4904
 4905    pub fn edit_predictions_enabled(&self) -> bool {
 4906        match self.edit_prediction_settings {
 4907            EditPredictionSettings::Disabled => false,
 4908            EditPredictionSettings::Enabled { .. } => true,
 4909        }
 4910    }
 4911
 4912    fn edit_prediction_requires_modifier(&self) -> bool {
 4913        match self.edit_prediction_settings {
 4914            EditPredictionSettings::Disabled => false,
 4915            EditPredictionSettings::Enabled {
 4916                preview_requires_modifier,
 4917                ..
 4918            } => preview_requires_modifier,
 4919        }
 4920    }
 4921
 4922    fn edit_prediction_settings_at_position(
 4923        &self,
 4924        buffer: &Entity<Buffer>,
 4925        buffer_position: language::Anchor,
 4926        cx: &App,
 4927    ) -> EditPredictionSettings {
 4928        if self.mode != EditorMode::Full
 4929            || !self.show_inline_completions_override.unwrap_or(true)
 4930            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4931        {
 4932            return EditPredictionSettings::Disabled;
 4933        }
 4934
 4935        let buffer = buffer.read(cx);
 4936
 4937        let file = buffer.file();
 4938
 4939        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4940            return EditPredictionSettings::Disabled;
 4941        };
 4942
 4943        let by_provider = matches!(
 4944            self.menu_inline_completions_policy,
 4945            MenuInlineCompletionsPolicy::ByProvider
 4946        );
 4947
 4948        let show_in_menu = by_provider
 4949            && self
 4950                .edit_prediction_provider
 4951                .as_ref()
 4952                .map_or(false, |provider| {
 4953                    provider.provider.show_completions_in_menu()
 4954                });
 4955
 4956        let preview_requires_modifier =
 4957            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4958
 4959        EditPredictionSettings::Enabled {
 4960            show_in_menu,
 4961            preview_requires_modifier,
 4962        }
 4963    }
 4964
 4965    fn should_show_edit_predictions(&self) -> bool {
 4966        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4967    }
 4968
 4969    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4970        matches!(
 4971            self.edit_prediction_preview,
 4972            EditPredictionPreview::Active { .. }
 4973        )
 4974    }
 4975
 4976    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4977        let cursor = self.selections.newest_anchor().head();
 4978        if let Some((buffer, cursor_position)) =
 4979            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4980        {
 4981            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4982        } else {
 4983            false
 4984        }
 4985    }
 4986
 4987    fn inline_completions_enabled_in_buffer(
 4988        &self,
 4989        buffer: &Entity<Buffer>,
 4990        buffer_position: language::Anchor,
 4991        cx: &App,
 4992    ) -> bool {
 4993        maybe!({
 4994            let provider = self.edit_prediction_provider()?;
 4995            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4996                return Some(false);
 4997            }
 4998            let buffer = buffer.read(cx);
 4999            let Some(file) = buffer.file() else {
 5000                return Some(true);
 5001            };
 5002            let settings = all_language_settings(Some(file), cx);
 5003            Some(settings.inline_completions_enabled_for_path(file.path()))
 5004        })
 5005        .unwrap_or(false)
 5006    }
 5007
 5008    fn cycle_inline_completion(
 5009        &mut self,
 5010        direction: Direction,
 5011        window: &mut Window,
 5012        cx: &mut Context<Self>,
 5013    ) -> Option<()> {
 5014        let provider = self.edit_prediction_provider()?;
 5015        let cursor = self.selections.newest_anchor().head();
 5016        let (buffer, cursor_buffer_position) =
 5017            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5018        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5019            return None;
 5020        }
 5021
 5022        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5023        self.update_visible_inline_completion(window, cx);
 5024
 5025        Some(())
 5026    }
 5027
 5028    pub fn show_inline_completion(
 5029        &mut self,
 5030        _: &ShowEditPrediction,
 5031        window: &mut Window,
 5032        cx: &mut Context<Self>,
 5033    ) {
 5034        if !self.has_active_inline_completion() {
 5035            self.refresh_inline_completion(false, true, window, cx);
 5036            return;
 5037        }
 5038
 5039        self.update_visible_inline_completion(window, cx);
 5040    }
 5041
 5042    pub fn display_cursor_names(
 5043        &mut self,
 5044        _: &DisplayCursorNames,
 5045        window: &mut Window,
 5046        cx: &mut Context<Self>,
 5047    ) {
 5048        self.show_cursor_names(window, cx);
 5049    }
 5050
 5051    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5052        self.show_cursor_names = true;
 5053        cx.notify();
 5054        cx.spawn_in(window, |this, mut cx| async move {
 5055            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5056            this.update(&mut cx, |this, cx| {
 5057                this.show_cursor_names = false;
 5058                cx.notify()
 5059            })
 5060            .ok()
 5061        })
 5062        .detach();
 5063    }
 5064
 5065    pub fn next_edit_prediction(
 5066        &mut self,
 5067        _: &NextEditPrediction,
 5068        window: &mut Window,
 5069        cx: &mut Context<Self>,
 5070    ) {
 5071        if self.has_active_inline_completion() {
 5072            self.cycle_inline_completion(Direction::Next, window, cx);
 5073        } else {
 5074            let is_copilot_disabled = self
 5075                .refresh_inline_completion(false, true, window, cx)
 5076                .is_none();
 5077            if is_copilot_disabled {
 5078                cx.propagate();
 5079            }
 5080        }
 5081    }
 5082
 5083    pub fn previous_edit_prediction(
 5084        &mut self,
 5085        _: &PreviousEditPrediction,
 5086        window: &mut Window,
 5087        cx: &mut Context<Self>,
 5088    ) {
 5089        if self.has_active_inline_completion() {
 5090            self.cycle_inline_completion(Direction::Prev, window, cx);
 5091        } else {
 5092            let is_copilot_disabled = self
 5093                .refresh_inline_completion(false, true, window, cx)
 5094                .is_none();
 5095            if is_copilot_disabled {
 5096                cx.propagate();
 5097            }
 5098        }
 5099    }
 5100
 5101    pub fn accept_edit_prediction(
 5102        &mut self,
 5103        _: &AcceptEditPrediction,
 5104        window: &mut Window,
 5105        cx: &mut Context<Self>,
 5106    ) {
 5107        if self.show_edit_predictions_in_menu() {
 5108            self.hide_context_menu(window, cx);
 5109        }
 5110
 5111        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5112            return;
 5113        };
 5114
 5115        self.report_inline_completion_event(
 5116            active_inline_completion.completion_id.clone(),
 5117            true,
 5118            cx,
 5119        );
 5120
 5121        match &active_inline_completion.completion {
 5122            InlineCompletion::Move { target, .. } => {
 5123                let target = *target;
 5124
 5125                if let Some(position_map) = &self.last_position_map {
 5126                    if position_map
 5127                        .visible_row_range
 5128                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5129                        || !self.edit_prediction_requires_modifier()
 5130                    {
 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        &self,
 6224        style: &EditorStyle,
 6225        max_size: Size<Pixels>,
 6226        cx: &mut Context<Editor>,
 6227    ) -> Option<AnyElement> {
 6228        self.context_menu.borrow().as_ref().and_then(|menu| {
 6229            if menu.visible() {
 6230                menu.render_aside(
 6231                    style,
 6232                    max_size,
 6233                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6234                    cx,
 6235                )
 6236            } else {
 6237                None
 6238            }
 6239        })
 6240    }
 6241
 6242    fn hide_context_menu(
 6243        &mut self,
 6244        window: &mut Window,
 6245        cx: &mut Context<Self>,
 6246    ) -> Option<CodeContextMenu> {
 6247        cx.notify();
 6248        self.completion_tasks.clear();
 6249        let context_menu = self.context_menu.borrow_mut().take();
 6250        self.stale_inline_completion_in_menu.take();
 6251        self.update_visible_inline_completion(window, cx);
 6252        context_menu
 6253    }
 6254
 6255    fn show_snippet_choices(
 6256        &mut self,
 6257        choices: &Vec<String>,
 6258        selection: Range<Anchor>,
 6259        cx: &mut Context<Self>,
 6260    ) {
 6261        if selection.start.buffer_id.is_none() {
 6262            return;
 6263        }
 6264        let buffer_id = selection.start.buffer_id.unwrap();
 6265        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6266        let id = post_inc(&mut self.next_completion_id);
 6267
 6268        if let Some(buffer) = buffer {
 6269            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6270                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6271            ));
 6272        }
 6273    }
 6274
 6275    pub fn insert_snippet(
 6276        &mut self,
 6277        insertion_ranges: &[Range<usize>],
 6278        snippet: Snippet,
 6279        window: &mut Window,
 6280        cx: &mut Context<Self>,
 6281    ) -> Result<()> {
 6282        struct Tabstop<T> {
 6283            is_end_tabstop: bool,
 6284            ranges: Vec<Range<T>>,
 6285            choices: Option<Vec<String>>,
 6286        }
 6287
 6288        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6289            let snippet_text: Arc<str> = snippet.text.clone().into();
 6290            buffer.edit(
 6291                insertion_ranges
 6292                    .iter()
 6293                    .cloned()
 6294                    .map(|range| (range, snippet_text.clone())),
 6295                Some(AutoindentMode::EachLine),
 6296                cx,
 6297            );
 6298
 6299            let snapshot = &*buffer.read(cx);
 6300            let snippet = &snippet;
 6301            snippet
 6302                .tabstops
 6303                .iter()
 6304                .map(|tabstop| {
 6305                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6306                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6307                    });
 6308                    let mut tabstop_ranges = tabstop
 6309                        .ranges
 6310                        .iter()
 6311                        .flat_map(|tabstop_range| {
 6312                            let mut delta = 0_isize;
 6313                            insertion_ranges.iter().map(move |insertion_range| {
 6314                                let insertion_start = insertion_range.start as isize + delta;
 6315                                delta +=
 6316                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6317
 6318                                let start = ((insertion_start + tabstop_range.start) as usize)
 6319                                    .min(snapshot.len());
 6320                                let end = ((insertion_start + tabstop_range.end) as usize)
 6321                                    .min(snapshot.len());
 6322                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6323                            })
 6324                        })
 6325                        .collect::<Vec<_>>();
 6326                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6327
 6328                    Tabstop {
 6329                        is_end_tabstop,
 6330                        ranges: tabstop_ranges,
 6331                        choices: tabstop.choices.clone(),
 6332                    }
 6333                })
 6334                .collect::<Vec<_>>()
 6335        });
 6336        if let Some(tabstop) = tabstops.first() {
 6337            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6338                s.select_ranges(tabstop.ranges.iter().cloned());
 6339            });
 6340
 6341            if let Some(choices) = &tabstop.choices {
 6342                if let Some(selection) = tabstop.ranges.first() {
 6343                    self.show_snippet_choices(choices, selection.clone(), cx)
 6344                }
 6345            }
 6346
 6347            // If we're already at the last tabstop and it's at the end of the snippet,
 6348            // we're done, we don't need to keep the state around.
 6349            if !tabstop.is_end_tabstop {
 6350                let choices = tabstops
 6351                    .iter()
 6352                    .map(|tabstop| tabstop.choices.clone())
 6353                    .collect();
 6354
 6355                let ranges = tabstops
 6356                    .into_iter()
 6357                    .map(|tabstop| tabstop.ranges)
 6358                    .collect::<Vec<_>>();
 6359
 6360                self.snippet_stack.push(SnippetState {
 6361                    active_index: 0,
 6362                    ranges,
 6363                    choices,
 6364                });
 6365            }
 6366
 6367            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6368            if self.autoclose_regions.is_empty() {
 6369                let snapshot = self.buffer.read(cx).snapshot(cx);
 6370                for selection in &mut self.selections.all::<Point>(cx) {
 6371                    let selection_head = selection.head();
 6372                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6373                        continue;
 6374                    };
 6375
 6376                    let mut bracket_pair = None;
 6377                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6378                    let prev_chars = snapshot
 6379                        .reversed_chars_at(selection_head)
 6380                        .collect::<String>();
 6381                    for (pair, enabled) in scope.brackets() {
 6382                        if enabled
 6383                            && pair.close
 6384                            && prev_chars.starts_with(pair.start.as_str())
 6385                            && next_chars.starts_with(pair.end.as_str())
 6386                        {
 6387                            bracket_pair = Some(pair.clone());
 6388                            break;
 6389                        }
 6390                    }
 6391                    if let Some(pair) = bracket_pair {
 6392                        let start = snapshot.anchor_after(selection_head);
 6393                        let end = snapshot.anchor_after(selection_head);
 6394                        self.autoclose_regions.push(AutocloseRegion {
 6395                            selection_id: selection.id,
 6396                            range: start..end,
 6397                            pair,
 6398                        });
 6399                    }
 6400                }
 6401            }
 6402        }
 6403        Ok(())
 6404    }
 6405
 6406    pub fn move_to_next_snippet_tabstop(
 6407        &mut self,
 6408        window: &mut Window,
 6409        cx: &mut Context<Self>,
 6410    ) -> bool {
 6411        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6412    }
 6413
 6414    pub fn move_to_prev_snippet_tabstop(
 6415        &mut self,
 6416        window: &mut Window,
 6417        cx: &mut Context<Self>,
 6418    ) -> bool {
 6419        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6420    }
 6421
 6422    pub fn move_to_snippet_tabstop(
 6423        &mut self,
 6424        bias: Bias,
 6425        window: &mut Window,
 6426        cx: &mut Context<Self>,
 6427    ) -> bool {
 6428        if let Some(mut snippet) = self.snippet_stack.pop() {
 6429            match bias {
 6430                Bias::Left => {
 6431                    if snippet.active_index > 0 {
 6432                        snippet.active_index -= 1;
 6433                    } else {
 6434                        self.snippet_stack.push(snippet);
 6435                        return false;
 6436                    }
 6437                }
 6438                Bias::Right => {
 6439                    if snippet.active_index + 1 < snippet.ranges.len() {
 6440                        snippet.active_index += 1;
 6441                    } else {
 6442                        self.snippet_stack.push(snippet);
 6443                        return false;
 6444                    }
 6445                }
 6446            }
 6447            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6448                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6449                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6450                });
 6451
 6452                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6453                    if let Some(selection) = current_ranges.first() {
 6454                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6455                    }
 6456                }
 6457
 6458                // If snippet state is not at the last tabstop, push it back on the stack
 6459                if snippet.active_index + 1 < snippet.ranges.len() {
 6460                    self.snippet_stack.push(snippet);
 6461                }
 6462                return true;
 6463            }
 6464        }
 6465
 6466        false
 6467    }
 6468
 6469    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6470        self.transact(window, cx, |this, window, cx| {
 6471            this.select_all(&SelectAll, window, cx);
 6472            this.insert("", window, cx);
 6473        });
 6474    }
 6475
 6476    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6477        self.transact(window, cx, |this, window, cx| {
 6478            this.select_autoclose_pair(window, cx);
 6479            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6480            if !this.linked_edit_ranges.is_empty() {
 6481                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6482                let snapshot = this.buffer.read(cx).snapshot(cx);
 6483
 6484                for selection in selections.iter() {
 6485                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6486                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6487                    if selection_start.buffer_id != selection_end.buffer_id {
 6488                        continue;
 6489                    }
 6490                    if let Some(ranges) =
 6491                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6492                    {
 6493                        for (buffer, entries) in ranges {
 6494                            linked_ranges.entry(buffer).or_default().extend(entries);
 6495                        }
 6496                    }
 6497                }
 6498            }
 6499
 6500            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6501            if !this.selections.line_mode {
 6502                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6503                for selection in &mut selections {
 6504                    if selection.is_empty() {
 6505                        let old_head = selection.head();
 6506                        let mut new_head =
 6507                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6508                                .to_point(&display_map);
 6509                        if let Some((buffer, line_buffer_range)) = display_map
 6510                            .buffer_snapshot
 6511                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6512                        {
 6513                            let indent_size =
 6514                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6515                            let indent_len = match indent_size.kind {
 6516                                IndentKind::Space => {
 6517                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6518                                }
 6519                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6520                            };
 6521                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6522                                let indent_len = indent_len.get();
 6523                                new_head = cmp::min(
 6524                                    new_head,
 6525                                    MultiBufferPoint::new(
 6526                                        old_head.row,
 6527                                        ((old_head.column - 1) / indent_len) * indent_len,
 6528                                    ),
 6529                                );
 6530                            }
 6531                        }
 6532
 6533                        selection.set_head(new_head, SelectionGoal::None);
 6534                    }
 6535                }
 6536            }
 6537
 6538            this.signature_help_state.set_backspace_pressed(true);
 6539            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6540                s.select(selections)
 6541            });
 6542            this.insert("", window, cx);
 6543            let empty_str: Arc<str> = Arc::from("");
 6544            for (buffer, edits) in linked_ranges {
 6545                let snapshot = buffer.read(cx).snapshot();
 6546                use text::ToPoint as TP;
 6547
 6548                let edits = edits
 6549                    .into_iter()
 6550                    .map(|range| {
 6551                        let end_point = TP::to_point(&range.end, &snapshot);
 6552                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6553
 6554                        if end_point == start_point {
 6555                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6556                                .saturating_sub(1);
 6557                            start_point =
 6558                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6559                        };
 6560
 6561                        (start_point..end_point, empty_str.clone())
 6562                    })
 6563                    .sorted_by_key(|(range, _)| range.start)
 6564                    .collect::<Vec<_>>();
 6565                buffer.update(cx, |this, cx| {
 6566                    this.edit(edits, None, cx);
 6567                })
 6568            }
 6569            this.refresh_inline_completion(true, false, window, cx);
 6570            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6571        });
 6572    }
 6573
 6574    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6575        self.transact(window, cx, |this, window, cx| {
 6576            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6577                let line_mode = s.line_mode;
 6578                s.move_with(|map, selection| {
 6579                    if selection.is_empty() && !line_mode {
 6580                        let cursor = movement::right(map, selection.head());
 6581                        selection.end = cursor;
 6582                        selection.reversed = true;
 6583                        selection.goal = SelectionGoal::None;
 6584                    }
 6585                })
 6586            });
 6587            this.insert("", window, cx);
 6588            this.refresh_inline_completion(true, false, window, cx);
 6589        });
 6590    }
 6591
 6592    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6593        if self.move_to_prev_snippet_tabstop(window, cx) {
 6594            return;
 6595        }
 6596
 6597        self.outdent(&Outdent, window, cx);
 6598    }
 6599
 6600    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6601        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6602            return;
 6603        }
 6604
 6605        let mut selections = self.selections.all_adjusted(cx);
 6606        let buffer = self.buffer.read(cx);
 6607        let snapshot = buffer.snapshot(cx);
 6608        let rows_iter = selections.iter().map(|s| s.head().row);
 6609        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6610
 6611        let mut edits = Vec::new();
 6612        let mut prev_edited_row = 0;
 6613        let mut row_delta = 0;
 6614        for selection in &mut selections {
 6615            if selection.start.row != prev_edited_row {
 6616                row_delta = 0;
 6617            }
 6618            prev_edited_row = selection.end.row;
 6619
 6620            // If the selection is non-empty, then increase the indentation of the selected lines.
 6621            if !selection.is_empty() {
 6622                row_delta =
 6623                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6624                continue;
 6625            }
 6626
 6627            // If the selection is empty and the cursor is in the leading whitespace before the
 6628            // suggested indentation, then auto-indent the line.
 6629            let cursor = selection.head();
 6630            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6631            if let Some(suggested_indent) =
 6632                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6633            {
 6634                if cursor.column < suggested_indent.len
 6635                    && cursor.column <= current_indent.len
 6636                    && current_indent.len <= suggested_indent.len
 6637                {
 6638                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6639                    selection.end = selection.start;
 6640                    if row_delta == 0 {
 6641                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6642                            cursor.row,
 6643                            current_indent,
 6644                            suggested_indent,
 6645                        ));
 6646                        row_delta = suggested_indent.len - current_indent.len;
 6647                    }
 6648                    continue;
 6649                }
 6650            }
 6651
 6652            // Otherwise, insert a hard or soft tab.
 6653            let settings = buffer.settings_at(cursor, cx);
 6654            let tab_size = if settings.hard_tabs {
 6655                IndentSize::tab()
 6656            } else {
 6657                let tab_size = settings.tab_size.get();
 6658                let char_column = snapshot
 6659                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6660                    .flat_map(str::chars)
 6661                    .count()
 6662                    + row_delta as usize;
 6663                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6664                IndentSize::spaces(chars_to_next_tab_stop)
 6665            };
 6666            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6667            selection.end = selection.start;
 6668            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6669            row_delta += tab_size.len;
 6670        }
 6671
 6672        self.transact(window, cx, |this, window, cx| {
 6673            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6674            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6675                s.select(selections)
 6676            });
 6677            this.refresh_inline_completion(true, false, window, cx);
 6678        });
 6679    }
 6680
 6681    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6682        if self.read_only(cx) {
 6683            return;
 6684        }
 6685        let mut selections = self.selections.all::<Point>(cx);
 6686        let mut prev_edited_row = 0;
 6687        let mut row_delta = 0;
 6688        let mut edits = Vec::new();
 6689        let buffer = self.buffer.read(cx);
 6690        let snapshot = buffer.snapshot(cx);
 6691        for selection in &mut selections {
 6692            if selection.start.row != prev_edited_row {
 6693                row_delta = 0;
 6694            }
 6695            prev_edited_row = selection.end.row;
 6696
 6697            row_delta =
 6698                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6699        }
 6700
 6701        self.transact(window, cx, |this, window, cx| {
 6702            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6703            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6704                s.select(selections)
 6705            });
 6706        });
 6707    }
 6708
 6709    fn indent_selection(
 6710        buffer: &MultiBuffer,
 6711        snapshot: &MultiBufferSnapshot,
 6712        selection: &mut Selection<Point>,
 6713        edits: &mut Vec<(Range<Point>, String)>,
 6714        delta_for_start_row: u32,
 6715        cx: &App,
 6716    ) -> u32 {
 6717        let settings = buffer.settings_at(selection.start, cx);
 6718        let tab_size = settings.tab_size.get();
 6719        let indent_kind = if settings.hard_tabs {
 6720            IndentKind::Tab
 6721        } else {
 6722            IndentKind::Space
 6723        };
 6724        let mut start_row = selection.start.row;
 6725        let mut end_row = selection.end.row + 1;
 6726
 6727        // If a selection ends at the beginning of a line, don't indent
 6728        // that last line.
 6729        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6730            end_row -= 1;
 6731        }
 6732
 6733        // Avoid re-indenting a row that has already been indented by a
 6734        // previous selection, but still update this selection's column
 6735        // to reflect that indentation.
 6736        if delta_for_start_row > 0 {
 6737            start_row += 1;
 6738            selection.start.column += delta_for_start_row;
 6739            if selection.end.row == selection.start.row {
 6740                selection.end.column += delta_for_start_row;
 6741            }
 6742        }
 6743
 6744        let mut delta_for_end_row = 0;
 6745        let has_multiple_rows = start_row + 1 != end_row;
 6746        for row in start_row..end_row {
 6747            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6748            let indent_delta = match (current_indent.kind, indent_kind) {
 6749                (IndentKind::Space, IndentKind::Space) => {
 6750                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6751                    IndentSize::spaces(columns_to_next_tab_stop)
 6752                }
 6753                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6754                (_, IndentKind::Tab) => IndentSize::tab(),
 6755            };
 6756
 6757            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6758                0
 6759            } else {
 6760                selection.start.column
 6761            };
 6762            let row_start = Point::new(row, start);
 6763            edits.push((
 6764                row_start..row_start,
 6765                indent_delta.chars().collect::<String>(),
 6766            ));
 6767
 6768            // Update this selection's endpoints to reflect the indentation.
 6769            if row == selection.start.row {
 6770                selection.start.column += indent_delta.len;
 6771            }
 6772            if row == selection.end.row {
 6773                selection.end.column += indent_delta.len;
 6774                delta_for_end_row = indent_delta.len;
 6775            }
 6776        }
 6777
 6778        if selection.start.row == selection.end.row {
 6779            delta_for_start_row + delta_for_end_row
 6780        } else {
 6781            delta_for_end_row
 6782        }
 6783    }
 6784
 6785    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6786        if self.read_only(cx) {
 6787            return;
 6788        }
 6789        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6790        let selections = self.selections.all::<Point>(cx);
 6791        let mut deletion_ranges = Vec::new();
 6792        let mut last_outdent = None;
 6793        {
 6794            let buffer = self.buffer.read(cx);
 6795            let snapshot = buffer.snapshot(cx);
 6796            for selection in &selections {
 6797                let settings = buffer.settings_at(selection.start, cx);
 6798                let tab_size = settings.tab_size.get();
 6799                let mut rows = selection.spanned_rows(false, &display_map);
 6800
 6801                // Avoid re-outdenting a row that has already been outdented by a
 6802                // previous selection.
 6803                if let Some(last_row) = last_outdent {
 6804                    if last_row == rows.start {
 6805                        rows.start = rows.start.next_row();
 6806                    }
 6807                }
 6808                let has_multiple_rows = rows.len() > 1;
 6809                for row in rows.iter_rows() {
 6810                    let indent_size = snapshot.indent_size_for_line(row);
 6811                    if indent_size.len > 0 {
 6812                        let deletion_len = match indent_size.kind {
 6813                            IndentKind::Space => {
 6814                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6815                                if columns_to_prev_tab_stop == 0 {
 6816                                    tab_size
 6817                                } else {
 6818                                    columns_to_prev_tab_stop
 6819                                }
 6820                            }
 6821                            IndentKind::Tab => 1,
 6822                        };
 6823                        let start = if has_multiple_rows
 6824                            || deletion_len > selection.start.column
 6825                            || indent_size.len < selection.start.column
 6826                        {
 6827                            0
 6828                        } else {
 6829                            selection.start.column - deletion_len
 6830                        };
 6831                        deletion_ranges.push(
 6832                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6833                        );
 6834                        last_outdent = Some(row);
 6835                    }
 6836                }
 6837            }
 6838        }
 6839
 6840        self.transact(window, cx, |this, window, cx| {
 6841            this.buffer.update(cx, |buffer, cx| {
 6842                let empty_str: Arc<str> = Arc::default();
 6843                buffer.edit(
 6844                    deletion_ranges
 6845                        .into_iter()
 6846                        .map(|range| (range, empty_str.clone())),
 6847                    None,
 6848                    cx,
 6849                );
 6850            });
 6851            let selections = this.selections.all::<usize>(cx);
 6852            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6853                s.select(selections)
 6854            });
 6855        });
 6856    }
 6857
 6858    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6859        if self.read_only(cx) {
 6860            return;
 6861        }
 6862        let selections = self
 6863            .selections
 6864            .all::<usize>(cx)
 6865            .into_iter()
 6866            .map(|s| s.range());
 6867
 6868        self.transact(window, cx, |this, window, cx| {
 6869            this.buffer.update(cx, |buffer, cx| {
 6870                buffer.autoindent_ranges(selections, cx);
 6871            });
 6872            let selections = this.selections.all::<usize>(cx);
 6873            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6874                s.select(selections)
 6875            });
 6876        });
 6877    }
 6878
 6879    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6880        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6881        let selections = self.selections.all::<Point>(cx);
 6882
 6883        let mut new_cursors = Vec::new();
 6884        let mut edit_ranges = Vec::new();
 6885        let mut selections = selections.iter().peekable();
 6886        while let Some(selection) = selections.next() {
 6887            let mut rows = selection.spanned_rows(false, &display_map);
 6888            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6889
 6890            // Accumulate contiguous regions of rows that we want to delete.
 6891            while let Some(next_selection) = selections.peek() {
 6892                let next_rows = next_selection.spanned_rows(false, &display_map);
 6893                if next_rows.start <= rows.end {
 6894                    rows.end = next_rows.end;
 6895                    selections.next().unwrap();
 6896                } else {
 6897                    break;
 6898                }
 6899            }
 6900
 6901            let buffer = &display_map.buffer_snapshot;
 6902            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6903            let edit_end;
 6904            let cursor_buffer_row;
 6905            if buffer.max_point().row >= rows.end.0 {
 6906                // If there's a line after the range, delete the \n from the end of the row range
 6907                // and position the cursor on the next line.
 6908                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6909                cursor_buffer_row = rows.end;
 6910            } else {
 6911                // If there isn't a line after the range, delete the \n from the line before the
 6912                // start of the row range and position the cursor there.
 6913                edit_start = edit_start.saturating_sub(1);
 6914                edit_end = buffer.len();
 6915                cursor_buffer_row = rows.start.previous_row();
 6916            }
 6917
 6918            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6919            *cursor.column_mut() =
 6920                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6921
 6922            new_cursors.push((
 6923                selection.id,
 6924                buffer.anchor_after(cursor.to_point(&display_map)),
 6925            ));
 6926            edit_ranges.push(edit_start..edit_end);
 6927        }
 6928
 6929        self.transact(window, cx, |this, window, cx| {
 6930            let buffer = this.buffer.update(cx, |buffer, cx| {
 6931                let empty_str: Arc<str> = Arc::default();
 6932                buffer.edit(
 6933                    edit_ranges
 6934                        .into_iter()
 6935                        .map(|range| (range, empty_str.clone())),
 6936                    None,
 6937                    cx,
 6938                );
 6939                buffer.snapshot(cx)
 6940            });
 6941            let new_selections = new_cursors
 6942                .into_iter()
 6943                .map(|(id, cursor)| {
 6944                    let cursor = cursor.to_point(&buffer);
 6945                    Selection {
 6946                        id,
 6947                        start: cursor,
 6948                        end: cursor,
 6949                        reversed: false,
 6950                        goal: SelectionGoal::None,
 6951                    }
 6952                })
 6953                .collect();
 6954
 6955            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6956                s.select(new_selections);
 6957            });
 6958        });
 6959    }
 6960
 6961    pub fn join_lines_impl(
 6962        &mut self,
 6963        insert_whitespace: bool,
 6964        window: &mut Window,
 6965        cx: &mut Context<Self>,
 6966    ) {
 6967        if self.read_only(cx) {
 6968            return;
 6969        }
 6970        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6971        for selection in self.selections.all::<Point>(cx) {
 6972            let start = MultiBufferRow(selection.start.row);
 6973            // Treat single line selections as if they include the next line. Otherwise this action
 6974            // would do nothing for single line selections individual cursors.
 6975            let end = if selection.start.row == selection.end.row {
 6976                MultiBufferRow(selection.start.row + 1)
 6977            } else {
 6978                MultiBufferRow(selection.end.row)
 6979            };
 6980
 6981            if let Some(last_row_range) = row_ranges.last_mut() {
 6982                if start <= last_row_range.end {
 6983                    last_row_range.end = end;
 6984                    continue;
 6985                }
 6986            }
 6987            row_ranges.push(start..end);
 6988        }
 6989
 6990        let snapshot = self.buffer.read(cx).snapshot(cx);
 6991        let mut cursor_positions = Vec::new();
 6992        for row_range in &row_ranges {
 6993            let anchor = snapshot.anchor_before(Point::new(
 6994                row_range.end.previous_row().0,
 6995                snapshot.line_len(row_range.end.previous_row()),
 6996            ));
 6997            cursor_positions.push(anchor..anchor);
 6998        }
 6999
 7000        self.transact(window, cx, |this, window, cx| {
 7001            for row_range in row_ranges.into_iter().rev() {
 7002                for row in row_range.iter_rows().rev() {
 7003                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7004                    let next_line_row = row.next_row();
 7005                    let indent = snapshot.indent_size_for_line(next_line_row);
 7006                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7007
 7008                    let replace =
 7009                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7010                            " "
 7011                        } else {
 7012                            ""
 7013                        };
 7014
 7015                    this.buffer.update(cx, |buffer, cx| {
 7016                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7017                    });
 7018                }
 7019            }
 7020
 7021            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7022                s.select_anchor_ranges(cursor_positions)
 7023            });
 7024        });
 7025    }
 7026
 7027    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7028        self.join_lines_impl(true, window, cx);
 7029    }
 7030
 7031    pub fn sort_lines_case_sensitive(
 7032        &mut self,
 7033        _: &SortLinesCaseSensitive,
 7034        window: &mut Window,
 7035        cx: &mut Context<Self>,
 7036    ) {
 7037        self.manipulate_lines(window, cx, |lines| lines.sort())
 7038    }
 7039
 7040    pub fn sort_lines_case_insensitive(
 7041        &mut self,
 7042        _: &SortLinesCaseInsensitive,
 7043        window: &mut Window,
 7044        cx: &mut Context<Self>,
 7045    ) {
 7046        self.manipulate_lines(window, cx, |lines| {
 7047            lines.sort_by_key(|line| line.to_lowercase())
 7048        })
 7049    }
 7050
 7051    pub fn unique_lines_case_insensitive(
 7052        &mut self,
 7053        _: &UniqueLinesCaseInsensitive,
 7054        window: &mut Window,
 7055        cx: &mut Context<Self>,
 7056    ) {
 7057        self.manipulate_lines(window, cx, |lines| {
 7058            let mut seen = HashSet::default();
 7059            lines.retain(|line| seen.insert(line.to_lowercase()));
 7060        })
 7061    }
 7062
 7063    pub fn unique_lines_case_sensitive(
 7064        &mut self,
 7065        _: &UniqueLinesCaseSensitive,
 7066        window: &mut Window,
 7067        cx: &mut Context<Self>,
 7068    ) {
 7069        self.manipulate_lines(window, cx, |lines| {
 7070            let mut seen = HashSet::default();
 7071            lines.retain(|line| seen.insert(*line));
 7072        })
 7073    }
 7074
 7075    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 7076        let mut revert_changes = HashMap::default();
 7077        let snapshot = self.snapshot(window, cx);
 7078        for hunk in snapshot
 7079            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 7080        {
 7081            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7082        }
 7083        if !revert_changes.is_empty() {
 7084            self.transact(window, cx, |editor, window, cx| {
 7085                editor.revert(revert_changes, window, cx);
 7086            });
 7087        }
 7088    }
 7089
 7090    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7091        let Some(project) = self.project.clone() else {
 7092            return;
 7093        };
 7094        self.reload(project, window, cx)
 7095            .detach_and_notify_err(window, cx);
 7096    }
 7097
 7098    pub fn revert_selected_hunks(
 7099        &mut self,
 7100        _: &RevertSelectedHunks,
 7101        window: &mut Window,
 7102        cx: &mut Context<Self>,
 7103    ) {
 7104        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 7105        self.discard_hunks_in_ranges(selections, window, cx);
 7106    }
 7107
 7108    fn discard_hunks_in_ranges(
 7109        &mut self,
 7110        ranges: impl Iterator<Item = Range<Point>>,
 7111        window: &mut Window,
 7112        cx: &mut Context<Editor>,
 7113    ) {
 7114        let mut revert_changes = HashMap::default();
 7115        let snapshot = self.snapshot(window, cx);
 7116        for hunk in &snapshot.hunks_for_ranges(ranges) {
 7117            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7118        }
 7119        if !revert_changes.is_empty() {
 7120            self.transact(window, cx, |editor, window, cx| {
 7121                editor.revert(revert_changes, window, cx);
 7122            });
 7123        }
 7124    }
 7125
 7126    pub fn open_active_item_in_terminal(
 7127        &mut self,
 7128        _: &OpenInTerminal,
 7129        window: &mut Window,
 7130        cx: &mut Context<Self>,
 7131    ) {
 7132        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7133            let project_path = buffer.read(cx).project_path(cx)?;
 7134            let project = self.project.as_ref()?.read(cx);
 7135            let entry = project.entry_for_path(&project_path, cx)?;
 7136            let parent = match &entry.canonical_path {
 7137                Some(canonical_path) => canonical_path.to_path_buf(),
 7138                None => project.absolute_path(&project_path, cx)?,
 7139            }
 7140            .parent()?
 7141            .to_path_buf();
 7142            Some(parent)
 7143        }) {
 7144            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7145        }
 7146    }
 7147
 7148    pub fn prepare_revert_change(
 7149        &self,
 7150        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7151        hunk: &MultiBufferDiffHunk,
 7152        cx: &mut App,
 7153    ) -> Option<()> {
 7154        let buffer = self.buffer.read(cx);
 7155        let diff = buffer.diff_for(hunk.buffer_id)?;
 7156        let buffer = buffer.buffer(hunk.buffer_id)?;
 7157        let buffer = buffer.read(cx);
 7158        let original_text = diff
 7159            .read(cx)
 7160            .base_text()
 7161            .as_ref()?
 7162            .as_rope()
 7163            .slice(hunk.diff_base_byte_range.clone());
 7164        let buffer_snapshot = buffer.snapshot();
 7165        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7166        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7167            probe
 7168                .0
 7169                .start
 7170                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7171                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7172        }) {
 7173            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7174            Some(())
 7175        } else {
 7176            None
 7177        }
 7178    }
 7179
 7180    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7181        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7182    }
 7183
 7184    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7185        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7186    }
 7187
 7188    fn manipulate_lines<Fn>(
 7189        &mut self,
 7190        window: &mut Window,
 7191        cx: &mut Context<Self>,
 7192        mut callback: Fn,
 7193    ) where
 7194        Fn: FnMut(&mut Vec<&str>),
 7195    {
 7196        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7197        let buffer = self.buffer.read(cx).snapshot(cx);
 7198
 7199        let mut edits = Vec::new();
 7200
 7201        let selections = self.selections.all::<Point>(cx);
 7202        let mut selections = selections.iter().peekable();
 7203        let mut contiguous_row_selections = Vec::new();
 7204        let mut new_selections = Vec::new();
 7205        let mut added_lines = 0;
 7206        let mut removed_lines = 0;
 7207
 7208        while let Some(selection) = selections.next() {
 7209            let (start_row, end_row) = consume_contiguous_rows(
 7210                &mut contiguous_row_selections,
 7211                selection,
 7212                &display_map,
 7213                &mut selections,
 7214            );
 7215
 7216            let start_point = Point::new(start_row.0, 0);
 7217            let end_point = Point::new(
 7218                end_row.previous_row().0,
 7219                buffer.line_len(end_row.previous_row()),
 7220            );
 7221            let text = buffer
 7222                .text_for_range(start_point..end_point)
 7223                .collect::<String>();
 7224
 7225            let mut lines = text.split('\n').collect_vec();
 7226
 7227            let lines_before = lines.len();
 7228            callback(&mut lines);
 7229            let lines_after = lines.len();
 7230
 7231            edits.push((start_point..end_point, lines.join("\n")));
 7232
 7233            // Selections must change based on added and removed line count
 7234            let start_row =
 7235                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7236            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7237            new_selections.push(Selection {
 7238                id: selection.id,
 7239                start: start_row,
 7240                end: end_row,
 7241                goal: SelectionGoal::None,
 7242                reversed: selection.reversed,
 7243            });
 7244
 7245            if lines_after > lines_before {
 7246                added_lines += lines_after - lines_before;
 7247            } else if lines_before > lines_after {
 7248                removed_lines += lines_before - lines_after;
 7249            }
 7250        }
 7251
 7252        self.transact(window, cx, |this, window, cx| {
 7253            let buffer = this.buffer.update(cx, |buffer, cx| {
 7254                buffer.edit(edits, None, cx);
 7255                buffer.snapshot(cx)
 7256            });
 7257
 7258            // Recalculate offsets on newly edited buffer
 7259            let new_selections = new_selections
 7260                .iter()
 7261                .map(|s| {
 7262                    let start_point = Point::new(s.start.0, 0);
 7263                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7264                    Selection {
 7265                        id: s.id,
 7266                        start: buffer.point_to_offset(start_point),
 7267                        end: buffer.point_to_offset(end_point),
 7268                        goal: s.goal,
 7269                        reversed: s.reversed,
 7270                    }
 7271                })
 7272                .collect();
 7273
 7274            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7275                s.select(new_selections);
 7276            });
 7277
 7278            this.request_autoscroll(Autoscroll::fit(), cx);
 7279        });
 7280    }
 7281
 7282    pub fn convert_to_upper_case(
 7283        &mut self,
 7284        _: &ConvertToUpperCase,
 7285        window: &mut Window,
 7286        cx: &mut Context<Self>,
 7287    ) {
 7288        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7289    }
 7290
 7291    pub fn convert_to_lower_case(
 7292        &mut self,
 7293        _: &ConvertToLowerCase,
 7294        window: &mut Window,
 7295        cx: &mut Context<Self>,
 7296    ) {
 7297        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7298    }
 7299
 7300    pub fn convert_to_title_case(
 7301        &mut self,
 7302        _: &ConvertToTitleCase,
 7303        window: &mut Window,
 7304        cx: &mut Context<Self>,
 7305    ) {
 7306        self.manipulate_text(window, cx, |text| {
 7307            text.split('\n')
 7308                .map(|line| line.to_case(Case::Title))
 7309                .join("\n")
 7310        })
 7311    }
 7312
 7313    pub fn convert_to_snake_case(
 7314        &mut self,
 7315        _: &ConvertToSnakeCase,
 7316        window: &mut Window,
 7317        cx: &mut Context<Self>,
 7318    ) {
 7319        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7320    }
 7321
 7322    pub fn convert_to_kebab_case(
 7323        &mut self,
 7324        _: &ConvertToKebabCase,
 7325        window: &mut Window,
 7326        cx: &mut Context<Self>,
 7327    ) {
 7328        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7329    }
 7330
 7331    pub fn convert_to_upper_camel_case(
 7332        &mut self,
 7333        _: &ConvertToUpperCamelCase,
 7334        window: &mut Window,
 7335        cx: &mut Context<Self>,
 7336    ) {
 7337        self.manipulate_text(window, cx, |text| {
 7338            text.split('\n')
 7339                .map(|line| line.to_case(Case::UpperCamel))
 7340                .join("\n")
 7341        })
 7342    }
 7343
 7344    pub fn convert_to_lower_camel_case(
 7345        &mut self,
 7346        _: &ConvertToLowerCamelCase,
 7347        window: &mut Window,
 7348        cx: &mut Context<Self>,
 7349    ) {
 7350        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7351    }
 7352
 7353    pub fn convert_to_opposite_case(
 7354        &mut self,
 7355        _: &ConvertToOppositeCase,
 7356        window: &mut Window,
 7357        cx: &mut Context<Self>,
 7358    ) {
 7359        self.manipulate_text(window, cx, |text| {
 7360            text.chars()
 7361                .fold(String::with_capacity(text.len()), |mut t, c| {
 7362                    if c.is_uppercase() {
 7363                        t.extend(c.to_lowercase());
 7364                    } else {
 7365                        t.extend(c.to_uppercase());
 7366                    }
 7367                    t
 7368                })
 7369        })
 7370    }
 7371
 7372    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7373    where
 7374        Fn: FnMut(&str) -> String,
 7375    {
 7376        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7377        let buffer = self.buffer.read(cx).snapshot(cx);
 7378
 7379        let mut new_selections = Vec::new();
 7380        let mut edits = Vec::new();
 7381        let mut selection_adjustment = 0i32;
 7382
 7383        for selection in self.selections.all::<usize>(cx) {
 7384            let selection_is_empty = selection.is_empty();
 7385
 7386            let (start, end) = if selection_is_empty {
 7387                let word_range = movement::surrounding_word(
 7388                    &display_map,
 7389                    selection.start.to_display_point(&display_map),
 7390                );
 7391                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7392                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7393                (start, end)
 7394            } else {
 7395                (selection.start, selection.end)
 7396            };
 7397
 7398            let text = buffer.text_for_range(start..end).collect::<String>();
 7399            let old_length = text.len() as i32;
 7400            let text = callback(&text);
 7401
 7402            new_selections.push(Selection {
 7403                start: (start as i32 - selection_adjustment) as usize,
 7404                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7405                goal: SelectionGoal::None,
 7406                ..selection
 7407            });
 7408
 7409            selection_adjustment += old_length - text.len() as i32;
 7410
 7411            edits.push((start..end, text));
 7412        }
 7413
 7414        self.transact(window, cx, |this, window, cx| {
 7415            this.buffer.update(cx, |buffer, cx| {
 7416                buffer.edit(edits, None, cx);
 7417            });
 7418
 7419            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7420                s.select(new_selections);
 7421            });
 7422
 7423            this.request_autoscroll(Autoscroll::fit(), cx);
 7424        });
 7425    }
 7426
 7427    pub fn duplicate(
 7428        &mut self,
 7429        upwards: bool,
 7430        whole_lines: bool,
 7431        window: &mut Window,
 7432        cx: &mut Context<Self>,
 7433    ) {
 7434        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7435        let buffer = &display_map.buffer_snapshot;
 7436        let selections = self.selections.all::<Point>(cx);
 7437
 7438        let mut edits = Vec::new();
 7439        let mut selections_iter = selections.iter().peekable();
 7440        while let Some(selection) = selections_iter.next() {
 7441            let mut rows = selection.spanned_rows(false, &display_map);
 7442            // duplicate line-wise
 7443            if whole_lines || selection.start == selection.end {
 7444                // Avoid duplicating the same lines twice.
 7445                while let Some(next_selection) = selections_iter.peek() {
 7446                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7447                    if next_rows.start < rows.end {
 7448                        rows.end = next_rows.end;
 7449                        selections_iter.next().unwrap();
 7450                    } else {
 7451                        break;
 7452                    }
 7453                }
 7454
 7455                // Copy the text from the selected row region and splice it either at the start
 7456                // or end of the region.
 7457                let start = Point::new(rows.start.0, 0);
 7458                let end = Point::new(
 7459                    rows.end.previous_row().0,
 7460                    buffer.line_len(rows.end.previous_row()),
 7461                );
 7462                let text = buffer
 7463                    .text_for_range(start..end)
 7464                    .chain(Some("\n"))
 7465                    .collect::<String>();
 7466                let insert_location = if upwards {
 7467                    Point::new(rows.end.0, 0)
 7468                } else {
 7469                    start
 7470                };
 7471                edits.push((insert_location..insert_location, text));
 7472            } else {
 7473                // duplicate character-wise
 7474                let start = selection.start;
 7475                let end = selection.end;
 7476                let text = buffer.text_for_range(start..end).collect::<String>();
 7477                edits.push((selection.end..selection.end, text));
 7478            }
 7479        }
 7480
 7481        self.transact(window, cx, |this, _, cx| {
 7482            this.buffer.update(cx, |buffer, cx| {
 7483                buffer.edit(edits, None, cx);
 7484            });
 7485
 7486            this.request_autoscroll(Autoscroll::fit(), cx);
 7487        });
 7488    }
 7489
 7490    pub fn duplicate_line_up(
 7491        &mut self,
 7492        _: &DuplicateLineUp,
 7493        window: &mut Window,
 7494        cx: &mut Context<Self>,
 7495    ) {
 7496        self.duplicate(true, true, window, cx);
 7497    }
 7498
 7499    pub fn duplicate_line_down(
 7500        &mut self,
 7501        _: &DuplicateLineDown,
 7502        window: &mut Window,
 7503        cx: &mut Context<Self>,
 7504    ) {
 7505        self.duplicate(false, true, window, cx);
 7506    }
 7507
 7508    pub fn duplicate_selection(
 7509        &mut self,
 7510        _: &DuplicateSelection,
 7511        window: &mut Window,
 7512        cx: &mut Context<Self>,
 7513    ) {
 7514        self.duplicate(false, false, window, cx);
 7515    }
 7516
 7517    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7518        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7519        let buffer = self.buffer.read(cx).snapshot(cx);
 7520
 7521        let mut edits = Vec::new();
 7522        let mut unfold_ranges = Vec::new();
 7523        let mut refold_creases = Vec::new();
 7524
 7525        let selections = self.selections.all::<Point>(cx);
 7526        let mut selections = selections.iter().peekable();
 7527        let mut contiguous_row_selections = Vec::new();
 7528        let mut new_selections = Vec::new();
 7529
 7530        while let Some(selection) = selections.next() {
 7531            // Find all the selections that span a contiguous row range
 7532            let (start_row, end_row) = consume_contiguous_rows(
 7533                &mut contiguous_row_selections,
 7534                selection,
 7535                &display_map,
 7536                &mut selections,
 7537            );
 7538
 7539            // Move the text spanned by the row range to be before the line preceding the row range
 7540            if start_row.0 > 0 {
 7541                let range_to_move = Point::new(
 7542                    start_row.previous_row().0,
 7543                    buffer.line_len(start_row.previous_row()),
 7544                )
 7545                    ..Point::new(
 7546                        end_row.previous_row().0,
 7547                        buffer.line_len(end_row.previous_row()),
 7548                    );
 7549                let insertion_point = display_map
 7550                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7551                    .0;
 7552
 7553                // Don't move lines across excerpts
 7554                if buffer
 7555                    .excerpt_containing(insertion_point..range_to_move.end)
 7556                    .is_some()
 7557                {
 7558                    let text = buffer
 7559                        .text_for_range(range_to_move.clone())
 7560                        .flat_map(|s| s.chars())
 7561                        .skip(1)
 7562                        .chain(['\n'])
 7563                        .collect::<String>();
 7564
 7565                    edits.push((
 7566                        buffer.anchor_after(range_to_move.start)
 7567                            ..buffer.anchor_before(range_to_move.end),
 7568                        String::new(),
 7569                    ));
 7570                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7571                    edits.push((insertion_anchor..insertion_anchor, text));
 7572
 7573                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7574
 7575                    // Move selections up
 7576                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7577                        |mut selection| {
 7578                            selection.start.row -= row_delta;
 7579                            selection.end.row -= row_delta;
 7580                            selection
 7581                        },
 7582                    ));
 7583
 7584                    // Move folds up
 7585                    unfold_ranges.push(range_to_move.clone());
 7586                    for fold in display_map.folds_in_range(
 7587                        buffer.anchor_before(range_to_move.start)
 7588                            ..buffer.anchor_after(range_to_move.end),
 7589                    ) {
 7590                        let mut start = fold.range.start.to_point(&buffer);
 7591                        let mut end = fold.range.end.to_point(&buffer);
 7592                        start.row -= row_delta;
 7593                        end.row -= row_delta;
 7594                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7595                    }
 7596                }
 7597            }
 7598
 7599            // If we didn't move line(s), preserve the existing selections
 7600            new_selections.append(&mut contiguous_row_selections);
 7601        }
 7602
 7603        self.transact(window, cx, |this, window, cx| {
 7604            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7605            this.buffer.update(cx, |buffer, cx| {
 7606                for (range, text) in edits {
 7607                    buffer.edit([(range, text)], None, cx);
 7608                }
 7609            });
 7610            this.fold_creases(refold_creases, true, window, cx);
 7611            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7612                s.select(new_selections);
 7613            })
 7614        });
 7615    }
 7616
 7617    pub fn move_line_down(
 7618        &mut self,
 7619        _: &MoveLineDown,
 7620        window: &mut Window,
 7621        cx: &mut Context<Self>,
 7622    ) {
 7623        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7624        let buffer = self.buffer.read(cx).snapshot(cx);
 7625
 7626        let mut edits = Vec::new();
 7627        let mut unfold_ranges = Vec::new();
 7628        let mut refold_creases = Vec::new();
 7629
 7630        let selections = self.selections.all::<Point>(cx);
 7631        let mut selections = selections.iter().peekable();
 7632        let mut contiguous_row_selections = Vec::new();
 7633        let mut new_selections = Vec::new();
 7634
 7635        while let Some(selection) = selections.next() {
 7636            // Find all the selections that span a contiguous row range
 7637            let (start_row, end_row) = consume_contiguous_rows(
 7638                &mut contiguous_row_selections,
 7639                selection,
 7640                &display_map,
 7641                &mut selections,
 7642            );
 7643
 7644            // Move the text spanned by the row range to be after the last line of the row range
 7645            if end_row.0 <= buffer.max_point().row {
 7646                let range_to_move =
 7647                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7648                let insertion_point = display_map
 7649                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7650                    .0;
 7651
 7652                // Don't move lines across excerpt boundaries
 7653                if buffer
 7654                    .excerpt_containing(range_to_move.start..insertion_point)
 7655                    .is_some()
 7656                {
 7657                    let mut text = String::from("\n");
 7658                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7659                    text.pop(); // Drop trailing newline
 7660                    edits.push((
 7661                        buffer.anchor_after(range_to_move.start)
 7662                            ..buffer.anchor_before(range_to_move.end),
 7663                        String::new(),
 7664                    ));
 7665                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7666                    edits.push((insertion_anchor..insertion_anchor, text));
 7667
 7668                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7669
 7670                    // Move selections down
 7671                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7672                        |mut selection| {
 7673                            selection.start.row += row_delta;
 7674                            selection.end.row += row_delta;
 7675                            selection
 7676                        },
 7677                    ));
 7678
 7679                    // Move folds down
 7680                    unfold_ranges.push(range_to_move.clone());
 7681                    for fold in display_map.folds_in_range(
 7682                        buffer.anchor_before(range_to_move.start)
 7683                            ..buffer.anchor_after(range_to_move.end),
 7684                    ) {
 7685                        let mut start = fold.range.start.to_point(&buffer);
 7686                        let mut end = fold.range.end.to_point(&buffer);
 7687                        start.row += row_delta;
 7688                        end.row += row_delta;
 7689                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7690                    }
 7691                }
 7692            }
 7693
 7694            // If we didn't move line(s), preserve the existing selections
 7695            new_selections.append(&mut contiguous_row_selections);
 7696        }
 7697
 7698        self.transact(window, cx, |this, window, cx| {
 7699            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7700            this.buffer.update(cx, |buffer, cx| {
 7701                for (range, text) in edits {
 7702                    buffer.edit([(range, text)], None, cx);
 7703                }
 7704            });
 7705            this.fold_creases(refold_creases, true, window, cx);
 7706            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7707                s.select(new_selections)
 7708            });
 7709        });
 7710    }
 7711
 7712    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7713        let text_layout_details = &self.text_layout_details(window);
 7714        self.transact(window, cx, |this, window, cx| {
 7715            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7716                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7717                let line_mode = s.line_mode;
 7718                s.move_with(|display_map, selection| {
 7719                    if !selection.is_empty() || line_mode {
 7720                        return;
 7721                    }
 7722
 7723                    let mut head = selection.head();
 7724                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7725                    if head.column() == display_map.line_len(head.row()) {
 7726                        transpose_offset = display_map
 7727                            .buffer_snapshot
 7728                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7729                    }
 7730
 7731                    if transpose_offset == 0 {
 7732                        return;
 7733                    }
 7734
 7735                    *head.column_mut() += 1;
 7736                    head = display_map.clip_point(head, Bias::Right);
 7737                    let goal = SelectionGoal::HorizontalPosition(
 7738                        display_map
 7739                            .x_for_display_point(head, text_layout_details)
 7740                            .into(),
 7741                    );
 7742                    selection.collapse_to(head, goal);
 7743
 7744                    let transpose_start = display_map
 7745                        .buffer_snapshot
 7746                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7747                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7748                        let transpose_end = display_map
 7749                            .buffer_snapshot
 7750                            .clip_offset(transpose_offset + 1, Bias::Right);
 7751                        if let Some(ch) =
 7752                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7753                        {
 7754                            edits.push((transpose_start..transpose_offset, String::new()));
 7755                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7756                        }
 7757                    }
 7758                });
 7759                edits
 7760            });
 7761            this.buffer
 7762                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7763            let selections = this.selections.all::<usize>(cx);
 7764            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7765                s.select(selections);
 7766            });
 7767        });
 7768    }
 7769
 7770    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7771        self.rewrap_impl(IsVimMode::No, cx)
 7772    }
 7773
 7774    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7775        let buffer = self.buffer.read(cx).snapshot(cx);
 7776        let selections = self.selections.all::<Point>(cx);
 7777        let mut selections = selections.iter().peekable();
 7778
 7779        let mut edits = Vec::new();
 7780        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7781
 7782        while let Some(selection) = selections.next() {
 7783            let mut start_row = selection.start.row;
 7784            let mut end_row = selection.end.row;
 7785
 7786            // Skip selections that overlap with a range that has already been rewrapped.
 7787            let selection_range = start_row..end_row;
 7788            if rewrapped_row_ranges
 7789                .iter()
 7790                .any(|range| range.overlaps(&selection_range))
 7791            {
 7792                continue;
 7793            }
 7794
 7795            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7796
 7797            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7798                match language_scope.language_name().as_ref() {
 7799                    "Markdown" | "Plain Text" => {
 7800                        should_rewrap = true;
 7801                    }
 7802                    _ => {}
 7803                }
 7804            }
 7805
 7806            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7807
 7808            // Since not all lines in the selection may be at the same indent
 7809            // level, choose the indent size that is the most common between all
 7810            // of the lines.
 7811            //
 7812            // If there is a tie, we use the deepest indent.
 7813            let (indent_size, indent_end) = {
 7814                let mut indent_size_occurrences = HashMap::default();
 7815                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7816
 7817                for row in start_row..=end_row {
 7818                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7819                    rows_by_indent_size.entry(indent).or_default().push(row);
 7820                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7821                }
 7822
 7823                let indent_size = indent_size_occurrences
 7824                    .into_iter()
 7825                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7826                    .map(|(indent, _)| indent)
 7827                    .unwrap_or_default();
 7828                let row = rows_by_indent_size[&indent_size][0];
 7829                let indent_end = Point::new(row, indent_size.len);
 7830
 7831                (indent_size, indent_end)
 7832            };
 7833
 7834            let mut line_prefix = indent_size.chars().collect::<String>();
 7835
 7836            if let Some(comment_prefix) =
 7837                buffer
 7838                    .language_scope_at(selection.head())
 7839                    .and_then(|language| {
 7840                        language
 7841                            .line_comment_prefixes()
 7842                            .iter()
 7843                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7844                            .cloned()
 7845                    })
 7846            {
 7847                line_prefix.push_str(&comment_prefix);
 7848                should_rewrap = true;
 7849            }
 7850
 7851            if !should_rewrap {
 7852                continue;
 7853            }
 7854
 7855            if selection.is_empty() {
 7856                'expand_upwards: while start_row > 0 {
 7857                    let prev_row = start_row - 1;
 7858                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7859                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7860                    {
 7861                        start_row = prev_row;
 7862                    } else {
 7863                        break 'expand_upwards;
 7864                    }
 7865                }
 7866
 7867                'expand_downwards: while end_row < buffer.max_point().row {
 7868                    let next_row = end_row + 1;
 7869                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7870                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7871                    {
 7872                        end_row = next_row;
 7873                    } else {
 7874                        break 'expand_downwards;
 7875                    }
 7876                }
 7877            }
 7878
 7879            let start = Point::new(start_row, 0);
 7880            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7881            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7882            let Some(lines_without_prefixes) = selection_text
 7883                .lines()
 7884                .map(|line| {
 7885                    line.strip_prefix(&line_prefix)
 7886                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7887                        .ok_or_else(|| {
 7888                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7889                        })
 7890                })
 7891                .collect::<Result<Vec<_>, _>>()
 7892                .log_err()
 7893            else {
 7894                continue;
 7895            };
 7896
 7897            let wrap_column = buffer
 7898                .settings_at(Point::new(start_row, 0), cx)
 7899                .preferred_line_length as usize;
 7900            let wrapped_text = wrap_with_prefix(
 7901                line_prefix,
 7902                lines_without_prefixes.join(" "),
 7903                wrap_column,
 7904                tab_size,
 7905            );
 7906
 7907            // TODO: should always use char-based diff while still supporting cursor behavior that
 7908            // matches vim.
 7909            let diff = match is_vim_mode {
 7910                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7911                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7912            };
 7913            let mut offset = start.to_offset(&buffer);
 7914            let mut moved_since_edit = true;
 7915
 7916            for change in diff.iter_all_changes() {
 7917                let value = change.value();
 7918                match change.tag() {
 7919                    ChangeTag::Equal => {
 7920                        offset += value.len();
 7921                        moved_since_edit = true;
 7922                    }
 7923                    ChangeTag::Delete => {
 7924                        let start = buffer.anchor_after(offset);
 7925                        let end = buffer.anchor_before(offset + value.len());
 7926
 7927                        if moved_since_edit {
 7928                            edits.push((start..end, String::new()));
 7929                        } else {
 7930                            edits.last_mut().unwrap().0.end = end;
 7931                        }
 7932
 7933                        offset += value.len();
 7934                        moved_since_edit = false;
 7935                    }
 7936                    ChangeTag::Insert => {
 7937                        if moved_since_edit {
 7938                            let anchor = buffer.anchor_after(offset);
 7939                            edits.push((anchor..anchor, value.to_string()));
 7940                        } else {
 7941                            edits.last_mut().unwrap().1.push_str(value);
 7942                        }
 7943
 7944                        moved_since_edit = false;
 7945                    }
 7946                }
 7947            }
 7948
 7949            rewrapped_row_ranges.push(start_row..=end_row);
 7950        }
 7951
 7952        self.buffer
 7953            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7954    }
 7955
 7956    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7957        let mut text = String::new();
 7958        let buffer = self.buffer.read(cx).snapshot(cx);
 7959        let mut selections = self.selections.all::<Point>(cx);
 7960        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7961        {
 7962            let max_point = buffer.max_point();
 7963            let mut is_first = true;
 7964            for selection in &mut selections {
 7965                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7966                if is_entire_line {
 7967                    selection.start = Point::new(selection.start.row, 0);
 7968                    if !selection.is_empty() && selection.end.column == 0 {
 7969                        selection.end = cmp::min(max_point, selection.end);
 7970                    } else {
 7971                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7972                    }
 7973                    selection.goal = SelectionGoal::None;
 7974                }
 7975                if is_first {
 7976                    is_first = false;
 7977                } else {
 7978                    text += "\n";
 7979                }
 7980                let mut len = 0;
 7981                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7982                    text.push_str(chunk);
 7983                    len += chunk.len();
 7984                }
 7985                clipboard_selections.push(ClipboardSelection {
 7986                    len,
 7987                    is_entire_line,
 7988                    first_line_indent: buffer
 7989                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7990                        .len,
 7991                });
 7992            }
 7993        }
 7994
 7995        self.transact(window, cx, |this, window, cx| {
 7996            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7997                s.select(selections);
 7998            });
 7999            this.insert("", window, cx);
 8000        });
 8001        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8002    }
 8003
 8004    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8005        let item = self.cut_common(window, cx);
 8006        cx.write_to_clipboard(item);
 8007    }
 8008
 8009    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8010        self.change_selections(None, window, cx, |s| {
 8011            s.move_with(|snapshot, sel| {
 8012                if sel.is_empty() {
 8013                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8014                }
 8015            });
 8016        });
 8017        let item = self.cut_common(window, cx);
 8018        cx.set_global(KillRing(item))
 8019    }
 8020
 8021    pub fn kill_ring_yank(
 8022        &mut self,
 8023        _: &KillRingYank,
 8024        window: &mut Window,
 8025        cx: &mut Context<Self>,
 8026    ) {
 8027        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8028            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8029                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8030            } else {
 8031                return;
 8032            }
 8033        } else {
 8034            return;
 8035        };
 8036        self.do_paste(&text, metadata, false, window, cx);
 8037    }
 8038
 8039    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8040        let selections = self.selections.all::<Point>(cx);
 8041        let buffer = self.buffer.read(cx).read(cx);
 8042        let mut text = String::new();
 8043
 8044        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8045        {
 8046            let max_point = buffer.max_point();
 8047            let mut is_first = true;
 8048            for selection in selections.iter() {
 8049                let mut start = selection.start;
 8050                let mut end = selection.end;
 8051                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8052                if is_entire_line {
 8053                    start = Point::new(start.row, 0);
 8054                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8055                }
 8056                if is_first {
 8057                    is_first = false;
 8058                } else {
 8059                    text += "\n";
 8060                }
 8061                let mut len = 0;
 8062                for chunk in buffer.text_for_range(start..end) {
 8063                    text.push_str(chunk);
 8064                    len += chunk.len();
 8065                }
 8066                clipboard_selections.push(ClipboardSelection {
 8067                    len,
 8068                    is_entire_line,
 8069                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8070                });
 8071            }
 8072        }
 8073
 8074        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8075            text,
 8076            clipboard_selections,
 8077        ));
 8078    }
 8079
 8080    pub fn do_paste(
 8081        &mut self,
 8082        text: &String,
 8083        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8084        handle_entire_lines: bool,
 8085        window: &mut Window,
 8086        cx: &mut Context<Self>,
 8087    ) {
 8088        if self.read_only(cx) {
 8089            return;
 8090        }
 8091
 8092        let clipboard_text = Cow::Borrowed(text);
 8093
 8094        self.transact(window, cx, |this, window, cx| {
 8095            if let Some(mut clipboard_selections) = clipboard_selections {
 8096                let old_selections = this.selections.all::<usize>(cx);
 8097                let all_selections_were_entire_line =
 8098                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8099                let first_selection_indent_column =
 8100                    clipboard_selections.first().map(|s| s.first_line_indent);
 8101                if clipboard_selections.len() != old_selections.len() {
 8102                    clipboard_selections.drain(..);
 8103                }
 8104                let cursor_offset = this.selections.last::<usize>(cx).head();
 8105                let mut auto_indent_on_paste = true;
 8106
 8107                this.buffer.update(cx, |buffer, cx| {
 8108                    let snapshot = buffer.read(cx);
 8109                    auto_indent_on_paste =
 8110                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8111
 8112                    let mut start_offset = 0;
 8113                    let mut edits = Vec::new();
 8114                    let mut original_indent_columns = Vec::new();
 8115                    for (ix, selection) in old_selections.iter().enumerate() {
 8116                        let to_insert;
 8117                        let entire_line;
 8118                        let original_indent_column;
 8119                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8120                            let end_offset = start_offset + clipboard_selection.len;
 8121                            to_insert = &clipboard_text[start_offset..end_offset];
 8122                            entire_line = clipboard_selection.is_entire_line;
 8123                            start_offset = end_offset + 1;
 8124                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8125                        } else {
 8126                            to_insert = clipboard_text.as_str();
 8127                            entire_line = all_selections_were_entire_line;
 8128                            original_indent_column = first_selection_indent_column
 8129                        }
 8130
 8131                        // If the corresponding selection was empty when this slice of the
 8132                        // clipboard text was written, then the entire line containing the
 8133                        // selection was copied. If this selection is also currently empty,
 8134                        // then paste the line before the current line of the buffer.
 8135                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8136                            let column = selection.start.to_point(&snapshot).column as usize;
 8137                            let line_start = selection.start - column;
 8138                            line_start..line_start
 8139                        } else {
 8140                            selection.range()
 8141                        };
 8142
 8143                        edits.push((range, to_insert));
 8144                        original_indent_columns.extend(original_indent_column);
 8145                    }
 8146                    drop(snapshot);
 8147
 8148                    buffer.edit(
 8149                        edits,
 8150                        if auto_indent_on_paste {
 8151                            Some(AutoindentMode::Block {
 8152                                original_indent_columns,
 8153                            })
 8154                        } else {
 8155                            None
 8156                        },
 8157                        cx,
 8158                    );
 8159                });
 8160
 8161                let selections = this.selections.all::<usize>(cx);
 8162                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8163                    s.select(selections)
 8164                });
 8165            } else {
 8166                this.insert(&clipboard_text, window, cx);
 8167            }
 8168        });
 8169    }
 8170
 8171    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8172        if let Some(item) = cx.read_from_clipboard() {
 8173            let entries = item.entries();
 8174
 8175            match entries.first() {
 8176                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8177                // of all the pasted entries.
 8178                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8179                    .do_paste(
 8180                        clipboard_string.text(),
 8181                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8182                        true,
 8183                        window,
 8184                        cx,
 8185                    ),
 8186                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8187            }
 8188        }
 8189    }
 8190
 8191    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8192        if self.read_only(cx) {
 8193            return;
 8194        }
 8195
 8196        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8197            if let Some((selections, _)) =
 8198                self.selection_history.transaction(transaction_id).cloned()
 8199            {
 8200                self.change_selections(None, window, cx, |s| {
 8201                    s.select_anchors(selections.to_vec());
 8202                });
 8203            }
 8204            self.request_autoscroll(Autoscroll::fit(), cx);
 8205            self.unmark_text(window, cx);
 8206            self.refresh_inline_completion(true, false, window, cx);
 8207            cx.emit(EditorEvent::Edited { transaction_id });
 8208            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8209        }
 8210    }
 8211
 8212    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8213        if self.read_only(cx) {
 8214            return;
 8215        }
 8216
 8217        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8218            if let Some((_, Some(selections))) =
 8219                self.selection_history.transaction(transaction_id).cloned()
 8220            {
 8221                self.change_selections(None, window, cx, |s| {
 8222                    s.select_anchors(selections.to_vec());
 8223                });
 8224            }
 8225            self.request_autoscroll(Autoscroll::fit(), cx);
 8226            self.unmark_text(window, cx);
 8227            self.refresh_inline_completion(true, false, window, cx);
 8228            cx.emit(EditorEvent::Edited { transaction_id });
 8229        }
 8230    }
 8231
 8232    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8233        self.buffer
 8234            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8235    }
 8236
 8237    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8238        self.buffer
 8239            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8240    }
 8241
 8242    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8243        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8244            let line_mode = s.line_mode;
 8245            s.move_with(|map, selection| {
 8246                let cursor = if selection.is_empty() && !line_mode {
 8247                    movement::left(map, selection.start)
 8248                } else {
 8249                    selection.start
 8250                };
 8251                selection.collapse_to(cursor, SelectionGoal::None);
 8252            });
 8253        })
 8254    }
 8255
 8256    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8257        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8258            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8259        })
 8260    }
 8261
 8262    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8263        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8264            let line_mode = s.line_mode;
 8265            s.move_with(|map, selection| {
 8266                let cursor = if selection.is_empty() && !line_mode {
 8267                    movement::right(map, selection.end)
 8268                } else {
 8269                    selection.end
 8270                };
 8271                selection.collapse_to(cursor, SelectionGoal::None)
 8272            });
 8273        })
 8274    }
 8275
 8276    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8277        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8278            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8279        })
 8280    }
 8281
 8282    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8283        if self.take_rename(true, window, cx).is_some() {
 8284            return;
 8285        }
 8286
 8287        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8288            cx.propagate();
 8289            return;
 8290        }
 8291
 8292        let text_layout_details = &self.text_layout_details(window);
 8293        let selection_count = self.selections.count();
 8294        let first_selection = self.selections.first_anchor();
 8295
 8296        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8297            let line_mode = s.line_mode;
 8298            s.move_with(|map, selection| {
 8299                if !selection.is_empty() && !line_mode {
 8300                    selection.goal = SelectionGoal::None;
 8301                }
 8302                let (cursor, goal) = movement::up(
 8303                    map,
 8304                    selection.start,
 8305                    selection.goal,
 8306                    false,
 8307                    text_layout_details,
 8308                );
 8309                selection.collapse_to(cursor, goal);
 8310            });
 8311        });
 8312
 8313        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8314        {
 8315            cx.propagate();
 8316        }
 8317    }
 8318
 8319    pub fn move_up_by_lines(
 8320        &mut self,
 8321        action: &MoveUpByLines,
 8322        window: &mut Window,
 8323        cx: &mut Context<Self>,
 8324    ) {
 8325        if self.take_rename(true, window, cx).is_some() {
 8326            return;
 8327        }
 8328
 8329        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8330            cx.propagate();
 8331            return;
 8332        }
 8333
 8334        let text_layout_details = &self.text_layout_details(window);
 8335
 8336        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8337            let line_mode = s.line_mode;
 8338            s.move_with(|map, selection| {
 8339                if !selection.is_empty() && !line_mode {
 8340                    selection.goal = SelectionGoal::None;
 8341                }
 8342                let (cursor, goal) = movement::up_by_rows(
 8343                    map,
 8344                    selection.start,
 8345                    action.lines,
 8346                    selection.goal,
 8347                    false,
 8348                    text_layout_details,
 8349                );
 8350                selection.collapse_to(cursor, goal);
 8351            });
 8352        })
 8353    }
 8354
 8355    pub fn move_down_by_lines(
 8356        &mut self,
 8357        action: &MoveDownByLines,
 8358        window: &mut Window,
 8359        cx: &mut Context<Self>,
 8360    ) {
 8361        if self.take_rename(true, window, cx).is_some() {
 8362            return;
 8363        }
 8364
 8365        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8366            cx.propagate();
 8367            return;
 8368        }
 8369
 8370        let text_layout_details = &self.text_layout_details(window);
 8371
 8372        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8373            let line_mode = s.line_mode;
 8374            s.move_with(|map, selection| {
 8375                if !selection.is_empty() && !line_mode {
 8376                    selection.goal = SelectionGoal::None;
 8377                }
 8378                let (cursor, goal) = movement::down_by_rows(
 8379                    map,
 8380                    selection.start,
 8381                    action.lines,
 8382                    selection.goal,
 8383                    false,
 8384                    text_layout_details,
 8385                );
 8386                selection.collapse_to(cursor, goal);
 8387            });
 8388        })
 8389    }
 8390
 8391    pub fn select_down_by_lines(
 8392        &mut self,
 8393        action: &SelectDownByLines,
 8394        window: &mut Window,
 8395        cx: &mut Context<Self>,
 8396    ) {
 8397        let text_layout_details = &self.text_layout_details(window);
 8398        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8399            s.move_heads_with(|map, head, goal| {
 8400                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8401            })
 8402        })
 8403    }
 8404
 8405    pub fn select_up_by_lines(
 8406        &mut self,
 8407        action: &SelectUpByLines,
 8408        window: &mut Window,
 8409        cx: &mut Context<Self>,
 8410    ) {
 8411        let text_layout_details = &self.text_layout_details(window);
 8412        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8413            s.move_heads_with(|map, head, goal| {
 8414                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8415            })
 8416        })
 8417    }
 8418
 8419    pub fn select_page_up(
 8420        &mut self,
 8421        _: &SelectPageUp,
 8422        window: &mut Window,
 8423        cx: &mut Context<Self>,
 8424    ) {
 8425        let Some(row_count) = self.visible_row_count() else {
 8426            return;
 8427        };
 8428
 8429        let text_layout_details = &self.text_layout_details(window);
 8430
 8431        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8432            s.move_heads_with(|map, head, goal| {
 8433                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8434            })
 8435        })
 8436    }
 8437
 8438    pub fn move_page_up(
 8439        &mut self,
 8440        action: &MovePageUp,
 8441        window: &mut Window,
 8442        cx: &mut Context<Self>,
 8443    ) {
 8444        if self.take_rename(true, window, cx).is_some() {
 8445            return;
 8446        }
 8447
 8448        if self
 8449            .context_menu
 8450            .borrow_mut()
 8451            .as_mut()
 8452            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8453            .unwrap_or(false)
 8454        {
 8455            return;
 8456        }
 8457
 8458        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8459            cx.propagate();
 8460            return;
 8461        }
 8462
 8463        let Some(row_count) = self.visible_row_count() else {
 8464            return;
 8465        };
 8466
 8467        let autoscroll = if action.center_cursor {
 8468            Autoscroll::center()
 8469        } else {
 8470            Autoscroll::fit()
 8471        };
 8472
 8473        let text_layout_details = &self.text_layout_details(window);
 8474
 8475        self.change_selections(Some(autoscroll), window, cx, |s| {
 8476            let line_mode = s.line_mode;
 8477            s.move_with(|map, selection| {
 8478                if !selection.is_empty() && !line_mode {
 8479                    selection.goal = SelectionGoal::None;
 8480                }
 8481                let (cursor, goal) = movement::up_by_rows(
 8482                    map,
 8483                    selection.end,
 8484                    row_count,
 8485                    selection.goal,
 8486                    false,
 8487                    text_layout_details,
 8488                );
 8489                selection.collapse_to(cursor, goal);
 8490            });
 8491        });
 8492    }
 8493
 8494    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8495        let text_layout_details = &self.text_layout_details(window);
 8496        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8497            s.move_heads_with(|map, head, goal| {
 8498                movement::up(map, head, goal, false, text_layout_details)
 8499            })
 8500        })
 8501    }
 8502
 8503    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8504        self.take_rename(true, window, cx);
 8505
 8506        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8507            cx.propagate();
 8508            return;
 8509        }
 8510
 8511        let text_layout_details = &self.text_layout_details(window);
 8512        let selection_count = self.selections.count();
 8513        let first_selection = self.selections.first_anchor();
 8514
 8515        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8516            let line_mode = s.line_mode;
 8517            s.move_with(|map, selection| {
 8518                if !selection.is_empty() && !line_mode {
 8519                    selection.goal = SelectionGoal::None;
 8520                }
 8521                let (cursor, goal) = movement::down(
 8522                    map,
 8523                    selection.end,
 8524                    selection.goal,
 8525                    false,
 8526                    text_layout_details,
 8527                );
 8528                selection.collapse_to(cursor, goal);
 8529            });
 8530        });
 8531
 8532        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8533        {
 8534            cx.propagate();
 8535        }
 8536    }
 8537
 8538    pub fn select_page_down(
 8539        &mut self,
 8540        _: &SelectPageDown,
 8541        window: &mut Window,
 8542        cx: &mut Context<Self>,
 8543    ) {
 8544        let Some(row_count) = self.visible_row_count() else {
 8545            return;
 8546        };
 8547
 8548        let text_layout_details = &self.text_layout_details(window);
 8549
 8550        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8551            s.move_heads_with(|map, head, goal| {
 8552                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8553            })
 8554        })
 8555    }
 8556
 8557    pub fn move_page_down(
 8558        &mut self,
 8559        action: &MovePageDown,
 8560        window: &mut Window,
 8561        cx: &mut Context<Self>,
 8562    ) {
 8563        if self.take_rename(true, window, cx).is_some() {
 8564            return;
 8565        }
 8566
 8567        if self
 8568            .context_menu
 8569            .borrow_mut()
 8570            .as_mut()
 8571            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8572            .unwrap_or(false)
 8573        {
 8574            return;
 8575        }
 8576
 8577        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8578            cx.propagate();
 8579            return;
 8580        }
 8581
 8582        let Some(row_count) = self.visible_row_count() else {
 8583            return;
 8584        };
 8585
 8586        let autoscroll = if action.center_cursor {
 8587            Autoscroll::center()
 8588        } else {
 8589            Autoscroll::fit()
 8590        };
 8591
 8592        let text_layout_details = &self.text_layout_details(window);
 8593        self.change_selections(Some(autoscroll), window, cx, |s| {
 8594            let line_mode = s.line_mode;
 8595            s.move_with(|map, selection| {
 8596                if !selection.is_empty() && !line_mode {
 8597                    selection.goal = SelectionGoal::None;
 8598                }
 8599                let (cursor, goal) = movement::down_by_rows(
 8600                    map,
 8601                    selection.end,
 8602                    row_count,
 8603                    selection.goal,
 8604                    false,
 8605                    text_layout_details,
 8606                );
 8607                selection.collapse_to(cursor, goal);
 8608            });
 8609        });
 8610    }
 8611
 8612    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8613        let text_layout_details = &self.text_layout_details(window);
 8614        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8615            s.move_heads_with(|map, head, goal| {
 8616                movement::down(map, head, goal, false, text_layout_details)
 8617            })
 8618        });
 8619    }
 8620
 8621    pub fn context_menu_first(
 8622        &mut self,
 8623        _: &ContextMenuFirst,
 8624        _window: &mut Window,
 8625        cx: &mut Context<Self>,
 8626    ) {
 8627        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8628            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8629        }
 8630    }
 8631
 8632    pub fn context_menu_prev(
 8633        &mut self,
 8634        _: &ContextMenuPrev,
 8635        _window: &mut Window,
 8636        cx: &mut Context<Self>,
 8637    ) {
 8638        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8639            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8640        }
 8641    }
 8642
 8643    pub fn context_menu_next(
 8644        &mut self,
 8645        _: &ContextMenuNext,
 8646        _window: &mut Window,
 8647        cx: &mut Context<Self>,
 8648    ) {
 8649        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8650            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8651        }
 8652    }
 8653
 8654    pub fn context_menu_last(
 8655        &mut self,
 8656        _: &ContextMenuLast,
 8657        _window: &mut Window,
 8658        cx: &mut Context<Self>,
 8659    ) {
 8660        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8661            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8662        }
 8663    }
 8664
 8665    pub fn move_to_previous_word_start(
 8666        &mut self,
 8667        _: &MoveToPreviousWordStart,
 8668        window: &mut Window,
 8669        cx: &mut Context<Self>,
 8670    ) {
 8671        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8672            s.move_cursors_with(|map, head, _| {
 8673                (
 8674                    movement::previous_word_start(map, head),
 8675                    SelectionGoal::None,
 8676                )
 8677            });
 8678        })
 8679    }
 8680
 8681    pub fn move_to_previous_subword_start(
 8682        &mut self,
 8683        _: &MoveToPreviousSubwordStart,
 8684        window: &mut Window,
 8685        cx: &mut Context<Self>,
 8686    ) {
 8687        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8688            s.move_cursors_with(|map, head, _| {
 8689                (
 8690                    movement::previous_subword_start(map, head),
 8691                    SelectionGoal::None,
 8692                )
 8693            });
 8694        })
 8695    }
 8696
 8697    pub fn select_to_previous_word_start(
 8698        &mut self,
 8699        _: &SelectToPreviousWordStart,
 8700        window: &mut Window,
 8701        cx: &mut Context<Self>,
 8702    ) {
 8703        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8704            s.move_heads_with(|map, head, _| {
 8705                (
 8706                    movement::previous_word_start(map, head),
 8707                    SelectionGoal::None,
 8708                )
 8709            });
 8710        })
 8711    }
 8712
 8713    pub fn select_to_previous_subword_start(
 8714        &mut self,
 8715        _: &SelectToPreviousSubwordStart,
 8716        window: &mut Window,
 8717        cx: &mut Context<Self>,
 8718    ) {
 8719        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8720            s.move_heads_with(|map, head, _| {
 8721                (
 8722                    movement::previous_subword_start(map, head),
 8723                    SelectionGoal::None,
 8724                )
 8725            });
 8726        })
 8727    }
 8728
 8729    pub fn delete_to_previous_word_start(
 8730        &mut self,
 8731        action: &DeleteToPreviousWordStart,
 8732        window: &mut Window,
 8733        cx: &mut Context<Self>,
 8734    ) {
 8735        self.transact(window, cx, |this, window, cx| {
 8736            this.select_autoclose_pair(window, cx);
 8737            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8738                let line_mode = s.line_mode;
 8739                s.move_with(|map, selection| {
 8740                    if selection.is_empty() && !line_mode {
 8741                        let cursor = if action.ignore_newlines {
 8742                            movement::previous_word_start(map, selection.head())
 8743                        } else {
 8744                            movement::previous_word_start_or_newline(map, selection.head())
 8745                        };
 8746                        selection.set_head(cursor, SelectionGoal::None);
 8747                    }
 8748                });
 8749            });
 8750            this.insert("", window, cx);
 8751        });
 8752    }
 8753
 8754    pub fn delete_to_previous_subword_start(
 8755        &mut self,
 8756        _: &DeleteToPreviousSubwordStart,
 8757        window: &mut Window,
 8758        cx: &mut Context<Self>,
 8759    ) {
 8760        self.transact(window, cx, |this, window, cx| {
 8761            this.select_autoclose_pair(window, cx);
 8762            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8763                let line_mode = s.line_mode;
 8764                s.move_with(|map, selection| {
 8765                    if selection.is_empty() && !line_mode {
 8766                        let cursor = movement::previous_subword_start(map, selection.head());
 8767                        selection.set_head(cursor, SelectionGoal::None);
 8768                    }
 8769                });
 8770            });
 8771            this.insert("", window, cx);
 8772        });
 8773    }
 8774
 8775    pub fn move_to_next_word_end(
 8776        &mut self,
 8777        _: &MoveToNextWordEnd,
 8778        window: &mut Window,
 8779        cx: &mut Context<Self>,
 8780    ) {
 8781        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8782            s.move_cursors_with(|map, head, _| {
 8783                (movement::next_word_end(map, head), SelectionGoal::None)
 8784            });
 8785        })
 8786    }
 8787
 8788    pub fn move_to_next_subword_end(
 8789        &mut self,
 8790        _: &MoveToNextSubwordEnd,
 8791        window: &mut Window,
 8792        cx: &mut Context<Self>,
 8793    ) {
 8794        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8795            s.move_cursors_with(|map, head, _| {
 8796                (movement::next_subword_end(map, head), SelectionGoal::None)
 8797            });
 8798        })
 8799    }
 8800
 8801    pub fn select_to_next_word_end(
 8802        &mut self,
 8803        _: &SelectToNextWordEnd,
 8804        window: &mut Window,
 8805        cx: &mut Context<Self>,
 8806    ) {
 8807        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8808            s.move_heads_with(|map, head, _| {
 8809                (movement::next_word_end(map, head), SelectionGoal::None)
 8810            });
 8811        })
 8812    }
 8813
 8814    pub fn select_to_next_subword_end(
 8815        &mut self,
 8816        _: &SelectToNextSubwordEnd,
 8817        window: &mut Window,
 8818        cx: &mut Context<Self>,
 8819    ) {
 8820        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8821            s.move_heads_with(|map, head, _| {
 8822                (movement::next_subword_end(map, head), SelectionGoal::None)
 8823            });
 8824        })
 8825    }
 8826
 8827    pub fn delete_to_next_word_end(
 8828        &mut self,
 8829        action: &DeleteToNextWordEnd,
 8830        window: &mut Window,
 8831        cx: &mut Context<Self>,
 8832    ) {
 8833        self.transact(window, cx, |this, window, cx| {
 8834            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8835                let line_mode = s.line_mode;
 8836                s.move_with(|map, selection| {
 8837                    if selection.is_empty() && !line_mode {
 8838                        let cursor = if action.ignore_newlines {
 8839                            movement::next_word_end(map, selection.head())
 8840                        } else {
 8841                            movement::next_word_end_or_newline(map, selection.head())
 8842                        };
 8843                        selection.set_head(cursor, SelectionGoal::None);
 8844                    }
 8845                });
 8846            });
 8847            this.insert("", window, cx);
 8848        });
 8849    }
 8850
 8851    pub fn delete_to_next_subword_end(
 8852        &mut self,
 8853        _: &DeleteToNextSubwordEnd,
 8854        window: &mut Window,
 8855        cx: &mut Context<Self>,
 8856    ) {
 8857        self.transact(window, cx, |this, window, cx| {
 8858            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8859                s.move_with(|map, selection| {
 8860                    if selection.is_empty() {
 8861                        let cursor = movement::next_subword_end(map, selection.head());
 8862                        selection.set_head(cursor, SelectionGoal::None);
 8863                    }
 8864                });
 8865            });
 8866            this.insert("", window, cx);
 8867        });
 8868    }
 8869
 8870    pub fn move_to_beginning_of_line(
 8871        &mut self,
 8872        action: &MoveToBeginningOfLine,
 8873        window: &mut Window,
 8874        cx: &mut Context<Self>,
 8875    ) {
 8876        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8877            s.move_cursors_with(|map, head, _| {
 8878                (
 8879                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8880                    SelectionGoal::None,
 8881                )
 8882            });
 8883        })
 8884    }
 8885
 8886    pub fn select_to_beginning_of_line(
 8887        &mut self,
 8888        action: &SelectToBeginningOfLine,
 8889        window: &mut Window,
 8890        cx: &mut Context<Self>,
 8891    ) {
 8892        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8893            s.move_heads_with(|map, head, _| {
 8894                (
 8895                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8896                    SelectionGoal::None,
 8897                )
 8898            });
 8899        });
 8900    }
 8901
 8902    pub fn delete_to_beginning_of_line(
 8903        &mut self,
 8904        _: &DeleteToBeginningOfLine,
 8905        window: &mut Window,
 8906        cx: &mut Context<Self>,
 8907    ) {
 8908        self.transact(window, cx, |this, window, cx| {
 8909            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8910                s.move_with(|_, selection| {
 8911                    selection.reversed = true;
 8912                });
 8913            });
 8914
 8915            this.select_to_beginning_of_line(
 8916                &SelectToBeginningOfLine {
 8917                    stop_at_soft_wraps: false,
 8918                },
 8919                window,
 8920                cx,
 8921            );
 8922            this.backspace(&Backspace, window, cx);
 8923        });
 8924    }
 8925
 8926    pub fn move_to_end_of_line(
 8927        &mut self,
 8928        action: &MoveToEndOfLine,
 8929        window: &mut Window,
 8930        cx: &mut Context<Self>,
 8931    ) {
 8932        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8933            s.move_cursors_with(|map, head, _| {
 8934                (
 8935                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8936                    SelectionGoal::None,
 8937                )
 8938            });
 8939        })
 8940    }
 8941
 8942    pub fn select_to_end_of_line(
 8943        &mut self,
 8944        action: &SelectToEndOfLine,
 8945        window: &mut Window,
 8946        cx: &mut Context<Self>,
 8947    ) {
 8948        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8949            s.move_heads_with(|map, head, _| {
 8950                (
 8951                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8952                    SelectionGoal::None,
 8953                )
 8954            });
 8955        })
 8956    }
 8957
 8958    pub fn delete_to_end_of_line(
 8959        &mut self,
 8960        _: &DeleteToEndOfLine,
 8961        window: &mut Window,
 8962        cx: &mut Context<Self>,
 8963    ) {
 8964        self.transact(window, cx, |this, window, cx| {
 8965            this.select_to_end_of_line(
 8966                &SelectToEndOfLine {
 8967                    stop_at_soft_wraps: false,
 8968                },
 8969                window,
 8970                cx,
 8971            );
 8972            this.delete(&Delete, window, cx);
 8973        });
 8974    }
 8975
 8976    pub fn cut_to_end_of_line(
 8977        &mut self,
 8978        _: &CutToEndOfLine,
 8979        window: &mut Window,
 8980        cx: &mut Context<Self>,
 8981    ) {
 8982        self.transact(window, cx, |this, window, cx| {
 8983            this.select_to_end_of_line(
 8984                &SelectToEndOfLine {
 8985                    stop_at_soft_wraps: false,
 8986                },
 8987                window,
 8988                cx,
 8989            );
 8990            this.cut(&Cut, window, cx);
 8991        });
 8992    }
 8993
 8994    pub fn move_to_start_of_paragraph(
 8995        &mut self,
 8996        _: &MoveToStartOfParagraph,
 8997        window: &mut Window,
 8998        cx: &mut Context<Self>,
 8999    ) {
 9000        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9001            cx.propagate();
 9002            return;
 9003        }
 9004
 9005        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9006            s.move_with(|map, selection| {
 9007                selection.collapse_to(
 9008                    movement::start_of_paragraph(map, selection.head(), 1),
 9009                    SelectionGoal::None,
 9010                )
 9011            });
 9012        })
 9013    }
 9014
 9015    pub fn move_to_end_of_paragraph(
 9016        &mut self,
 9017        _: &MoveToEndOfParagraph,
 9018        window: &mut Window,
 9019        cx: &mut Context<Self>,
 9020    ) {
 9021        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9022            cx.propagate();
 9023            return;
 9024        }
 9025
 9026        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9027            s.move_with(|map, selection| {
 9028                selection.collapse_to(
 9029                    movement::end_of_paragraph(map, selection.head(), 1),
 9030                    SelectionGoal::None,
 9031                )
 9032            });
 9033        })
 9034    }
 9035
 9036    pub fn select_to_start_of_paragraph(
 9037        &mut self,
 9038        _: &SelectToStartOfParagraph,
 9039        window: &mut Window,
 9040        cx: &mut Context<Self>,
 9041    ) {
 9042        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9043            cx.propagate();
 9044            return;
 9045        }
 9046
 9047        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9048            s.move_heads_with(|map, head, _| {
 9049                (
 9050                    movement::start_of_paragraph(map, head, 1),
 9051                    SelectionGoal::None,
 9052                )
 9053            });
 9054        })
 9055    }
 9056
 9057    pub fn select_to_end_of_paragraph(
 9058        &mut self,
 9059        _: &SelectToEndOfParagraph,
 9060        window: &mut Window,
 9061        cx: &mut Context<Self>,
 9062    ) {
 9063        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9064            cx.propagate();
 9065            return;
 9066        }
 9067
 9068        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9069            s.move_heads_with(|map, head, _| {
 9070                (
 9071                    movement::end_of_paragraph(map, head, 1),
 9072                    SelectionGoal::None,
 9073                )
 9074            });
 9075        })
 9076    }
 9077
 9078    pub fn move_to_beginning(
 9079        &mut self,
 9080        _: &MoveToBeginning,
 9081        window: &mut Window,
 9082        cx: &mut Context<Self>,
 9083    ) {
 9084        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9085            cx.propagate();
 9086            return;
 9087        }
 9088
 9089        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9090            s.select_ranges(vec![0..0]);
 9091        });
 9092    }
 9093
 9094    pub fn select_to_beginning(
 9095        &mut self,
 9096        _: &SelectToBeginning,
 9097        window: &mut Window,
 9098        cx: &mut Context<Self>,
 9099    ) {
 9100        let mut selection = self.selections.last::<Point>(cx);
 9101        selection.set_head(Point::zero(), SelectionGoal::None);
 9102
 9103        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9104            s.select(vec![selection]);
 9105        });
 9106    }
 9107
 9108    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9109        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9110            cx.propagate();
 9111            return;
 9112        }
 9113
 9114        let cursor = self.buffer.read(cx).read(cx).len();
 9115        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9116            s.select_ranges(vec![cursor..cursor])
 9117        });
 9118    }
 9119
 9120    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9121        self.nav_history = nav_history;
 9122    }
 9123
 9124    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9125        self.nav_history.as_ref()
 9126    }
 9127
 9128    fn push_to_nav_history(
 9129        &mut self,
 9130        cursor_anchor: Anchor,
 9131        new_position: Option<Point>,
 9132        cx: &mut Context<Self>,
 9133    ) {
 9134        if let Some(nav_history) = self.nav_history.as_mut() {
 9135            let buffer = self.buffer.read(cx).read(cx);
 9136            let cursor_position = cursor_anchor.to_point(&buffer);
 9137            let scroll_state = self.scroll_manager.anchor();
 9138            let scroll_top_row = scroll_state.top_row(&buffer);
 9139            drop(buffer);
 9140
 9141            if let Some(new_position) = new_position {
 9142                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9143                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9144                    return;
 9145                }
 9146            }
 9147
 9148            nav_history.push(
 9149                Some(NavigationData {
 9150                    cursor_anchor,
 9151                    cursor_position,
 9152                    scroll_anchor: scroll_state,
 9153                    scroll_top_row,
 9154                }),
 9155                cx,
 9156            );
 9157        }
 9158    }
 9159
 9160    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9161        let buffer = self.buffer.read(cx).snapshot(cx);
 9162        let mut selection = self.selections.first::<usize>(cx);
 9163        selection.set_head(buffer.len(), SelectionGoal::None);
 9164        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9165            s.select(vec![selection]);
 9166        });
 9167    }
 9168
 9169    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9170        let end = self.buffer.read(cx).read(cx).len();
 9171        self.change_selections(None, window, cx, |s| {
 9172            s.select_ranges(vec![0..end]);
 9173        });
 9174    }
 9175
 9176    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9177        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9178        let mut selections = self.selections.all::<Point>(cx);
 9179        let max_point = display_map.buffer_snapshot.max_point();
 9180        for selection in &mut selections {
 9181            let rows = selection.spanned_rows(true, &display_map);
 9182            selection.start = Point::new(rows.start.0, 0);
 9183            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9184            selection.reversed = false;
 9185        }
 9186        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9187            s.select(selections);
 9188        });
 9189    }
 9190
 9191    pub fn split_selection_into_lines(
 9192        &mut self,
 9193        _: &SplitSelectionIntoLines,
 9194        window: &mut Window,
 9195        cx: &mut Context<Self>,
 9196    ) {
 9197        let selections = self
 9198            .selections
 9199            .all::<Point>(cx)
 9200            .into_iter()
 9201            .map(|selection| selection.start..selection.end)
 9202            .collect::<Vec<_>>();
 9203        self.unfold_ranges(&selections, true, true, cx);
 9204
 9205        let mut new_selection_ranges = Vec::new();
 9206        {
 9207            let buffer = self.buffer.read(cx).read(cx);
 9208            for selection in selections {
 9209                for row in selection.start.row..selection.end.row {
 9210                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9211                    new_selection_ranges.push(cursor..cursor);
 9212                }
 9213
 9214                let is_multiline_selection = selection.start.row != selection.end.row;
 9215                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9216                // so this action feels more ergonomic when paired with other selection operations
 9217                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9218                if !should_skip_last {
 9219                    new_selection_ranges.push(selection.end..selection.end);
 9220                }
 9221            }
 9222        }
 9223        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9224            s.select_ranges(new_selection_ranges);
 9225        });
 9226    }
 9227
 9228    pub fn add_selection_above(
 9229        &mut self,
 9230        _: &AddSelectionAbove,
 9231        window: &mut Window,
 9232        cx: &mut Context<Self>,
 9233    ) {
 9234        self.add_selection(true, window, cx);
 9235    }
 9236
 9237    pub fn add_selection_below(
 9238        &mut self,
 9239        _: &AddSelectionBelow,
 9240        window: &mut Window,
 9241        cx: &mut Context<Self>,
 9242    ) {
 9243        self.add_selection(false, window, cx);
 9244    }
 9245
 9246    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9247        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9248        let mut selections = self.selections.all::<Point>(cx);
 9249        let text_layout_details = self.text_layout_details(window);
 9250        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9251            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9252            let range = oldest_selection.display_range(&display_map).sorted();
 9253
 9254            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9255            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9256            let positions = start_x.min(end_x)..start_x.max(end_x);
 9257
 9258            selections.clear();
 9259            let mut stack = Vec::new();
 9260            for row in range.start.row().0..=range.end.row().0 {
 9261                if let Some(selection) = self.selections.build_columnar_selection(
 9262                    &display_map,
 9263                    DisplayRow(row),
 9264                    &positions,
 9265                    oldest_selection.reversed,
 9266                    &text_layout_details,
 9267                ) {
 9268                    stack.push(selection.id);
 9269                    selections.push(selection);
 9270                }
 9271            }
 9272
 9273            if above {
 9274                stack.reverse();
 9275            }
 9276
 9277            AddSelectionsState { above, stack }
 9278        });
 9279
 9280        let last_added_selection = *state.stack.last().unwrap();
 9281        let mut new_selections = Vec::new();
 9282        if above == state.above {
 9283            let end_row = if above {
 9284                DisplayRow(0)
 9285            } else {
 9286                display_map.max_point().row()
 9287            };
 9288
 9289            'outer: for selection in selections {
 9290                if selection.id == last_added_selection {
 9291                    let range = selection.display_range(&display_map).sorted();
 9292                    debug_assert_eq!(range.start.row(), range.end.row());
 9293                    let mut row = range.start.row();
 9294                    let positions =
 9295                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9296                            px(start)..px(end)
 9297                        } else {
 9298                            let start_x =
 9299                                display_map.x_for_display_point(range.start, &text_layout_details);
 9300                            let end_x =
 9301                                display_map.x_for_display_point(range.end, &text_layout_details);
 9302                            start_x.min(end_x)..start_x.max(end_x)
 9303                        };
 9304
 9305                    while row != end_row {
 9306                        if above {
 9307                            row.0 -= 1;
 9308                        } else {
 9309                            row.0 += 1;
 9310                        }
 9311
 9312                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9313                            &display_map,
 9314                            row,
 9315                            &positions,
 9316                            selection.reversed,
 9317                            &text_layout_details,
 9318                        ) {
 9319                            state.stack.push(new_selection.id);
 9320                            if above {
 9321                                new_selections.push(new_selection);
 9322                                new_selections.push(selection);
 9323                            } else {
 9324                                new_selections.push(selection);
 9325                                new_selections.push(new_selection);
 9326                            }
 9327
 9328                            continue 'outer;
 9329                        }
 9330                    }
 9331                }
 9332
 9333                new_selections.push(selection);
 9334            }
 9335        } else {
 9336            new_selections = selections;
 9337            new_selections.retain(|s| s.id != last_added_selection);
 9338            state.stack.pop();
 9339        }
 9340
 9341        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9342            s.select(new_selections);
 9343        });
 9344        if state.stack.len() > 1 {
 9345            self.add_selections_state = Some(state);
 9346        }
 9347    }
 9348
 9349    pub fn select_next_match_internal(
 9350        &mut self,
 9351        display_map: &DisplaySnapshot,
 9352        replace_newest: bool,
 9353        autoscroll: Option<Autoscroll>,
 9354        window: &mut Window,
 9355        cx: &mut Context<Self>,
 9356    ) -> Result<()> {
 9357        fn select_next_match_ranges(
 9358            this: &mut Editor,
 9359            range: Range<usize>,
 9360            replace_newest: bool,
 9361            auto_scroll: Option<Autoscroll>,
 9362            window: &mut Window,
 9363            cx: &mut Context<Editor>,
 9364        ) {
 9365            this.unfold_ranges(&[range.clone()], false, true, cx);
 9366            this.change_selections(auto_scroll, window, cx, |s| {
 9367                if replace_newest {
 9368                    s.delete(s.newest_anchor().id);
 9369                }
 9370                s.insert_range(range.clone());
 9371            });
 9372        }
 9373
 9374        let buffer = &display_map.buffer_snapshot;
 9375        let mut selections = self.selections.all::<usize>(cx);
 9376        if let Some(mut select_next_state) = self.select_next_state.take() {
 9377            let query = &select_next_state.query;
 9378            if !select_next_state.done {
 9379                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9380                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9381                let mut next_selected_range = None;
 9382
 9383                let bytes_after_last_selection =
 9384                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9385                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9386                let query_matches = query
 9387                    .stream_find_iter(bytes_after_last_selection)
 9388                    .map(|result| (last_selection.end, result))
 9389                    .chain(
 9390                        query
 9391                            .stream_find_iter(bytes_before_first_selection)
 9392                            .map(|result| (0, result)),
 9393                    );
 9394
 9395                for (start_offset, query_match) in query_matches {
 9396                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9397                    let offset_range =
 9398                        start_offset + query_match.start()..start_offset + query_match.end();
 9399                    let display_range = offset_range.start.to_display_point(display_map)
 9400                        ..offset_range.end.to_display_point(display_map);
 9401
 9402                    if !select_next_state.wordwise
 9403                        || (!movement::is_inside_word(display_map, display_range.start)
 9404                            && !movement::is_inside_word(display_map, display_range.end))
 9405                    {
 9406                        // TODO: This is n^2, because we might check all the selections
 9407                        if !selections
 9408                            .iter()
 9409                            .any(|selection| selection.range().overlaps(&offset_range))
 9410                        {
 9411                            next_selected_range = Some(offset_range);
 9412                            break;
 9413                        }
 9414                    }
 9415                }
 9416
 9417                if let Some(next_selected_range) = next_selected_range {
 9418                    select_next_match_ranges(
 9419                        self,
 9420                        next_selected_range,
 9421                        replace_newest,
 9422                        autoscroll,
 9423                        window,
 9424                        cx,
 9425                    );
 9426                } else {
 9427                    select_next_state.done = true;
 9428                }
 9429            }
 9430
 9431            self.select_next_state = Some(select_next_state);
 9432        } else {
 9433            let mut only_carets = true;
 9434            let mut same_text_selected = true;
 9435            let mut selected_text = None;
 9436
 9437            let mut selections_iter = selections.iter().peekable();
 9438            while let Some(selection) = selections_iter.next() {
 9439                if selection.start != selection.end {
 9440                    only_carets = false;
 9441                }
 9442
 9443                if same_text_selected {
 9444                    if selected_text.is_none() {
 9445                        selected_text =
 9446                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9447                    }
 9448
 9449                    if let Some(next_selection) = selections_iter.peek() {
 9450                        if next_selection.range().len() == selection.range().len() {
 9451                            let next_selected_text = buffer
 9452                                .text_for_range(next_selection.range())
 9453                                .collect::<String>();
 9454                            if Some(next_selected_text) != selected_text {
 9455                                same_text_selected = false;
 9456                                selected_text = None;
 9457                            }
 9458                        } else {
 9459                            same_text_selected = false;
 9460                            selected_text = None;
 9461                        }
 9462                    }
 9463                }
 9464            }
 9465
 9466            if only_carets {
 9467                for selection in &mut selections {
 9468                    let word_range = movement::surrounding_word(
 9469                        display_map,
 9470                        selection.start.to_display_point(display_map),
 9471                    );
 9472                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9473                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9474                    selection.goal = SelectionGoal::None;
 9475                    selection.reversed = false;
 9476                    select_next_match_ranges(
 9477                        self,
 9478                        selection.start..selection.end,
 9479                        replace_newest,
 9480                        autoscroll,
 9481                        window,
 9482                        cx,
 9483                    );
 9484                }
 9485
 9486                if selections.len() == 1 {
 9487                    let selection = selections
 9488                        .last()
 9489                        .expect("ensured that there's only one selection");
 9490                    let query = buffer
 9491                        .text_for_range(selection.start..selection.end)
 9492                        .collect::<String>();
 9493                    let is_empty = query.is_empty();
 9494                    let select_state = SelectNextState {
 9495                        query: AhoCorasick::new(&[query])?,
 9496                        wordwise: true,
 9497                        done: is_empty,
 9498                    };
 9499                    self.select_next_state = Some(select_state);
 9500                } else {
 9501                    self.select_next_state = None;
 9502                }
 9503            } else if let Some(selected_text) = selected_text {
 9504                self.select_next_state = Some(SelectNextState {
 9505                    query: AhoCorasick::new(&[selected_text])?,
 9506                    wordwise: false,
 9507                    done: false,
 9508                });
 9509                self.select_next_match_internal(
 9510                    display_map,
 9511                    replace_newest,
 9512                    autoscroll,
 9513                    window,
 9514                    cx,
 9515                )?;
 9516            }
 9517        }
 9518        Ok(())
 9519    }
 9520
 9521    pub fn select_all_matches(
 9522        &mut self,
 9523        _action: &SelectAllMatches,
 9524        window: &mut Window,
 9525        cx: &mut Context<Self>,
 9526    ) -> Result<()> {
 9527        self.push_to_selection_history();
 9528        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9529
 9530        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9531        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9532            return Ok(());
 9533        };
 9534        if select_next_state.done {
 9535            return Ok(());
 9536        }
 9537
 9538        let mut new_selections = self.selections.all::<usize>(cx);
 9539
 9540        let buffer = &display_map.buffer_snapshot;
 9541        let query_matches = select_next_state
 9542            .query
 9543            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9544
 9545        for query_match in query_matches {
 9546            let query_match = query_match.unwrap(); // can only fail due to I/O
 9547            let offset_range = query_match.start()..query_match.end();
 9548            let display_range = offset_range.start.to_display_point(&display_map)
 9549                ..offset_range.end.to_display_point(&display_map);
 9550
 9551            if !select_next_state.wordwise
 9552                || (!movement::is_inside_word(&display_map, display_range.start)
 9553                    && !movement::is_inside_word(&display_map, display_range.end))
 9554            {
 9555                self.selections.change_with(cx, |selections| {
 9556                    new_selections.push(Selection {
 9557                        id: selections.new_selection_id(),
 9558                        start: offset_range.start,
 9559                        end: offset_range.end,
 9560                        reversed: false,
 9561                        goal: SelectionGoal::None,
 9562                    });
 9563                });
 9564            }
 9565        }
 9566
 9567        new_selections.sort_by_key(|selection| selection.start);
 9568        let mut ix = 0;
 9569        while ix + 1 < new_selections.len() {
 9570            let current_selection = &new_selections[ix];
 9571            let next_selection = &new_selections[ix + 1];
 9572            if current_selection.range().overlaps(&next_selection.range()) {
 9573                if current_selection.id < next_selection.id {
 9574                    new_selections.remove(ix + 1);
 9575                } else {
 9576                    new_selections.remove(ix);
 9577                }
 9578            } else {
 9579                ix += 1;
 9580            }
 9581        }
 9582
 9583        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9584
 9585        for selection in new_selections.iter_mut() {
 9586            selection.reversed = reversed;
 9587        }
 9588
 9589        select_next_state.done = true;
 9590        self.unfold_ranges(
 9591            &new_selections
 9592                .iter()
 9593                .map(|selection| selection.range())
 9594                .collect::<Vec<_>>(),
 9595            false,
 9596            false,
 9597            cx,
 9598        );
 9599        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9600            selections.select(new_selections)
 9601        });
 9602
 9603        Ok(())
 9604    }
 9605
 9606    pub fn select_next(
 9607        &mut self,
 9608        action: &SelectNext,
 9609        window: &mut Window,
 9610        cx: &mut Context<Self>,
 9611    ) -> Result<()> {
 9612        self.push_to_selection_history();
 9613        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9614        self.select_next_match_internal(
 9615            &display_map,
 9616            action.replace_newest,
 9617            Some(Autoscroll::newest()),
 9618            window,
 9619            cx,
 9620        )?;
 9621        Ok(())
 9622    }
 9623
 9624    pub fn select_previous(
 9625        &mut self,
 9626        action: &SelectPrevious,
 9627        window: &mut Window,
 9628        cx: &mut Context<Self>,
 9629    ) -> Result<()> {
 9630        self.push_to_selection_history();
 9631        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9632        let buffer = &display_map.buffer_snapshot;
 9633        let mut selections = self.selections.all::<usize>(cx);
 9634        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9635            let query = &select_prev_state.query;
 9636            if !select_prev_state.done {
 9637                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9638                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9639                let mut next_selected_range = None;
 9640                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9641                let bytes_before_last_selection =
 9642                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9643                let bytes_after_first_selection =
 9644                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9645                let query_matches = query
 9646                    .stream_find_iter(bytes_before_last_selection)
 9647                    .map(|result| (last_selection.start, result))
 9648                    .chain(
 9649                        query
 9650                            .stream_find_iter(bytes_after_first_selection)
 9651                            .map(|result| (buffer.len(), result)),
 9652                    );
 9653                for (end_offset, query_match) in query_matches {
 9654                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9655                    let offset_range =
 9656                        end_offset - query_match.end()..end_offset - query_match.start();
 9657                    let display_range = offset_range.start.to_display_point(&display_map)
 9658                        ..offset_range.end.to_display_point(&display_map);
 9659
 9660                    if !select_prev_state.wordwise
 9661                        || (!movement::is_inside_word(&display_map, display_range.start)
 9662                            && !movement::is_inside_word(&display_map, display_range.end))
 9663                    {
 9664                        next_selected_range = Some(offset_range);
 9665                        break;
 9666                    }
 9667                }
 9668
 9669                if let Some(next_selected_range) = next_selected_range {
 9670                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9671                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9672                        if action.replace_newest {
 9673                            s.delete(s.newest_anchor().id);
 9674                        }
 9675                        s.insert_range(next_selected_range);
 9676                    });
 9677                } else {
 9678                    select_prev_state.done = true;
 9679                }
 9680            }
 9681
 9682            self.select_prev_state = Some(select_prev_state);
 9683        } else {
 9684            let mut only_carets = true;
 9685            let mut same_text_selected = true;
 9686            let mut selected_text = None;
 9687
 9688            let mut selections_iter = selections.iter().peekable();
 9689            while let Some(selection) = selections_iter.next() {
 9690                if selection.start != selection.end {
 9691                    only_carets = false;
 9692                }
 9693
 9694                if same_text_selected {
 9695                    if selected_text.is_none() {
 9696                        selected_text =
 9697                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9698                    }
 9699
 9700                    if let Some(next_selection) = selections_iter.peek() {
 9701                        if next_selection.range().len() == selection.range().len() {
 9702                            let next_selected_text = buffer
 9703                                .text_for_range(next_selection.range())
 9704                                .collect::<String>();
 9705                            if Some(next_selected_text) != selected_text {
 9706                                same_text_selected = false;
 9707                                selected_text = None;
 9708                            }
 9709                        } else {
 9710                            same_text_selected = false;
 9711                            selected_text = None;
 9712                        }
 9713                    }
 9714                }
 9715            }
 9716
 9717            if only_carets {
 9718                for selection in &mut selections {
 9719                    let word_range = movement::surrounding_word(
 9720                        &display_map,
 9721                        selection.start.to_display_point(&display_map),
 9722                    );
 9723                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9724                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9725                    selection.goal = SelectionGoal::None;
 9726                    selection.reversed = false;
 9727                }
 9728                if selections.len() == 1 {
 9729                    let selection = selections
 9730                        .last()
 9731                        .expect("ensured that there's only one selection");
 9732                    let query = buffer
 9733                        .text_for_range(selection.start..selection.end)
 9734                        .collect::<String>();
 9735                    let is_empty = query.is_empty();
 9736                    let select_state = SelectNextState {
 9737                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9738                        wordwise: true,
 9739                        done: is_empty,
 9740                    };
 9741                    self.select_prev_state = Some(select_state);
 9742                } else {
 9743                    self.select_prev_state = None;
 9744                }
 9745
 9746                self.unfold_ranges(
 9747                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9748                    false,
 9749                    true,
 9750                    cx,
 9751                );
 9752                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9753                    s.select(selections);
 9754                });
 9755            } else if let Some(selected_text) = selected_text {
 9756                self.select_prev_state = Some(SelectNextState {
 9757                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9758                    wordwise: false,
 9759                    done: false,
 9760                });
 9761                self.select_previous(action, window, cx)?;
 9762            }
 9763        }
 9764        Ok(())
 9765    }
 9766
 9767    pub fn toggle_comments(
 9768        &mut self,
 9769        action: &ToggleComments,
 9770        window: &mut Window,
 9771        cx: &mut Context<Self>,
 9772    ) {
 9773        if self.read_only(cx) {
 9774            return;
 9775        }
 9776        let text_layout_details = &self.text_layout_details(window);
 9777        self.transact(window, cx, |this, window, cx| {
 9778            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9779            let mut edits = Vec::new();
 9780            let mut selection_edit_ranges = Vec::new();
 9781            let mut last_toggled_row = None;
 9782            let snapshot = this.buffer.read(cx).read(cx);
 9783            let empty_str: Arc<str> = Arc::default();
 9784            let mut suffixes_inserted = Vec::new();
 9785            let ignore_indent = action.ignore_indent;
 9786
 9787            fn comment_prefix_range(
 9788                snapshot: &MultiBufferSnapshot,
 9789                row: MultiBufferRow,
 9790                comment_prefix: &str,
 9791                comment_prefix_whitespace: &str,
 9792                ignore_indent: bool,
 9793            ) -> Range<Point> {
 9794                let indent_size = if ignore_indent {
 9795                    0
 9796                } else {
 9797                    snapshot.indent_size_for_line(row).len
 9798                };
 9799
 9800                let start = Point::new(row.0, indent_size);
 9801
 9802                let mut line_bytes = snapshot
 9803                    .bytes_in_range(start..snapshot.max_point())
 9804                    .flatten()
 9805                    .copied();
 9806
 9807                // If this line currently begins with the line comment prefix, then record
 9808                // the range containing the prefix.
 9809                if line_bytes
 9810                    .by_ref()
 9811                    .take(comment_prefix.len())
 9812                    .eq(comment_prefix.bytes())
 9813                {
 9814                    // Include any whitespace that matches the comment prefix.
 9815                    let matching_whitespace_len = line_bytes
 9816                        .zip(comment_prefix_whitespace.bytes())
 9817                        .take_while(|(a, b)| a == b)
 9818                        .count() as u32;
 9819                    let end = Point::new(
 9820                        start.row,
 9821                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9822                    );
 9823                    start..end
 9824                } else {
 9825                    start..start
 9826                }
 9827            }
 9828
 9829            fn comment_suffix_range(
 9830                snapshot: &MultiBufferSnapshot,
 9831                row: MultiBufferRow,
 9832                comment_suffix: &str,
 9833                comment_suffix_has_leading_space: bool,
 9834            ) -> Range<Point> {
 9835                let end = Point::new(row.0, snapshot.line_len(row));
 9836                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9837
 9838                let mut line_end_bytes = snapshot
 9839                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9840                    .flatten()
 9841                    .copied();
 9842
 9843                let leading_space_len = if suffix_start_column > 0
 9844                    && line_end_bytes.next() == Some(b' ')
 9845                    && comment_suffix_has_leading_space
 9846                {
 9847                    1
 9848                } else {
 9849                    0
 9850                };
 9851
 9852                // If this line currently begins with the line comment prefix, then record
 9853                // the range containing the prefix.
 9854                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9855                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9856                    start..end
 9857                } else {
 9858                    end..end
 9859                }
 9860            }
 9861
 9862            // TODO: Handle selections that cross excerpts
 9863            for selection in &mut selections {
 9864                let start_column = snapshot
 9865                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9866                    .len;
 9867                let language = if let Some(language) =
 9868                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9869                {
 9870                    language
 9871                } else {
 9872                    continue;
 9873                };
 9874
 9875                selection_edit_ranges.clear();
 9876
 9877                // If multiple selections contain a given row, avoid processing that
 9878                // row more than once.
 9879                let mut start_row = MultiBufferRow(selection.start.row);
 9880                if last_toggled_row == Some(start_row) {
 9881                    start_row = start_row.next_row();
 9882                }
 9883                let end_row =
 9884                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9885                        MultiBufferRow(selection.end.row - 1)
 9886                    } else {
 9887                        MultiBufferRow(selection.end.row)
 9888                    };
 9889                last_toggled_row = Some(end_row);
 9890
 9891                if start_row > end_row {
 9892                    continue;
 9893                }
 9894
 9895                // If the language has line comments, toggle those.
 9896                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9897
 9898                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9899                if ignore_indent {
 9900                    full_comment_prefixes = full_comment_prefixes
 9901                        .into_iter()
 9902                        .map(|s| Arc::from(s.trim_end()))
 9903                        .collect();
 9904                }
 9905
 9906                if !full_comment_prefixes.is_empty() {
 9907                    let first_prefix = full_comment_prefixes
 9908                        .first()
 9909                        .expect("prefixes is non-empty");
 9910                    let prefix_trimmed_lengths = full_comment_prefixes
 9911                        .iter()
 9912                        .map(|p| p.trim_end_matches(' ').len())
 9913                        .collect::<SmallVec<[usize; 4]>>();
 9914
 9915                    let mut all_selection_lines_are_comments = true;
 9916
 9917                    for row in start_row.0..=end_row.0 {
 9918                        let row = MultiBufferRow(row);
 9919                        if start_row < end_row && snapshot.is_line_blank(row) {
 9920                            continue;
 9921                        }
 9922
 9923                        let prefix_range = full_comment_prefixes
 9924                            .iter()
 9925                            .zip(prefix_trimmed_lengths.iter().copied())
 9926                            .map(|(prefix, trimmed_prefix_len)| {
 9927                                comment_prefix_range(
 9928                                    snapshot.deref(),
 9929                                    row,
 9930                                    &prefix[..trimmed_prefix_len],
 9931                                    &prefix[trimmed_prefix_len..],
 9932                                    ignore_indent,
 9933                                )
 9934                            })
 9935                            .max_by_key(|range| range.end.column - range.start.column)
 9936                            .expect("prefixes is non-empty");
 9937
 9938                        if prefix_range.is_empty() {
 9939                            all_selection_lines_are_comments = false;
 9940                        }
 9941
 9942                        selection_edit_ranges.push(prefix_range);
 9943                    }
 9944
 9945                    if all_selection_lines_are_comments {
 9946                        edits.extend(
 9947                            selection_edit_ranges
 9948                                .iter()
 9949                                .cloned()
 9950                                .map(|range| (range, empty_str.clone())),
 9951                        );
 9952                    } else {
 9953                        let min_column = selection_edit_ranges
 9954                            .iter()
 9955                            .map(|range| range.start.column)
 9956                            .min()
 9957                            .unwrap_or(0);
 9958                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9959                            let position = Point::new(range.start.row, min_column);
 9960                            (position..position, first_prefix.clone())
 9961                        }));
 9962                    }
 9963                } else if let Some((full_comment_prefix, comment_suffix)) =
 9964                    language.block_comment_delimiters()
 9965                {
 9966                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9967                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9968                    let prefix_range = comment_prefix_range(
 9969                        snapshot.deref(),
 9970                        start_row,
 9971                        comment_prefix,
 9972                        comment_prefix_whitespace,
 9973                        ignore_indent,
 9974                    );
 9975                    let suffix_range = comment_suffix_range(
 9976                        snapshot.deref(),
 9977                        end_row,
 9978                        comment_suffix.trim_start_matches(' '),
 9979                        comment_suffix.starts_with(' '),
 9980                    );
 9981
 9982                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9983                        edits.push((
 9984                            prefix_range.start..prefix_range.start,
 9985                            full_comment_prefix.clone(),
 9986                        ));
 9987                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9988                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9989                    } else {
 9990                        edits.push((prefix_range, empty_str.clone()));
 9991                        edits.push((suffix_range, empty_str.clone()));
 9992                    }
 9993                } else {
 9994                    continue;
 9995                }
 9996            }
 9997
 9998            drop(snapshot);
 9999            this.buffer.update(cx, |buffer, cx| {
10000                buffer.edit(edits, None, cx);
10001            });
10002
10003            // Adjust selections so that they end before any comment suffixes that
10004            // were inserted.
10005            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10006            let mut selections = this.selections.all::<Point>(cx);
10007            let snapshot = this.buffer.read(cx).read(cx);
10008            for selection in &mut selections {
10009                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10010                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10011                        Ordering::Less => {
10012                            suffixes_inserted.next();
10013                            continue;
10014                        }
10015                        Ordering::Greater => break,
10016                        Ordering::Equal => {
10017                            if selection.end.column == snapshot.line_len(row) {
10018                                if selection.is_empty() {
10019                                    selection.start.column -= suffix_len as u32;
10020                                }
10021                                selection.end.column -= suffix_len as u32;
10022                            }
10023                            break;
10024                        }
10025                    }
10026                }
10027            }
10028
10029            drop(snapshot);
10030            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10031                s.select(selections)
10032            });
10033
10034            let selections = this.selections.all::<Point>(cx);
10035            let selections_on_single_row = selections.windows(2).all(|selections| {
10036                selections[0].start.row == selections[1].start.row
10037                    && selections[0].end.row == selections[1].end.row
10038                    && selections[0].start.row == selections[0].end.row
10039            });
10040            let selections_selecting = selections
10041                .iter()
10042                .any(|selection| selection.start != selection.end);
10043            let advance_downwards = action.advance_downwards
10044                && selections_on_single_row
10045                && !selections_selecting
10046                && !matches!(this.mode, EditorMode::SingleLine { .. });
10047
10048            if advance_downwards {
10049                let snapshot = this.buffer.read(cx).snapshot(cx);
10050
10051                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10052                    s.move_cursors_with(|display_snapshot, display_point, _| {
10053                        let mut point = display_point.to_point(display_snapshot);
10054                        point.row += 1;
10055                        point = snapshot.clip_point(point, Bias::Left);
10056                        let display_point = point.to_display_point(display_snapshot);
10057                        let goal = SelectionGoal::HorizontalPosition(
10058                            display_snapshot
10059                                .x_for_display_point(display_point, text_layout_details)
10060                                .into(),
10061                        );
10062                        (display_point, goal)
10063                    })
10064                });
10065            }
10066        });
10067    }
10068
10069    pub fn select_enclosing_symbol(
10070        &mut self,
10071        _: &SelectEnclosingSymbol,
10072        window: &mut Window,
10073        cx: &mut Context<Self>,
10074    ) {
10075        let buffer = self.buffer.read(cx).snapshot(cx);
10076        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10077
10078        fn update_selection(
10079            selection: &Selection<usize>,
10080            buffer_snap: &MultiBufferSnapshot,
10081        ) -> Option<Selection<usize>> {
10082            let cursor = selection.head();
10083            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10084            for symbol in symbols.iter().rev() {
10085                let start = symbol.range.start.to_offset(buffer_snap);
10086                let end = symbol.range.end.to_offset(buffer_snap);
10087                let new_range = start..end;
10088                if start < selection.start || end > selection.end {
10089                    return Some(Selection {
10090                        id: selection.id,
10091                        start: new_range.start,
10092                        end: new_range.end,
10093                        goal: SelectionGoal::None,
10094                        reversed: selection.reversed,
10095                    });
10096                }
10097            }
10098            None
10099        }
10100
10101        let mut selected_larger_symbol = false;
10102        let new_selections = old_selections
10103            .iter()
10104            .map(|selection| match update_selection(selection, &buffer) {
10105                Some(new_selection) => {
10106                    if new_selection.range() != selection.range() {
10107                        selected_larger_symbol = true;
10108                    }
10109                    new_selection
10110                }
10111                None => selection.clone(),
10112            })
10113            .collect::<Vec<_>>();
10114
10115        if selected_larger_symbol {
10116            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10117                s.select(new_selections);
10118            });
10119        }
10120    }
10121
10122    pub fn select_larger_syntax_node(
10123        &mut self,
10124        _: &SelectLargerSyntaxNode,
10125        window: &mut Window,
10126        cx: &mut Context<Self>,
10127    ) {
10128        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10129        let buffer = self.buffer.read(cx).snapshot(cx);
10130        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10131
10132        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10133        let mut selected_larger_node = false;
10134        let new_selections = old_selections
10135            .iter()
10136            .map(|selection| {
10137                let old_range = selection.start..selection.end;
10138                let mut new_range = old_range.clone();
10139                let mut new_node = None;
10140                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10141                {
10142                    new_node = Some(node);
10143                    new_range = containing_range;
10144                    if !display_map.intersects_fold(new_range.start)
10145                        && !display_map.intersects_fold(new_range.end)
10146                    {
10147                        break;
10148                    }
10149                }
10150
10151                if let Some(node) = new_node {
10152                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10153                    // nodes. Parent and grandparent are also logged because this operation will not
10154                    // visit nodes that have the same range as their parent.
10155                    log::info!("Node: {node:?}");
10156                    let parent = node.parent();
10157                    log::info!("Parent: {parent:?}");
10158                    let grandparent = parent.and_then(|x| x.parent());
10159                    log::info!("Grandparent: {grandparent:?}");
10160                }
10161
10162                selected_larger_node |= new_range != old_range;
10163                Selection {
10164                    id: selection.id,
10165                    start: new_range.start,
10166                    end: new_range.end,
10167                    goal: SelectionGoal::None,
10168                    reversed: selection.reversed,
10169                }
10170            })
10171            .collect::<Vec<_>>();
10172
10173        if selected_larger_node {
10174            stack.push(old_selections);
10175            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10176                s.select(new_selections);
10177            });
10178        }
10179        self.select_larger_syntax_node_stack = stack;
10180    }
10181
10182    pub fn select_smaller_syntax_node(
10183        &mut self,
10184        _: &SelectSmallerSyntaxNode,
10185        window: &mut Window,
10186        cx: &mut Context<Self>,
10187    ) {
10188        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10189        if let Some(selections) = stack.pop() {
10190            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10191                s.select(selections.to_vec());
10192            });
10193        }
10194        self.select_larger_syntax_node_stack = stack;
10195    }
10196
10197    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10198        if !EditorSettings::get_global(cx).gutter.runnables {
10199            self.clear_tasks();
10200            return Task::ready(());
10201        }
10202        let project = self.project.as_ref().map(Entity::downgrade);
10203        cx.spawn_in(window, |this, mut cx| async move {
10204            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10205            let Some(project) = project.and_then(|p| p.upgrade()) else {
10206                return;
10207            };
10208            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10209                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10210            }) else {
10211                return;
10212            };
10213
10214            let hide_runnables = project
10215                .update(&mut cx, |project, cx| {
10216                    // Do not display any test indicators in non-dev server remote projects.
10217                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10218                })
10219                .unwrap_or(true);
10220            if hide_runnables {
10221                return;
10222            }
10223            let new_rows =
10224                cx.background_spawn({
10225                    let snapshot = display_snapshot.clone();
10226                    async move {
10227                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10228                    }
10229                })
10230                    .await;
10231
10232            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10233            this.update(&mut cx, |this, _| {
10234                this.clear_tasks();
10235                for (key, value) in rows {
10236                    this.insert_tasks(key, value);
10237                }
10238            })
10239            .ok();
10240        })
10241    }
10242    fn fetch_runnable_ranges(
10243        snapshot: &DisplaySnapshot,
10244        range: Range<Anchor>,
10245    ) -> Vec<language::RunnableRange> {
10246        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10247    }
10248
10249    fn runnable_rows(
10250        project: Entity<Project>,
10251        snapshot: DisplaySnapshot,
10252        runnable_ranges: Vec<RunnableRange>,
10253        mut cx: AsyncWindowContext,
10254    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10255        runnable_ranges
10256            .into_iter()
10257            .filter_map(|mut runnable| {
10258                let tasks = cx
10259                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10260                    .ok()?;
10261                if tasks.is_empty() {
10262                    return None;
10263                }
10264
10265                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10266
10267                let row = snapshot
10268                    .buffer_snapshot
10269                    .buffer_line_for_row(MultiBufferRow(point.row))?
10270                    .1
10271                    .start
10272                    .row;
10273
10274                let context_range =
10275                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10276                Some((
10277                    (runnable.buffer_id, row),
10278                    RunnableTasks {
10279                        templates: tasks,
10280                        offset: MultiBufferOffset(runnable.run_range.start),
10281                        context_range,
10282                        column: point.column,
10283                        extra_variables: runnable.extra_captures,
10284                    },
10285                ))
10286            })
10287            .collect()
10288    }
10289
10290    fn templates_with_tags(
10291        project: &Entity<Project>,
10292        runnable: &mut Runnable,
10293        cx: &mut App,
10294    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10295        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10296            let (worktree_id, file) = project
10297                .buffer_for_id(runnable.buffer, cx)
10298                .and_then(|buffer| buffer.read(cx).file())
10299                .map(|file| (file.worktree_id(cx), file.clone()))
10300                .unzip();
10301
10302            (
10303                project.task_store().read(cx).task_inventory().cloned(),
10304                worktree_id,
10305                file,
10306            )
10307        });
10308
10309        let tags = mem::take(&mut runnable.tags);
10310        let mut tags: Vec<_> = tags
10311            .into_iter()
10312            .flat_map(|tag| {
10313                let tag = tag.0.clone();
10314                inventory
10315                    .as_ref()
10316                    .into_iter()
10317                    .flat_map(|inventory| {
10318                        inventory.read(cx).list_tasks(
10319                            file.clone(),
10320                            Some(runnable.language.clone()),
10321                            worktree_id,
10322                            cx,
10323                        )
10324                    })
10325                    .filter(move |(_, template)| {
10326                        template.tags.iter().any(|source_tag| source_tag == &tag)
10327                    })
10328            })
10329            .sorted_by_key(|(kind, _)| kind.to_owned())
10330            .collect();
10331        if let Some((leading_tag_source, _)) = tags.first() {
10332            // Strongest source wins; if we have worktree tag binding, prefer that to
10333            // global and language bindings;
10334            // if we have a global binding, prefer that to language binding.
10335            let first_mismatch = tags
10336                .iter()
10337                .position(|(tag_source, _)| tag_source != leading_tag_source);
10338            if let Some(index) = first_mismatch {
10339                tags.truncate(index);
10340            }
10341        }
10342
10343        tags
10344    }
10345
10346    pub fn move_to_enclosing_bracket(
10347        &mut self,
10348        _: &MoveToEnclosingBracket,
10349        window: &mut Window,
10350        cx: &mut Context<Self>,
10351    ) {
10352        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10353            s.move_offsets_with(|snapshot, selection| {
10354                let Some(enclosing_bracket_ranges) =
10355                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10356                else {
10357                    return;
10358                };
10359
10360                let mut best_length = usize::MAX;
10361                let mut best_inside = false;
10362                let mut best_in_bracket_range = false;
10363                let mut best_destination = None;
10364                for (open, close) in enclosing_bracket_ranges {
10365                    let close = close.to_inclusive();
10366                    let length = close.end() - open.start;
10367                    let inside = selection.start >= open.end && selection.end <= *close.start();
10368                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10369                        || close.contains(&selection.head());
10370
10371                    // If best is next to a bracket and current isn't, skip
10372                    if !in_bracket_range && best_in_bracket_range {
10373                        continue;
10374                    }
10375
10376                    // Prefer smaller lengths unless best is inside and current isn't
10377                    if length > best_length && (best_inside || !inside) {
10378                        continue;
10379                    }
10380
10381                    best_length = length;
10382                    best_inside = inside;
10383                    best_in_bracket_range = in_bracket_range;
10384                    best_destination = Some(
10385                        if close.contains(&selection.start) && close.contains(&selection.end) {
10386                            if inside {
10387                                open.end
10388                            } else {
10389                                open.start
10390                            }
10391                        } else if inside {
10392                            *close.start()
10393                        } else {
10394                            *close.end()
10395                        },
10396                    );
10397                }
10398
10399                if let Some(destination) = best_destination {
10400                    selection.collapse_to(destination, SelectionGoal::None);
10401                }
10402            })
10403        });
10404    }
10405
10406    pub fn undo_selection(
10407        &mut self,
10408        _: &UndoSelection,
10409        window: &mut Window,
10410        cx: &mut Context<Self>,
10411    ) {
10412        self.end_selection(window, cx);
10413        self.selection_history.mode = SelectionHistoryMode::Undoing;
10414        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10415            self.change_selections(None, window, cx, |s| {
10416                s.select_anchors(entry.selections.to_vec())
10417            });
10418            self.select_next_state = entry.select_next_state;
10419            self.select_prev_state = entry.select_prev_state;
10420            self.add_selections_state = entry.add_selections_state;
10421            self.request_autoscroll(Autoscroll::newest(), cx);
10422        }
10423        self.selection_history.mode = SelectionHistoryMode::Normal;
10424    }
10425
10426    pub fn redo_selection(
10427        &mut self,
10428        _: &RedoSelection,
10429        window: &mut Window,
10430        cx: &mut Context<Self>,
10431    ) {
10432        self.end_selection(window, cx);
10433        self.selection_history.mode = SelectionHistoryMode::Redoing;
10434        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10435            self.change_selections(None, window, cx, |s| {
10436                s.select_anchors(entry.selections.to_vec())
10437            });
10438            self.select_next_state = entry.select_next_state;
10439            self.select_prev_state = entry.select_prev_state;
10440            self.add_selections_state = entry.add_selections_state;
10441            self.request_autoscroll(Autoscroll::newest(), cx);
10442        }
10443        self.selection_history.mode = SelectionHistoryMode::Normal;
10444    }
10445
10446    pub fn expand_excerpts(
10447        &mut self,
10448        action: &ExpandExcerpts,
10449        _: &mut Window,
10450        cx: &mut Context<Self>,
10451    ) {
10452        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10453    }
10454
10455    pub fn expand_excerpts_down(
10456        &mut self,
10457        action: &ExpandExcerptsDown,
10458        _: &mut Window,
10459        cx: &mut Context<Self>,
10460    ) {
10461        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10462    }
10463
10464    pub fn expand_excerpts_up(
10465        &mut self,
10466        action: &ExpandExcerptsUp,
10467        _: &mut Window,
10468        cx: &mut Context<Self>,
10469    ) {
10470        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10471    }
10472
10473    pub fn expand_excerpts_for_direction(
10474        &mut self,
10475        lines: u32,
10476        direction: ExpandExcerptDirection,
10477
10478        cx: &mut Context<Self>,
10479    ) {
10480        let selections = self.selections.disjoint_anchors();
10481
10482        let lines = if lines == 0 {
10483            EditorSettings::get_global(cx).expand_excerpt_lines
10484        } else {
10485            lines
10486        };
10487
10488        self.buffer.update(cx, |buffer, cx| {
10489            let snapshot = buffer.snapshot(cx);
10490            let mut excerpt_ids = selections
10491                .iter()
10492                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10493                .collect::<Vec<_>>();
10494            excerpt_ids.sort();
10495            excerpt_ids.dedup();
10496            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10497        })
10498    }
10499
10500    pub fn expand_excerpt(
10501        &mut self,
10502        excerpt: ExcerptId,
10503        direction: ExpandExcerptDirection,
10504        cx: &mut Context<Self>,
10505    ) {
10506        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10507        self.buffer.update(cx, |buffer, cx| {
10508            buffer.expand_excerpts([excerpt], lines, direction, cx)
10509        })
10510    }
10511
10512    pub fn go_to_singleton_buffer_point(
10513        &mut self,
10514        point: Point,
10515        window: &mut Window,
10516        cx: &mut Context<Self>,
10517    ) {
10518        self.go_to_singleton_buffer_range(point..point, window, cx);
10519    }
10520
10521    pub fn go_to_singleton_buffer_range(
10522        &mut self,
10523        range: Range<Point>,
10524        window: &mut Window,
10525        cx: &mut Context<Self>,
10526    ) {
10527        let multibuffer = self.buffer().read(cx);
10528        let Some(buffer) = multibuffer.as_singleton() else {
10529            return;
10530        };
10531        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10532            return;
10533        };
10534        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10535            return;
10536        };
10537        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10538            s.select_anchor_ranges([start..end])
10539        });
10540    }
10541
10542    fn go_to_diagnostic(
10543        &mut self,
10544        _: &GoToDiagnostic,
10545        window: &mut Window,
10546        cx: &mut Context<Self>,
10547    ) {
10548        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10549    }
10550
10551    fn go_to_prev_diagnostic(
10552        &mut self,
10553        _: &GoToPrevDiagnostic,
10554        window: &mut Window,
10555        cx: &mut Context<Self>,
10556    ) {
10557        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10558    }
10559
10560    pub fn go_to_diagnostic_impl(
10561        &mut self,
10562        direction: Direction,
10563        window: &mut Window,
10564        cx: &mut Context<Self>,
10565    ) {
10566        let buffer = self.buffer.read(cx).snapshot(cx);
10567        let selection = self.selections.newest::<usize>(cx);
10568
10569        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10570        if direction == Direction::Next {
10571            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10572                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10573                    return;
10574                };
10575                self.activate_diagnostics(
10576                    buffer_id,
10577                    popover.local_diagnostic.diagnostic.group_id,
10578                    window,
10579                    cx,
10580                );
10581                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10582                    let primary_range_start = active_diagnostics.primary_range.start;
10583                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10584                        let mut new_selection = s.newest_anchor().clone();
10585                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10586                        s.select_anchors(vec![new_selection.clone()]);
10587                    });
10588                    self.refresh_inline_completion(false, true, window, cx);
10589                }
10590                return;
10591            }
10592        }
10593
10594        let active_group_id = self
10595            .active_diagnostics
10596            .as_ref()
10597            .map(|active_group| active_group.group_id);
10598        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10599            active_diagnostics
10600                .primary_range
10601                .to_offset(&buffer)
10602                .to_inclusive()
10603        });
10604        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10605            if active_primary_range.contains(&selection.head()) {
10606                *active_primary_range.start()
10607            } else {
10608                selection.head()
10609            }
10610        } else {
10611            selection.head()
10612        };
10613
10614        let snapshot = self.snapshot(window, cx);
10615        let primary_diagnostics_before = buffer
10616            .diagnostics_in_range::<usize>(0..search_start)
10617            .filter(|entry| entry.diagnostic.is_primary)
10618            .filter(|entry| entry.range.start != entry.range.end)
10619            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10620            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10621            .collect::<Vec<_>>();
10622        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10623            primary_diagnostics_before
10624                .iter()
10625                .position(|entry| entry.diagnostic.group_id == active_group_id)
10626        });
10627
10628        let primary_diagnostics_after = buffer
10629            .diagnostics_in_range::<usize>(search_start..buffer.len())
10630            .filter(|entry| entry.diagnostic.is_primary)
10631            .filter(|entry| entry.range.start != entry.range.end)
10632            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10633            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10634            .collect::<Vec<_>>();
10635        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10636            primary_diagnostics_after
10637                .iter()
10638                .enumerate()
10639                .rev()
10640                .find_map(|(i, entry)| {
10641                    if entry.diagnostic.group_id == active_group_id {
10642                        Some(i)
10643                    } else {
10644                        None
10645                    }
10646                })
10647        });
10648
10649        let next_primary_diagnostic = match direction {
10650            Direction::Prev => primary_diagnostics_before
10651                .iter()
10652                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10653                .rev()
10654                .next(),
10655            Direction::Next => primary_diagnostics_after
10656                .iter()
10657                .skip(
10658                    last_same_group_diagnostic_after
10659                        .map(|index| index + 1)
10660                        .unwrap_or(0),
10661                )
10662                .next(),
10663        };
10664
10665        // Cycle around to the start of the buffer, potentially moving back to the start of
10666        // the currently active diagnostic.
10667        let cycle_around = || match direction {
10668            Direction::Prev => primary_diagnostics_after
10669                .iter()
10670                .rev()
10671                .chain(primary_diagnostics_before.iter().rev())
10672                .next(),
10673            Direction::Next => primary_diagnostics_before
10674                .iter()
10675                .chain(primary_diagnostics_after.iter())
10676                .next(),
10677        };
10678
10679        if let Some((primary_range, group_id)) = next_primary_diagnostic
10680            .or_else(cycle_around)
10681            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10682        {
10683            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10684                return;
10685            };
10686            self.activate_diagnostics(buffer_id, group_id, window, cx);
10687            if self.active_diagnostics.is_some() {
10688                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10689                    s.select(vec![Selection {
10690                        id: selection.id,
10691                        start: primary_range.start,
10692                        end: primary_range.start,
10693                        reversed: false,
10694                        goal: SelectionGoal::None,
10695                    }]);
10696                });
10697                self.refresh_inline_completion(false, true, window, cx);
10698            }
10699        }
10700    }
10701
10702    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10703        let snapshot = self.snapshot(window, cx);
10704        let selection = self.selections.newest::<Point>(cx);
10705        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10706    }
10707
10708    fn go_to_hunk_after_position(
10709        &mut self,
10710        snapshot: &EditorSnapshot,
10711        position: Point,
10712        window: &mut Window,
10713        cx: &mut Context<Editor>,
10714    ) -> Option<MultiBufferDiffHunk> {
10715        let mut hunk = snapshot
10716            .buffer_snapshot
10717            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10718            .find(|hunk| hunk.row_range.start.0 > position.row);
10719        if hunk.is_none() {
10720            hunk = snapshot
10721                .buffer_snapshot
10722                .diff_hunks_in_range(Point::zero()..position)
10723                .find(|hunk| hunk.row_range.end.0 < position.row)
10724        }
10725        if let Some(hunk) = &hunk {
10726            let destination = Point::new(hunk.row_range.start.0, 0);
10727            self.unfold_ranges(&[destination..destination], false, false, cx);
10728            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10729                s.select_ranges(vec![destination..destination]);
10730            });
10731        }
10732
10733        hunk
10734    }
10735
10736    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10737        let snapshot = self.snapshot(window, cx);
10738        let selection = self.selections.newest::<Point>(cx);
10739        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10740    }
10741
10742    fn go_to_hunk_before_position(
10743        &mut self,
10744        snapshot: &EditorSnapshot,
10745        position: Point,
10746        window: &mut Window,
10747        cx: &mut Context<Editor>,
10748    ) -> Option<MultiBufferDiffHunk> {
10749        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10750        if hunk.is_none() {
10751            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10752        }
10753        if let Some(hunk) = &hunk {
10754            let destination = Point::new(hunk.row_range.start.0, 0);
10755            self.unfold_ranges(&[destination..destination], false, false, cx);
10756            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10757                s.select_ranges(vec![destination..destination]);
10758            });
10759        }
10760
10761        hunk
10762    }
10763
10764    pub fn go_to_definition(
10765        &mut self,
10766        _: &GoToDefinition,
10767        window: &mut Window,
10768        cx: &mut Context<Self>,
10769    ) -> Task<Result<Navigated>> {
10770        let definition =
10771            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10772        cx.spawn_in(window, |editor, mut cx| async move {
10773            if definition.await? == Navigated::Yes {
10774                return Ok(Navigated::Yes);
10775            }
10776            match editor.update_in(&mut cx, |editor, window, cx| {
10777                editor.find_all_references(&FindAllReferences, window, cx)
10778            })? {
10779                Some(references) => references.await,
10780                None => Ok(Navigated::No),
10781            }
10782        })
10783    }
10784
10785    pub fn go_to_declaration(
10786        &mut self,
10787        _: &GoToDeclaration,
10788        window: &mut Window,
10789        cx: &mut Context<Self>,
10790    ) -> Task<Result<Navigated>> {
10791        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10792    }
10793
10794    pub fn go_to_declaration_split(
10795        &mut self,
10796        _: &GoToDeclaration,
10797        window: &mut Window,
10798        cx: &mut Context<Self>,
10799    ) -> Task<Result<Navigated>> {
10800        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10801    }
10802
10803    pub fn go_to_implementation(
10804        &mut self,
10805        _: &GoToImplementation,
10806        window: &mut Window,
10807        cx: &mut Context<Self>,
10808    ) -> Task<Result<Navigated>> {
10809        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10810    }
10811
10812    pub fn go_to_implementation_split(
10813        &mut self,
10814        _: &GoToImplementationSplit,
10815        window: &mut Window,
10816        cx: &mut Context<Self>,
10817    ) -> Task<Result<Navigated>> {
10818        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10819    }
10820
10821    pub fn go_to_type_definition(
10822        &mut self,
10823        _: &GoToTypeDefinition,
10824        window: &mut Window,
10825        cx: &mut Context<Self>,
10826    ) -> Task<Result<Navigated>> {
10827        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10828    }
10829
10830    pub fn go_to_definition_split(
10831        &mut self,
10832        _: &GoToDefinitionSplit,
10833        window: &mut Window,
10834        cx: &mut Context<Self>,
10835    ) -> Task<Result<Navigated>> {
10836        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10837    }
10838
10839    pub fn go_to_type_definition_split(
10840        &mut self,
10841        _: &GoToTypeDefinitionSplit,
10842        window: &mut Window,
10843        cx: &mut Context<Self>,
10844    ) -> Task<Result<Navigated>> {
10845        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10846    }
10847
10848    fn go_to_definition_of_kind(
10849        &mut self,
10850        kind: GotoDefinitionKind,
10851        split: bool,
10852        window: &mut Window,
10853        cx: &mut Context<Self>,
10854    ) -> Task<Result<Navigated>> {
10855        let Some(provider) = self.semantics_provider.clone() else {
10856            return Task::ready(Ok(Navigated::No));
10857        };
10858        let head = self.selections.newest::<usize>(cx).head();
10859        let buffer = self.buffer.read(cx);
10860        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10861            text_anchor
10862        } else {
10863            return Task::ready(Ok(Navigated::No));
10864        };
10865
10866        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10867            return Task::ready(Ok(Navigated::No));
10868        };
10869
10870        cx.spawn_in(window, |editor, mut cx| async move {
10871            let definitions = definitions.await?;
10872            let navigated = editor
10873                .update_in(&mut cx, |editor, window, cx| {
10874                    editor.navigate_to_hover_links(
10875                        Some(kind),
10876                        definitions
10877                            .into_iter()
10878                            .filter(|location| {
10879                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10880                            })
10881                            .map(HoverLink::Text)
10882                            .collect::<Vec<_>>(),
10883                        split,
10884                        window,
10885                        cx,
10886                    )
10887                })?
10888                .await?;
10889            anyhow::Ok(navigated)
10890        })
10891    }
10892
10893    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10894        let selection = self.selections.newest_anchor();
10895        let head = selection.head();
10896        let tail = selection.tail();
10897
10898        let Some((buffer, start_position)) =
10899            self.buffer.read(cx).text_anchor_for_position(head, cx)
10900        else {
10901            return;
10902        };
10903
10904        let end_position = if head != tail {
10905            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10906                return;
10907            };
10908            Some(pos)
10909        } else {
10910            None
10911        };
10912
10913        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10914            let url = if let Some(end_pos) = end_position {
10915                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10916            } else {
10917                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10918            };
10919
10920            if let Some(url) = url {
10921                editor.update(&mut cx, |_, cx| {
10922                    cx.open_url(&url);
10923                })
10924            } else {
10925                Ok(())
10926            }
10927        });
10928
10929        url_finder.detach();
10930    }
10931
10932    pub fn open_selected_filename(
10933        &mut self,
10934        _: &OpenSelectedFilename,
10935        window: &mut Window,
10936        cx: &mut Context<Self>,
10937    ) {
10938        let Some(workspace) = self.workspace() else {
10939            return;
10940        };
10941
10942        let position = self.selections.newest_anchor().head();
10943
10944        let Some((buffer, buffer_position)) =
10945            self.buffer.read(cx).text_anchor_for_position(position, cx)
10946        else {
10947            return;
10948        };
10949
10950        let project = self.project.clone();
10951
10952        cx.spawn_in(window, |_, mut cx| async move {
10953            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10954
10955            if let Some((_, path)) = result {
10956                workspace
10957                    .update_in(&mut cx, |workspace, window, cx| {
10958                        workspace.open_resolved_path(path, window, cx)
10959                    })?
10960                    .await?;
10961            }
10962            anyhow::Ok(())
10963        })
10964        .detach();
10965    }
10966
10967    pub(crate) fn navigate_to_hover_links(
10968        &mut self,
10969        kind: Option<GotoDefinitionKind>,
10970        mut definitions: Vec<HoverLink>,
10971        split: bool,
10972        window: &mut Window,
10973        cx: &mut Context<Editor>,
10974    ) -> Task<Result<Navigated>> {
10975        // If there is one definition, just open it directly
10976        if definitions.len() == 1 {
10977            let definition = definitions.pop().unwrap();
10978
10979            enum TargetTaskResult {
10980                Location(Option<Location>),
10981                AlreadyNavigated,
10982            }
10983
10984            let target_task = match definition {
10985                HoverLink::Text(link) => {
10986                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10987                }
10988                HoverLink::InlayHint(lsp_location, server_id) => {
10989                    let computation =
10990                        self.compute_target_location(lsp_location, server_id, window, cx);
10991                    cx.background_spawn(async move {
10992                        let location = computation.await?;
10993                        Ok(TargetTaskResult::Location(location))
10994                    })
10995                }
10996                HoverLink::Url(url) => {
10997                    cx.open_url(&url);
10998                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10999                }
11000                HoverLink::File(path) => {
11001                    if let Some(workspace) = self.workspace() {
11002                        cx.spawn_in(window, |_, mut cx| async move {
11003                            workspace
11004                                .update_in(&mut cx, |workspace, window, cx| {
11005                                    workspace.open_resolved_path(path, window, cx)
11006                                })?
11007                                .await
11008                                .map(|_| TargetTaskResult::AlreadyNavigated)
11009                        })
11010                    } else {
11011                        Task::ready(Ok(TargetTaskResult::Location(None)))
11012                    }
11013                }
11014            };
11015            cx.spawn_in(window, |editor, mut cx| async move {
11016                let target = match target_task.await.context("target resolution task")? {
11017                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11018                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11019                    TargetTaskResult::Location(Some(target)) => target,
11020                };
11021
11022                editor.update_in(&mut cx, |editor, window, cx| {
11023                    let Some(workspace) = editor.workspace() else {
11024                        return Navigated::No;
11025                    };
11026                    let pane = workspace.read(cx).active_pane().clone();
11027
11028                    let range = target.range.to_point(target.buffer.read(cx));
11029                    let range = editor.range_for_match(&range);
11030                    let range = collapse_multiline_range(range);
11031
11032                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11033                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11034                    } else {
11035                        window.defer(cx, move |window, cx| {
11036                            let target_editor: Entity<Self> =
11037                                workspace.update(cx, |workspace, cx| {
11038                                    let pane = if split {
11039                                        workspace.adjacent_pane(window, cx)
11040                                    } else {
11041                                        workspace.active_pane().clone()
11042                                    };
11043
11044                                    workspace.open_project_item(
11045                                        pane,
11046                                        target.buffer.clone(),
11047                                        true,
11048                                        true,
11049                                        window,
11050                                        cx,
11051                                    )
11052                                });
11053                            target_editor.update(cx, |target_editor, cx| {
11054                                // When selecting a definition in a different buffer, disable the nav history
11055                                // to avoid creating a history entry at the previous cursor location.
11056                                pane.update(cx, |pane, _| pane.disable_history());
11057                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11058                                pane.update(cx, |pane, _| pane.enable_history());
11059                            });
11060                        });
11061                    }
11062                    Navigated::Yes
11063                })
11064            })
11065        } else if !definitions.is_empty() {
11066            cx.spawn_in(window, |editor, mut cx| async move {
11067                let (title, location_tasks, workspace) = editor
11068                    .update_in(&mut cx, |editor, window, cx| {
11069                        let tab_kind = match kind {
11070                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11071                            _ => "Definitions",
11072                        };
11073                        let title = definitions
11074                            .iter()
11075                            .find_map(|definition| match definition {
11076                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11077                                    let buffer = origin.buffer.read(cx);
11078                                    format!(
11079                                        "{} for {}",
11080                                        tab_kind,
11081                                        buffer
11082                                            .text_for_range(origin.range.clone())
11083                                            .collect::<String>()
11084                                    )
11085                                }),
11086                                HoverLink::InlayHint(_, _) => None,
11087                                HoverLink::Url(_) => None,
11088                                HoverLink::File(_) => None,
11089                            })
11090                            .unwrap_or(tab_kind.to_string());
11091                        let location_tasks = definitions
11092                            .into_iter()
11093                            .map(|definition| match definition {
11094                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11095                                HoverLink::InlayHint(lsp_location, server_id) => editor
11096                                    .compute_target_location(lsp_location, server_id, window, cx),
11097                                HoverLink::Url(_) => Task::ready(Ok(None)),
11098                                HoverLink::File(_) => Task::ready(Ok(None)),
11099                            })
11100                            .collect::<Vec<_>>();
11101                        (title, location_tasks, editor.workspace().clone())
11102                    })
11103                    .context("location tasks preparation")?;
11104
11105                let locations = future::join_all(location_tasks)
11106                    .await
11107                    .into_iter()
11108                    .filter_map(|location| location.transpose())
11109                    .collect::<Result<_>>()
11110                    .context("location tasks")?;
11111
11112                let Some(workspace) = workspace else {
11113                    return Ok(Navigated::No);
11114                };
11115                let opened = workspace
11116                    .update_in(&mut cx, |workspace, window, cx| {
11117                        Self::open_locations_in_multibuffer(
11118                            workspace,
11119                            locations,
11120                            title,
11121                            split,
11122                            MultibufferSelectionMode::First,
11123                            window,
11124                            cx,
11125                        )
11126                    })
11127                    .ok();
11128
11129                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11130            })
11131        } else {
11132            Task::ready(Ok(Navigated::No))
11133        }
11134    }
11135
11136    fn compute_target_location(
11137        &self,
11138        lsp_location: lsp::Location,
11139        server_id: LanguageServerId,
11140        window: &mut Window,
11141        cx: &mut Context<Self>,
11142    ) -> Task<anyhow::Result<Option<Location>>> {
11143        let Some(project) = self.project.clone() else {
11144            return Task::ready(Ok(None));
11145        };
11146
11147        cx.spawn_in(window, move |editor, mut cx| async move {
11148            let location_task = editor.update(&mut cx, |_, cx| {
11149                project.update(cx, |project, cx| {
11150                    let language_server_name = project
11151                        .language_server_statuses(cx)
11152                        .find(|(id, _)| server_id == *id)
11153                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11154                    language_server_name.map(|language_server_name| {
11155                        project.open_local_buffer_via_lsp(
11156                            lsp_location.uri.clone(),
11157                            server_id,
11158                            language_server_name,
11159                            cx,
11160                        )
11161                    })
11162                })
11163            })?;
11164            let location = match location_task {
11165                Some(task) => Some({
11166                    let target_buffer_handle = task.await.context("open local buffer")?;
11167                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11168                        let target_start = target_buffer
11169                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11170                        let target_end = target_buffer
11171                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11172                        target_buffer.anchor_after(target_start)
11173                            ..target_buffer.anchor_before(target_end)
11174                    })?;
11175                    Location {
11176                        buffer: target_buffer_handle,
11177                        range,
11178                    }
11179                }),
11180                None => None,
11181            };
11182            Ok(location)
11183        })
11184    }
11185
11186    pub fn find_all_references(
11187        &mut self,
11188        _: &FindAllReferences,
11189        window: &mut Window,
11190        cx: &mut Context<Self>,
11191    ) -> Option<Task<Result<Navigated>>> {
11192        let selection = self.selections.newest::<usize>(cx);
11193        let multi_buffer = self.buffer.read(cx);
11194        let head = selection.head();
11195
11196        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11197        let head_anchor = multi_buffer_snapshot.anchor_at(
11198            head,
11199            if head < selection.tail() {
11200                Bias::Right
11201            } else {
11202                Bias::Left
11203            },
11204        );
11205
11206        match self
11207            .find_all_references_task_sources
11208            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11209        {
11210            Ok(_) => {
11211                log::info!(
11212                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11213                );
11214                return None;
11215            }
11216            Err(i) => {
11217                self.find_all_references_task_sources.insert(i, head_anchor);
11218            }
11219        }
11220
11221        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11222        let workspace = self.workspace()?;
11223        let project = workspace.read(cx).project().clone();
11224        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11225        Some(cx.spawn_in(window, |editor, mut cx| async move {
11226            let _cleanup = defer({
11227                let mut cx = cx.clone();
11228                move || {
11229                    let _ = editor.update(&mut cx, |editor, _| {
11230                        if let Ok(i) =
11231                            editor
11232                                .find_all_references_task_sources
11233                                .binary_search_by(|anchor| {
11234                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11235                                })
11236                        {
11237                            editor.find_all_references_task_sources.remove(i);
11238                        }
11239                    });
11240                }
11241            });
11242
11243            let locations = references.await?;
11244            if locations.is_empty() {
11245                return anyhow::Ok(Navigated::No);
11246            }
11247
11248            workspace.update_in(&mut cx, |workspace, window, cx| {
11249                let title = locations
11250                    .first()
11251                    .as_ref()
11252                    .map(|location| {
11253                        let buffer = location.buffer.read(cx);
11254                        format!(
11255                            "References to `{}`",
11256                            buffer
11257                                .text_for_range(location.range.clone())
11258                                .collect::<String>()
11259                        )
11260                    })
11261                    .unwrap();
11262                Self::open_locations_in_multibuffer(
11263                    workspace,
11264                    locations,
11265                    title,
11266                    false,
11267                    MultibufferSelectionMode::First,
11268                    window,
11269                    cx,
11270                );
11271                Navigated::Yes
11272            })
11273        }))
11274    }
11275
11276    /// Opens a multibuffer with the given project locations in it
11277    pub fn open_locations_in_multibuffer(
11278        workspace: &mut Workspace,
11279        mut locations: Vec<Location>,
11280        title: String,
11281        split: bool,
11282        multibuffer_selection_mode: MultibufferSelectionMode,
11283        window: &mut Window,
11284        cx: &mut Context<Workspace>,
11285    ) {
11286        // If there are multiple definitions, open them in a multibuffer
11287        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11288        let mut locations = locations.into_iter().peekable();
11289        let mut ranges = Vec::new();
11290        let capability = workspace.project().read(cx).capability();
11291
11292        let excerpt_buffer = cx.new(|cx| {
11293            let mut multibuffer = MultiBuffer::new(capability);
11294            while let Some(location) = locations.next() {
11295                let buffer = location.buffer.read(cx);
11296                let mut ranges_for_buffer = Vec::new();
11297                let range = location.range.to_offset(buffer);
11298                ranges_for_buffer.push(range.clone());
11299
11300                while let Some(next_location) = locations.peek() {
11301                    if next_location.buffer == location.buffer {
11302                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11303                        locations.next();
11304                    } else {
11305                        break;
11306                    }
11307                }
11308
11309                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11310                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11311                    location.buffer.clone(),
11312                    ranges_for_buffer,
11313                    DEFAULT_MULTIBUFFER_CONTEXT,
11314                    cx,
11315                ))
11316            }
11317
11318            multibuffer.with_title(title)
11319        });
11320
11321        let editor = cx.new(|cx| {
11322            Editor::for_multibuffer(
11323                excerpt_buffer,
11324                Some(workspace.project().clone()),
11325                true,
11326                window,
11327                cx,
11328            )
11329        });
11330        editor.update(cx, |editor, cx| {
11331            match multibuffer_selection_mode {
11332                MultibufferSelectionMode::First => {
11333                    if let Some(first_range) = ranges.first() {
11334                        editor.change_selections(None, window, cx, |selections| {
11335                            selections.clear_disjoint();
11336                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11337                        });
11338                    }
11339                    editor.highlight_background::<Self>(
11340                        &ranges,
11341                        |theme| theme.editor_highlighted_line_background,
11342                        cx,
11343                    );
11344                }
11345                MultibufferSelectionMode::All => {
11346                    editor.change_selections(None, window, cx, |selections| {
11347                        selections.clear_disjoint();
11348                        selections.select_anchor_ranges(ranges);
11349                    });
11350                }
11351            }
11352            editor.register_buffers_with_language_servers(cx);
11353        });
11354
11355        let item = Box::new(editor);
11356        let item_id = item.item_id();
11357
11358        if split {
11359            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11360        } else {
11361            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11362                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11363                    pane.close_current_preview_item(window, cx)
11364                } else {
11365                    None
11366                }
11367            });
11368            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11369        }
11370        workspace.active_pane().update(cx, |pane, cx| {
11371            pane.set_preview_item_id(Some(item_id), cx);
11372        });
11373    }
11374
11375    pub fn rename(
11376        &mut self,
11377        _: &Rename,
11378        window: &mut Window,
11379        cx: &mut Context<Self>,
11380    ) -> Option<Task<Result<()>>> {
11381        use language::ToOffset as _;
11382
11383        let provider = self.semantics_provider.clone()?;
11384        let selection = self.selections.newest_anchor().clone();
11385        let (cursor_buffer, cursor_buffer_position) = self
11386            .buffer
11387            .read(cx)
11388            .text_anchor_for_position(selection.head(), cx)?;
11389        let (tail_buffer, cursor_buffer_position_end) = self
11390            .buffer
11391            .read(cx)
11392            .text_anchor_for_position(selection.tail(), cx)?;
11393        if tail_buffer != cursor_buffer {
11394            return None;
11395        }
11396
11397        let snapshot = cursor_buffer.read(cx).snapshot();
11398        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11399        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11400        let prepare_rename = provider
11401            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11402            .unwrap_or_else(|| Task::ready(Ok(None)));
11403        drop(snapshot);
11404
11405        Some(cx.spawn_in(window, |this, mut cx| async move {
11406            let rename_range = if let Some(range) = prepare_rename.await? {
11407                Some(range)
11408            } else {
11409                this.update(&mut cx, |this, cx| {
11410                    let buffer = this.buffer.read(cx).snapshot(cx);
11411                    let mut buffer_highlights = this
11412                        .document_highlights_for_position(selection.head(), &buffer)
11413                        .filter(|highlight| {
11414                            highlight.start.excerpt_id == selection.head().excerpt_id
11415                                && highlight.end.excerpt_id == selection.head().excerpt_id
11416                        });
11417                    buffer_highlights
11418                        .next()
11419                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11420                })?
11421            };
11422            if let Some(rename_range) = rename_range {
11423                this.update_in(&mut cx, |this, window, cx| {
11424                    let snapshot = cursor_buffer.read(cx).snapshot();
11425                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11426                    let cursor_offset_in_rename_range =
11427                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11428                    let cursor_offset_in_rename_range_end =
11429                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11430
11431                    this.take_rename(false, window, cx);
11432                    let buffer = this.buffer.read(cx).read(cx);
11433                    let cursor_offset = selection.head().to_offset(&buffer);
11434                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11435                    let rename_end = rename_start + rename_buffer_range.len();
11436                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11437                    let mut old_highlight_id = None;
11438                    let old_name: Arc<str> = buffer
11439                        .chunks(rename_start..rename_end, true)
11440                        .map(|chunk| {
11441                            if old_highlight_id.is_none() {
11442                                old_highlight_id = chunk.syntax_highlight_id;
11443                            }
11444                            chunk.text
11445                        })
11446                        .collect::<String>()
11447                        .into();
11448
11449                    drop(buffer);
11450
11451                    // Position the selection in the rename editor so that it matches the current selection.
11452                    this.show_local_selections = false;
11453                    let rename_editor = cx.new(|cx| {
11454                        let mut editor = Editor::single_line(window, cx);
11455                        editor.buffer.update(cx, |buffer, cx| {
11456                            buffer.edit([(0..0, old_name.clone())], None, cx)
11457                        });
11458                        let rename_selection_range = match cursor_offset_in_rename_range
11459                            .cmp(&cursor_offset_in_rename_range_end)
11460                        {
11461                            Ordering::Equal => {
11462                                editor.select_all(&SelectAll, window, cx);
11463                                return editor;
11464                            }
11465                            Ordering::Less => {
11466                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11467                            }
11468                            Ordering::Greater => {
11469                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11470                            }
11471                        };
11472                        if rename_selection_range.end > old_name.len() {
11473                            editor.select_all(&SelectAll, window, cx);
11474                        } else {
11475                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11476                                s.select_ranges([rename_selection_range]);
11477                            });
11478                        }
11479                        editor
11480                    });
11481                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11482                        if e == &EditorEvent::Focused {
11483                            cx.emit(EditorEvent::FocusedIn)
11484                        }
11485                    })
11486                    .detach();
11487
11488                    let write_highlights =
11489                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11490                    let read_highlights =
11491                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11492                    let ranges = write_highlights
11493                        .iter()
11494                        .flat_map(|(_, ranges)| ranges.iter())
11495                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11496                        .cloned()
11497                        .collect();
11498
11499                    this.highlight_text::<Rename>(
11500                        ranges,
11501                        HighlightStyle {
11502                            fade_out: Some(0.6),
11503                            ..Default::default()
11504                        },
11505                        cx,
11506                    );
11507                    let rename_focus_handle = rename_editor.focus_handle(cx);
11508                    window.focus(&rename_focus_handle);
11509                    let block_id = this.insert_blocks(
11510                        [BlockProperties {
11511                            style: BlockStyle::Flex,
11512                            placement: BlockPlacement::Below(range.start),
11513                            height: 1,
11514                            render: Arc::new({
11515                                let rename_editor = rename_editor.clone();
11516                                move |cx: &mut BlockContext| {
11517                                    let mut text_style = cx.editor_style.text.clone();
11518                                    if let Some(highlight_style) = old_highlight_id
11519                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11520                                    {
11521                                        text_style = text_style.highlight(highlight_style);
11522                                    }
11523                                    div()
11524                                        .block_mouse_down()
11525                                        .pl(cx.anchor_x)
11526                                        .child(EditorElement::new(
11527                                            &rename_editor,
11528                                            EditorStyle {
11529                                                background: cx.theme().system().transparent,
11530                                                local_player: cx.editor_style.local_player,
11531                                                text: text_style,
11532                                                scrollbar_width: cx.editor_style.scrollbar_width,
11533                                                syntax: cx.editor_style.syntax.clone(),
11534                                                status: cx.editor_style.status.clone(),
11535                                                inlay_hints_style: HighlightStyle {
11536                                                    font_weight: Some(FontWeight::BOLD),
11537                                                    ..make_inlay_hints_style(cx.app)
11538                                                },
11539                                                inline_completion_styles: make_suggestion_styles(
11540                                                    cx.app,
11541                                                ),
11542                                                ..EditorStyle::default()
11543                                            },
11544                                        ))
11545                                        .into_any_element()
11546                                }
11547                            }),
11548                            priority: 0,
11549                        }],
11550                        Some(Autoscroll::fit()),
11551                        cx,
11552                    )[0];
11553                    this.pending_rename = Some(RenameState {
11554                        range,
11555                        old_name,
11556                        editor: rename_editor,
11557                        block_id,
11558                    });
11559                })?;
11560            }
11561
11562            Ok(())
11563        }))
11564    }
11565
11566    pub fn confirm_rename(
11567        &mut self,
11568        _: &ConfirmRename,
11569        window: &mut Window,
11570        cx: &mut Context<Self>,
11571    ) -> Option<Task<Result<()>>> {
11572        let rename = self.take_rename(false, window, cx)?;
11573        let workspace = self.workspace()?.downgrade();
11574        let (buffer, start) = self
11575            .buffer
11576            .read(cx)
11577            .text_anchor_for_position(rename.range.start, cx)?;
11578        let (end_buffer, _) = self
11579            .buffer
11580            .read(cx)
11581            .text_anchor_for_position(rename.range.end, cx)?;
11582        if buffer != end_buffer {
11583            return None;
11584        }
11585
11586        let old_name = rename.old_name;
11587        let new_name = rename.editor.read(cx).text(cx);
11588
11589        let rename = self.semantics_provider.as_ref()?.perform_rename(
11590            &buffer,
11591            start,
11592            new_name.clone(),
11593            cx,
11594        )?;
11595
11596        Some(cx.spawn_in(window, |editor, mut cx| async move {
11597            let project_transaction = rename.await?;
11598            Self::open_project_transaction(
11599                &editor,
11600                workspace,
11601                project_transaction,
11602                format!("Rename: {}{}", old_name, new_name),
11603                cx.clone(),
11604            )
11605            .await?;
11606
11607            editor.update(&mut cx, |editor, cx| {
11608                editor.refresh_document_highlights(cx);
11609            })?;
11610            Ok(())
11611        }))
11612    }
11613
11614    fn take_rename(
11615        &mut self,
11616        moving_cursor: bool,
11617        window: &mut Window,
11618        cx: &mut Context<Self>,
11619    ) -> Option<RenameState> {
11620        let rename = self.pending_rename.take()?;
11621        if rename.editor.focus_handle(cx).is_focused(window) {
11622            window.focus(&self.focus_handle);
11623        }
11624
11625        self.remove_blocks(
11626            [rename.block_id].into_iter().collect(),
11627            Some(Autoscroll::fit()),
11628            cx,
11629        );
11630        self.clear_highlights::<Rename>(cx);
11631        self.show_local_selections = true;
11632
11633        if moving_cursor {
11634            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11635                editor.selections.newest::<usize>(cx).head()
11636            });
11637
11638            // Update the selection to match the position of the selection inside
11639            // the rename editor.
11640            let snapshot = self.buffer.read(cx).read(cx);
11641            let rename_range = rename.range.to_offset(&snapshot);
11642            let cursor_in_editor = snapshot
11643                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11644                .min(rename_range.end);
11645            drop(snapshot);
11646
11647            self.change_selections(None, window, cx, |s| {
11648                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11649            });
11650        } else {
11651            self.refresh_document_highlights(cx);
11652        }
11653
11654        Some(rename)
11655    }
11656
11657    pub fn pending_rename(&self) -> Option<&RenameState> {
11658        self.pending_rename.as_ref()
11659    }
11660
11661    fn format(
11662        &mut self,
11663        _: &Format,
11664        window: &mut Window,
11665        cx: &mut Context<Self>,
11666    ) -> Option<Task<Result<()>>> {
11667        let project = match &self.project {
11668            Some(project) => project.clone(),
11669            None => return None,
11670        };
11671
11672        Some(self.perform_format(
11673            project,
11674            FormatTrigger::Manual,
11675            FormatTarget::Buffers,
11676            window,
11677            cx,
11678        ))
11679    }
11680
11681    fn format_selections(
11682        &mut self,
11683        _: &FormatSelections,
11684        window: &mut Window,
11685        cx: &mut Context<Self>,
11686    ) -> Option<Task<Result<()>>> {
11687        let project = match &self.project {
11688            Some(project) => project.clone(),
11689            None => return None,
11690        };
11691
11692        let ranges = self
11693            .selections
11694            .all_adjusted(cx)
11695            .into_iter()
11696            .map(|selection| selection.range())
11697            .collect_vec();
11698
11699        Some(self.perform_format(
11700            project,
11701            FormatTrigger::Manual,
11702            FormatTarget::Ranges(ranges),
11703            window,
11704            cx,
11705        ))
11706    }
11707
11708    fn perform_format(
11709        &mut self,
11710        project: Entity<Project>,
11711        trigger: FormatTrigger,
11712        target: FormatTarget,
11713        window: &mut Window,
11714        cx: &mut Context<Self>,
11715    ) -> Task<Result<()>> {
11716        let buffer = self.buffer.clone();
11717        let (buffers, target) = match target {
11718            FormatTarget::Buffers => {
11719                let mut buffers = buffer.read(cx).all_buffers();
11720                if trigger == FormatTrigger::Save {
11721                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11722                }
11723                (buffers, LspFormatTarget::Buffers)
11724            }
11725            FormatTarget::Ranges(selection_ranges) => {
11726                let multi_buffer = buffer.read(cx);
11727                let snapshot = multi_buffer.read(cx);
11728                let mut buffers = HashSet::default();
11729                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11730                    BTreeMap::new();
11731                for selection_range in selection_ranges {
11732                    for (buffer, buffer_range, _) in
11733                        snapshot.range_to_buffer_ranges(selection_range)
11734                    {
11735                        let buffer_id = buffer.remote_id();
11736                        let start = buffer.anchor_before(buffer_range.start);
11737                        let end = buffer.anchor_after(buffer_range.end);
11738                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11739                        buffer_id_to_ranges
11740                            .entry(buffer_id)
11741                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11742                            .or_insert_with(|| vec![start..end]);
11743                    }
11744                }
11745                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11746            }
11747        };
11748
11749        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11750        let format = project.update(cx, |project, cx| {
11751            project.format(buffers, target, true, trigger, cx)
11752        });
11753
11754        cx.spawn_in(window, |_, mut cx| async move {
11755            let transaction = futures::select_biased! {
11756                () = timeout => {
11757                    log::warn!("timed out waiting for formatting");
11758                    None
11759                }
11760                transaction = format.log_err().fuse() => transaction,
11761            };
11762
11763            buffer
11764                .update(&mut cx, |buffer, cx| {
11765                    if let Some(transaction) = transaction {
11766                        if !buffer.is_singleton() {
11767                            buffer.push_transaction(&transaction.0, cx);
11768                        }
11769                    }
11770
11771                    cx.notify();
11772                })
11773                .ok();
11774
11775            Ok(())
11776        })
11777    }
11778
11779    fn restart_language_server(
11780        &mut self,
11781        _: &RestartLanguageServer,
11782        _: &mut Window,
11783        cx: &mut Context<Self>,
11784    ) {
11785        if let Some(project) = self.project.clone() {
11786            self.buffer.update(cx, |multi_buffer, cx| {
11787                project.update(cx, |project, cx| {
11788                    project.restart_language_servers_for_buffers(
11789                        multi_buffer.all_buffers().into_iter().collect(),
11790                        cx,
11791                    );
11792                });
11793            })
11794        }
11795    }
11796
11797    fn cancel_language_server_work(
11798        workspace: &mut Workspace,
11799        _: &actions::CancelLanguageServerWork,
11800        _: &mut Window,
11801        cx: &mut Context<Workspace>,
11802    ) {
11803        let project = workspace.project();
11804        let buffers = workspace
11805            .active_item(cx)
11806            .and_then(|item| item.act_as::<Editor>(cx))
11807            .map_or(HashSet::default(), |editor| {
11808                editor.read(cx).buffer.read(cx).all_buffers()
11809            });
11810        project.update(cx, |project, cx| {
11811            project.cancel_language_server_work_for_buffers(buffers, cx);
11812        });
11813    }
11814
11815    fn show_character_palette(
11816        &mut self,
11817        _: &ShowCharacterPalette,
11818        window: &mut Window,
11819        _: &mut Context<Self>,
11820    ) {
11821        window.show_character_palette();
11822    }
11823
11824    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11825        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11826            let buffer = self.buffer.read(cx).snapshot(cx);
11827            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11828            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11829            let is_valid = buffer
11830                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11831                .any(|entry| {
11832                    entry.diagnostic.is_primary
11833                        && !entry.range.is_empty()
11834                        && entry.range.start == primary_range_start
11835                        && entry.diagnostic.message == active_diagnostics.primary_message
11836                });
11837
11838            if is_valid != active_diagnostics.is_valid {
11839                active_diagnostics.is_valid = is_valid;
11840                let mut new_styles = HashMap::default();
11841                for (block_id, diagnostic) in &active_diagnostics.blocks {
11842                    new_styles.insert(
11843                        *block_id,
11844                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11845                    );
11846                }
11847                self.display_map.update(cx, |display_map, _cx| {
11848                    display_map.replace_blocks(new_styles)
11849                });
11850            }
11851        }
11852    }
11853
11854    fn activate_diagnostics(
11855        &mut self,
11856        buffer_id: BufferId,
11857        group_id: usize,
11858        window: &mut Window,
11859        cx: &mut Context<Self>,
11860    ) {
11861        self.dismiss_diagnostics(cx);
11862        let snapshot = self.snapshot(window, cx);
11863        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11864            let buffer = self.buffer.read(cx).snapshot(cx);
11865
11866            let mut primary_range = None;
11867            let mut primary_message = None;
11868            let diagnostic_group = buffer
11869                .diagnostic_group(buffer_id, group_id)
11870                .filter_map(|entry| {
11871                    let start = entry.range.start;
11872                    let end = entry.range.end;
11873                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11874                        && (start.row == end.row
11875                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11876                    {
11877                        return None;
11878                    }
11879                    if entry.diagnostic.is_primary {
11880                        primary_range = Some(entry.range.clone());
11881                        primary_message = Some(entry.diagnostic.message.clone());
11882                    }
11883                    Some(entry)
11884                })
11885                .collect::<Vec<_>>();
11886            let primary_range = primary_range?;
11887            let primary_message = primary_message?;
11888
11889            let blocks = display_map
11890                .insert_blocks(
11891                    diagnostic_group.iter().map(|entry| {
11892                        let diagnostic = entry.diagnostic.clone();
11893                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11894                        BlockProperties {
11895                            style: BlockStyle::Fixed,
11896                            placement: BlockPlacement::Below(
11897                                buffer.anchor_after(entry.range.start),
11898                            ),
11899                            height: message_height,
11900                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11901                            priority: 0,
11902                        }
11903                    }),
11904                    cx,
11905                )
11906                .into_iter()
11907                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11908                .collect();
11909
11910            Some(ActiveDiagnosticGroup {
11911                primary_range: buffer.anchor_before(primary_range.start)
11912                    ..buffer.anchor_after(primary_range.end),
11913                primary_message,
11914                group_id,
11915                blocks,
11916                is_valid: true,
11917            })
11918        });
11919    }
11920
11921    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11922        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11923            self.display_map.update(cx, |display_map, cx| {
11924                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11925            });
11926            cx.notify();
11927        }
11928    }
11929
11930    pub fn set_selections_from_remote(
11931        &mut self,
11932        selections: Vec<Selection<Anchor>>,
11933        pending_selection: Option<Selection<Anchor>>,
11934        window: &mut Window,
11935        cx: &mut Context<Self>,
11936    ) {
11937        let old_cursor_position = self.selections.newest_anchor().head();
11938        self.selections.change_with(cx, |s| {
11939            s.select_anchors(selections);
11940            if let Some(pending_selection) = pending_selection {
11941                s.set_pending(pending_selection, SelectMode::Character);
11942            } else {
11943                s.clear_pending();
11944            }
11945        });
11946        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11947    }
11948
11949    fn push_to_selection_history(&mut self) {
11950        self.selection_history.push(SelectionHistoryEntry {
11951            selections: self.selections.disjoint_anchors(),
11952            select_next_state: self.select_next_state.clone(),
11953            select_prev_state: self.select_prev_state.clone(),
11954            add_selections_state: self.add_selections_state.clone(),
11955        });
11956    }
11957
11958    pub fn transact(
11959        &mut self,
11960        window: &mut Window,
11961        cx: &mut Context<Self>,
11962        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11963    ) -> Option<TransactionId> {
11964        self.start_transaction_at(Instant::now(), window, cx);
11965        update(self, window, cx);
11966        self.end_transaction_at(Instant::now(), cx)
11967    }
11968
11969    pub fn start_transaction_at(
11970        &mut self,
11971        now: Instant,
11972        window: &mut Window,
11973        cx: &mut Context<Self>,
11974    ) {
11975        self.end_selection(window, cx);
11976        if let Some(tx_id) = self
11977            .buffer
11978            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11979        {
11980            self.selection_history
11981                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11982            cx.emit(EditorEvent::TransactionBegun {
11983                transaction_id: tx_id,
11984            })
11985        }
11986    }
11987
11988    pub fn end_transaction_at(
11989        &mut self,
11990        now: Instant,
11991        cx: &mut Context<Self>,
11992    ) -> Option<TransactionId> {
11993        if let Some(transaction_id) = self
11994            .buffer
11995            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11996        {
11997            if let Some((_, end_selections)) =
11998                self.selection_history.transaction_mut(transaction_id)
11999            {
12000                *end_selections = Some(self.selections.disjoint_anchors());
12001            } else {
12002                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12003            }
12004
12005            cx.emit(EditorEvent::Edited { transaction_id });
12006            Some(transaction_id)
12007        } else {
12008            None
12009        }
12010    }
12011
12012    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12013        if self.selection_mark_mode {
12014            self.change_selections(None, window, cx, |s| {
12015                s.move_with(|_, sel| {
12016                    sel.collapse_to(sel.head(), SelectionGoal::None);
12017                });
12018            })
12019        }
12020        self.selection_mark_mode = true;
12021        cx.notify();
12022    }
12023
12024    pub fn swap_selection_ends(
12025        &mut self,
12026        _: &actions::SwapSelectionEnds,
12027        window: &mut Window,
12028        cx: &mut Context<Self>,
12029    ) {
12030        self.change_selections(None, window, cx, |s| {
12031            s.move_with(|_, sel| {
12032                if sel.start != sel.end {
12033                    sel.reversed = !sel.reversed
12034                }
12035            });
12036        });
12037        self.request_autoscroll(Autoscroll::newest(), cx);
12038        cx.notify();
12039    }
12040
12041    pub fn toggle_fold(
12042        &mut self,
12043        _: &actions::ToggleFold,
12044        window: &mut Window,
12045        cx: &mut Context<Self>,
12046    ) {
12047        if self.is_singleton(cx) {
12048            let selection = self.selections.newest::<Point>(cx);
12049
12050            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12051            let range = if selection.is_empty() {
12052                let point = selection.head().to_display_point(&display_map);
12053                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12054                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12055                    .to_point(&display_map);
12056                start..end
12057            } else {
12058                selection.range()
12059            };
12060            if display_map.folds_in_range(range).next().is_some() {
12061                self.unfold_lines(&Default::default(), window, cx)
12062            } else {
12063                self.fold(&Default::default(), window, cx)
12064            }
12065        } else {
12066            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12067            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12068                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12069                .map(|(snapshot, _, _)| snapshot.remote_id())
12070                .collect();
12071
12072            for buffer_id in buffer_ids {
12073                if self.is_buffer_folded(buffer_id, cx) {
12074                    self.unfold_buffer(buffer_id, cx);
12075                } else {
12076                    self.fold_buffer(buffer_id, cx);
12077                }
12078            }
12079        }
12080    }
12081
12082    pub fn toggle_fold_recursive(
12083        &mut self,
12084        _: &actions::ToggleFoldRecursive,
12085        window: &mut Window,
12086        cx: &mut Context<Self>,
12087    ) {
12088        let selection = self.selections.newest::<Point>(cx);
12089
12090        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12091        let range = if selection.is_empty() {
12092            let point = selection.head().to_display_point(&display_map);
12093            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12094            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12095                .to_point(&display_map);
12096            start..end
12097        } else {
12098            selection.range()
12099        };
12100        if display_map.folds_in_range(range).next().is_some() {
12101            self.unfold_recursive(&Default::default(), window, cx)
12102        } else {
12103            self.fold_recursive(&Default::default(), window, cx)
12104        }
12105    }
12106
12107    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12108        if self.is_singleton(cx) {
12109            let mut to_fold = Vec::new();
12110            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12111            let selections = self.selections.all_adjusted(cx);
12112
12113            for selection in selections {
12114                let range = selection.range().sorted();
12115                let buffer_start_row = range.start.row;
12116
12117                if range.start.row != range.end.row {
12118                    let mut found = false;
12119                    let mut row = range.start.row;
12120                    while row <= range.end.row {
12121                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12122                        {
12123                            found = true;
12124                            row = crease.range().end.row + 1;
12125                            to_fold.push(crease);
12126                        } else {
12127                            row += 1
12128                        }
12129                    }
12130                    if found {
12131                        continue;
12132                    }
12133                }
12134
12135                for row in (0..=range.start.row).rev() {
12136                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12137                        if crease.range().end.row >= buffer_start_row {
12138                            to_fold.push(crease);
12139                            if row <= range.start.row {
12140                                break;
12141                            }
12142                        }
12143                    }
12144                }
12145            }
12146
12147            self.fold_creases(to_fold, true, window, cx);
12148        } else {
12149            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12150
12151            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12152                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12153                .map(|(snapshot, _, _)| snapshot.remote_id())
12154                .collect();
12155            for buffer_id in buffer_ids {
12156                self.fold_buffer(buffer_id, cx);
12157            }
12158        }
12159    }
12160
12161    fn fold_at_level(
12162        &mut self,
12163        fold_at: &FoldAtLevel,
12164        window: &mut Window,
12165        cx: &mut Context<Self>,
12166    ) {
12167        if !self.buffer.read(cx).is_singleton() {
12168            return;
12169        }
12170
12171        let fold_at_level = fold_at.0;
12172        let snapshot = self.buffer.read(cx).snapshot(cx);
12173        let mut to_fold = Vec::new();
12174        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12175
12176        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12177            while start_row < end_row {
12178                match self
12179                    .snapshot(window, cx)
12180                    .crease_for_buffer_row(MultiBufferRow(start_row))
12181                {
12182                    Some(crease) => {
12183                        let nested_start_row = crease.range().start.row + 1;
12184                        let nested_end_row = crease.range().end.row;
12185
12186                        if current_level < fold_at_level {
12187                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12188                        } else if current_level == fold_at_level {
12189                            to_fold.push(crease);
12190                        }
12191
12192                        start_row = nested_end_row + 1;
12193                    }
12194                    None => start_row += 1,
12195                }
12196            }
12197        }
12198
12199        self.fold_creases(to_fold, true, window, cx);
12200    }
12201
12202    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12203        if self.buffer.read(cx).is_singleton() {
12204            let mut fold_ranges = Vec::new();
12205            let snapshot = self.buffer.read(cx).snapshot(cx);
12206
12207            for row in 0..snapshot.max_row().0 {
12208                if let Some(foldable_range) = self
12209                    .snapshot(window, cx)
12210                    .crease_for_buffer_row(MultiBufferRow(row))
12211                {
12212                    fold_ranges.push(foldable_range);
12213                }
12214            }
12215
12216            self.fold_creases(fold_ranges, true, window, cx);
12217        } else {
12218            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12219                editor
12220                    .update_in(&mut cx, |editor, _, cx| {
12221                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12222                            editor.fold_buffer(buffer_id, cx);
12223                        }
12224                    })
12225                    .ok();
12226            });
12227        }
12228    }
12229
12230    pub fn fold_function_bodies(
12231        &mut self,
12232        _: &actions::FoldFunctionBodies,
12233        window: &mut Window,
12234        cx: &mut Context<Self>,
12235    ) {
12236        let snapshot = self.buffer.read(cx).snapshot(cx);
12237
12238        let ranges = snapshot
12239            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12240            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12241            .collect::<Vec<_>>();
12242
12243        let creases = ranges
12244            .into_iter()
12245            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12246            .collect();
12247
12248        self.fold_creases(creases, true, window, cx);
12249    }
12250
12251    pub fn fold_recursive(
12252        &mut self,
12253        _: &actions::FoldRecursive,
12254        window: &mut Window,
12255        cx: &mut Context<Self>,
12256    ) {
12257        let mut to_fold = Vec::new();
12258        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12259        let selections = self.selections.all_adjusted(cx);
12260
12261        for selection in selections {
12262            let range = selection.range().sorted();
12263            let buffer_start_row = range.start.row;
12264
12265            if range.start.row != range.end.row {
12266                let mut found = false;
12267                for row in range.start.row..=range.end.row {
12268                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12269                        found = true;
12270                        to_fold.push(crease);
12271                    }
12272                }
12273                if found {
12274                    continue;
12275                }
12276            }
12277
12278            for row in (0..=range.start.row).rev() {
12279                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12280                    if crease.range().end.row >= buffer_start_row {
12281                        to_fold.push(crease);
12282                    } else {
12283                        break;
12284                    }
12285                }
12286            }
12287        }
12288
12289        self.fold_creases(to_fold, true, window, cx);
12290    }
12291
12292    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12293        let buffer_row = fold_at.buffer_row;
12294        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12295
12296        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12297            let autoscroll = self
12298                .selections
12299                .all::<Point>(cx)
12300                .iter()
12301                .any(|selection| crease.range().overlaps(&selection.range()));
12302
12303            self.fold_creases(vec![crease], autoscroll, window, cx);
12304        }
12305    }
12306
12307    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12308        if self.is_singleton(cx) {
12309            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12310            let buffer = &display_map.buffer_snapshot;
12311            let selections = self.selections.all::<Point>(cx);
12312            let ranges = selections
12313                .iter()
12314                .map(|s| {
12315                    let range = s.display_range(&display_map).sorted();
12316                    let mut start = range.start.to_point(&display_map);
12317                    let mut end = range.end.to_point(&display_map);
12318                    start.column = 0;
12319                    end.column = buffer.line_len(MultiBufferRow(end.row));
12320                    start..end
12321                })
12322                .collect::<Vec<_>>();
12323
12324            self.unfold_ranges(&ranges, true, true, cx);
12325        } else {
12326            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12327            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12328                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12329                .map(|(snapshot, _, _)| snapshot.remote_id())
12330                .collect();
12331            for buffer_id in buffer_ids {
12332                self.unfold_buffer(buffer_id, cx);
12333            }
12334        }
12335    }
12336
12337    pub fn unfold_recursive(
12338        &mut self,
12339        _: &UnfoldRecursive,
12340        _window: &mut Window,
12341        cx: &mut Context<Self>,
12342    ) {
12343        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12344        let selections = self.selections.all::<Point>(cx);
12345        let ranges = selections
12346            .iter()
12347            .map(|s| {
12348                let mut range = s.display_range(&display_map).sorted();
12349                *range.start.column_mut() = 0;
12350                *range.end.column_mut() = display_map.line_len(range.end.row());
12351                let start = range.start.to_point(&display_map);
12352                let end = range.end.to_point(&display_map);
12353                start..end
12354            })
12355            .collect::<Vec<_>>();
12356
12357        self.unfold_ranges(&ranges, true, true, cx);
12358    }
12359
12360    pub fn unfold_at(
12361        &mut self,
12362        unfold_at: &UnfoldAt,
12363        _window: &mut Window,
12364        cx: &mut Context<Self>,
12365    ) {
12366        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12367
12368        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12369            ..Point::new(
12370                unfold_at.buffer_row.0,
12371                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12372            );
12373
12374        let autoscroll = self
12375            .selections
12376            .all::<Point>(cx)
12377            .iter()
12378            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12379
12380        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12381    }
12382
12383    pub fn unfold_all(
12384        &mut self,
12385        _: &actions::UnfoldAll,
12386        _window: &mut Window,
12387        cx: &mut Context<Self>,
12388    ) {
12389        if self.buffer.read(cx).is_singleton() {
12390            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12391            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12392        } else {
12393            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12394                editor
12395                    .update(&mut cx, |editor, cx| {
12396                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12397                            editor.unfold_buffer(buffer_id, cx);
12398                        }
12399                    })
12400                    .ok();
12401            });
12402        }
12403    }
12404
12405    pub fn fold_selected_ranges(
12406        &mut self,
12407        _: &FoldSelectedRanges,
12408        window: &mut Window,
12409        cx: &mut Context<Self>,
12410    ) {
12411        let selections = self.selections.all::<Point>(cx);
12412        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12413        let line_mode = self.selections.line_mode;
12414        let ranges = selections
12415            .into_iter()
12416            .map(|s| {
12417                if line_mode {
12418                    let start = Point::new(s.start.row, 0);
12419                    let end = Point::new(
12420                        s.end.row,
12421                        display_map
12422                            .buffer_snapshot
12423                            .line_len(MultiBufferRow(s.end.row)),
12424                    );
12425                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12426                } else {
12427                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12428                }
12429            })
12430            .collect::<Vec<_>>();
12431        self.fold_creases(ranges, true, window, cx);
12432    }
12433
12434    pub fn fold_ranges<T: ToOffset + Clone>(
12435        &mut self,
12436        ranges: Vec<Range<T>>,
12437        auto_scroll: bool,
12438        window: &mut Window,
12439        cx: &mut Context<Self>,
12440    ) {
12441        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12442        let ranges = ranges
12443            .into_iter()
12444            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12445            .collect::<Vec<_>>();
12446        self.fold_creases(ranges, auto_scroll, window, cx);
12447    }
12448
12449    pub fn fold_creases<T: ToOffset + Clone>(
12450        &mut self,
12451        creases: Vec<Crease<T>>,
12452        auto_scroll: bool,
12453        window: &mut Window,
12454        cx: &mut Context<Self>,
12455    ) {
12456        if creases.is_empty() {
12457            return;
12458        }
12459
12460        let mut buffers_affected = HashSet::default();
12461        let multi_buffer = self.buffer().read(cx);
12462        for crease in &creases {
12463            if let Some((_, buffer, _)) =
12464                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12465            {
12466                buffers_affected.insert(buffer.read(cx).remote_id());
12467            };
12468        }
12469
12470        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12471
12472        if auto_scroll {
12473            self.request_autoscroll(Autoscroll::fit(), cx);
12474        }
12475
12476        cx.notify();
12477
12478        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12479            // Clear diagnostics block when folding a range that contains it.
12480            let snapshot = self.snapshot(window, cx);
12481            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12482                drop(snapshot);
12483                self.active_diagnostics = Some(active_diagnostics);
12484                self.dismiss_diagnostics(cx);
12485            } else {
12486                self.active_diagnostics = Some(active_diagnostics);
12487            }
12488        }
12489
12490        self.scrollbar_marker_state.dirty = true;
12491    }
12492
12493    /// Removes any folds whose ranges intersect any of the given ranges.
12494    pub fn unfold_ranges<T: ToOffset + Clone>(
12495        &mut self,
12496        ranges: &[Range<T>],
12497        inclusive: bool,
12498        auto_scroll: bool,
12499        cx: &mut Context<Self>,
12500    ) {
12501        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12502            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12503        });
12504    }
12505
12506    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12507        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12508            return;
12509        }
12510        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12511        self.display_map
12512            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12513        cx.emit(EditorEvent::BufferFoldToggled {
12514            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12515            folded: true,
12516        });
12517        cx.notify();
12518    }
12519
12520    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12521        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12522            return;
12523        }
12524        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12525        self.display_map.update(cx, |display_map, cx| {
12526            display_map.unfold_buffer(buffer_id, cx);
12527        });
12528        cx.emit(EditorEvent::BufferFoldToggled {
12529            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12530            folded: false,
12531        });
12532        cx.notify();
12533    }
12534
12535    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12536        self.display_map.read(cx).is_buffer_folded(buffer)
12537    }
12538
12539    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12540        self.display_map.read(cx).folded_buffers()
12541    }
12542
12543    /// Removes any folds with the given ranges.
12544    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12545        &mut self,
12546        ranges: &[Range<T>],
12547        type_id: TypeId,
12548        auto_scroll: bool,
12549        cx: &mut Context<Self>,
12550    ) {
12551        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12552            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12553        });
12554    }
12555
12556    fn remove_folds_with<T: ToOffset + Clone>(
12557        &mut self,
12558        ranges: &[Range<T>],
12559        auto_scroll: bool,
12560        cx: &mut Context<Self>,
12561        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12562    ) {
12563        if ranges.is_empty() {
12564            return;
12565        }
12566
12567        let mut buffers_affected = HashSet::default();
12568        let multi_buffer = self.buffer().read(cx);
12569        for range in ranges {
12570            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12571                buffers_affected.insert(buffer.read(cx).remote_id());
12572            };
12573        }
12574
12575        self.display_map.update(cx, update);
12576
12577        if auto_scroll {
12578            self.request_autoscroll(Autoscroll::fit(), cx);
12579        }
12580
12581        cx.notify();
12582        self.scrollbar_marker_state.dirty = true;
12583        self.active_indent_guides_state.dirty = true;
12584    }
12585
12586    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12587        self.display_map.read(cx).fold_placeholder.clone()
12588    }
12589
12590    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12591        self.buffer.update(cx, |buffer, cx| {
12592            buffer.set_all_diff_hunks_expanded(cx);
12593        });
12594    }
12595
12596    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12597        self.distinguish_unstaged_diff_hunks = true;
12598    }
12599
12600    pub fn expand_all_diff_hunks(
12601        &mut self,
12602        _: &ExpandAllHunkDiffs,
12603        _window: &mut Window,
12604        cx: &mut Context<Self>,
12605    ) {
12606        self.buffer.update(cx, |buffer, cx| {
12607            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12608        });
12609    }
12610
12611    pub fn toggle_selected_diff_hunks(
12612        &mut self,
12613        _: &ToggleSelectedDiffHunks,
12614        _window: &mut Window,
12615        cx: &mut Context<Self>,
12616    ) {
12617        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12618        self.toggle_diff_hunks_in_ranges(ranges, cx);
12619    }
12620
12621    fn diff_hunks_in_ranges<'a>(
12622        &'a self,
12623        ranges: &'a [Range<Anchor>],
12624        buffer: &'a MultiBufferSnapshot,
12625    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12626        ranges.iter().flat_map(move |range| {
12627            let end_excerpt_id = range.end.excerpt_id;
12628            let range = range.to_point(buffer);
12629            let mut peek_end = range.end;
12630            if range.end.row < buffer.max_row().0 {
12631                peek_end = Point::new(range.end.row + 1, 0);
12632            }
12633            buffer
12634                .diff_hunks_in_range(range.start..peek_end)
12635                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12636        })
12637    }
12638
12639    pub fn has_stageable_diff_hunks_in_ranges(
12640        &self,
12641        ranges: &[Range<Anchor>],
12642        snapshot: &MultiBufferSnapshot,
12643    ) -> bool {
12644        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12645        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12646    }
12647
12648    pub fn toggle_staged_selected_diff_hunks(
12649        &mut self,
12650        _: &ToggleStagedSelectedDiffHunks,
12651        _window: &mut Window,
12652        cx: &mut Context<Self>,
12653    ) {
12654        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12655        self.stage_or_unstage_diff_hunks(&ranges, cx);
12656    }
12657
12658    pub fn stage_or_unstage_diff_hunks(
12659        &mut self,
12660        ranges: &[Range<Anchor>],
12661        cx: &mut Context<Self>,
12662    ) {
12663        let Some(project) = &self.project else {
12664            return;
12665        };
12666        let snapshot = self.buffer.read(cx).snapshot(cx);
12667        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12668
12669        let chunk_by = self
12670            .diff_hunks_in_ranges(&ranges, &snapshot)
12671            .chunk_by(|hunk| hunk.buffer_id);
12672        for (buffer_id, hunks) in &chunk_by {
12673            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12674                log::debug!("no buffer for id");
12675                continue;
12676            };
12677            let buffer = buffer.read(cx).snapshot();
12678            let Some((repo, path)) = project
12679                .read(cx)
12680                .repository_and_path_for_buffer_id(buffer_id, cx)
12681            else {
12682                log::debug!("no git repo for buffer id");
12683                continue;
12684            };
12685            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12686                log::debug!("no diff for buffer id");
12687                continue;
12688            };
12689            let Some(secondary_diff) = diff.secondary_diff() else {
12690                log::debug!("no secondary diff for buffer id");
12691                continue;
12692            };
12693
12694            let edits = diff.secondary_edits_for_stage_or_unstage(
12695                stage,
12696                hunks.map(|hunk| {
12697                    (
12698                        hunk.diff_base_byte_range.clone(),
12699                        hunk.secondary_diff_base_byte_range.clone(),
12700                        hunk.buffer_range.clone(),
12701                    )
12702                }),
12703                &buffer,
12704            );
12705
12706            let index_base = secondary_diff.base_text().map_or_else(
12707                || Rope::from(""),
12708                |snapshot| snapshot.text.as_rope().clone(),
12709            );
12710            let index_buffer = cx.new(|cx| {
12711                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12712            });
12713            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12714                index_buffer.edit(edits, None, cx);
12715                index_buffer.snapshot().as_rope().to_string()
12716            });
12717            let new_index_text = if new_index_text.is_empty()
12718                && (diff.is_single_insertion
12719                    || buffer
12720                        .file()
12721                        .map_or(false, |file| file.disk_state() == DiskState::New))
12722            {
12723                log::debug!("removing from index");
12724                None
12725            } else {
12726                Some(new_index_text)
12727            };
12728
12729            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12730        }
12731    }
12732
12733    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12734        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12735        self.buffer
12736            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12737    }
12738
12739    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12740        self.buffer.update(cx, |buffer, cx| {
12741            let ranges = vec![Anchor::min()..Anchor::max()];
12742            if !buffer.all_diff_hunks_expanded()
12743                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12744            {
12745                buffer.collapse_diff_hunks(ranges, cx);
12746                true
12747            } else {
12748                false
12749            }
12750        })
12751    }
12752
12753    fn toggle_diff_hunks_in_ranges(
12754        &mut self,
12755        ranges: Vec<Range<Anchor>>,
12756        cx: &mut Context<'_, Editor>,
12757    ) {
12758        self.buffer.update(cx, |buffer, cx| {
12759            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12760            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12761        })
12762    }
12763
12764    fn toggle_diff_hunks_in_ranges_narrow(
12765        &mut self,
12766        ranges: Vec<Range<Anchor>>,
12767        cx: &mut Context<'_, Editor>,
12768    ) {
12769        self.buffer.update(cx, |buffer, cx| {
12770            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12771            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12772        })
12773    }
12774
12775    pub(crate) fn apply_all_diff_hunks(
12776        &mut self,
12777        _: &ApplyAllDiffHunks,
12778        window: &mut Window,
12779        cx: &mut Context<Self>,
12780    ) {
12781        let buffers = self.buffer.read(cx).all_buffers();
12782        for branch_buffer in buffers {
12783            branch_buffer.update(cx, |branch_buffer, cx| {
12784                branch_buffer.merge_into_base(Vec::new(), cx);
12785            });
12786        }
12787
12788        if let Some(project) = self.project.clone() {
12789            self.save(true, project, window, cx).detach_and_log_err(cx);
12790        }
12791    }
12792
12793    pub(crate) fn apply_selected_diff_hunks(
12794        &mut self,
12795        _: &ApplyDiffHunk,
12796        window: &mut Window,
12797        cx: &mut Context<Self>,
12798    ) {
12799        let snapshot = self.snapshot(window, cx);
12800        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12801        let mut ranges_by_buffer = HashMap::default();
12802        self.transact(window, cx, |editor, _window, cx| {
12803            for hunk in hunks {
12804                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12805                    ranges_by_buffer
12806                        .entry(buffer.clone())
12807                        .or_insert_with(Vec::new)
12808                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12809                }
12810            }
12811
12812            for (buffer, ranges) in ranges_by_buffer {
12813                buffer.update(cx, |buffer, cx| {
12814                    buffer.merge_into_base(ranges, cx);
12815                });
12816            }
12817        });
12818
12819        if let Some(project) = self.project.clone() {
12820            self.save(true, project, window, cx).detach_and_log_err(cx);
12821        }
12822    }
12823
12824    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12825        if hovered != self.gutter_hovered {
12826            self.gutter_hovered = hovered;
12827            cx.notify();
12828        }
12829    }
12830
12831    pub fn insert_blocks(
12832        &mut self,
12833        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12834        autoscroll: Option<Autoscroll>,
12835        cx: &mut Context<Self>,
12836    ) -> Vec<CustomBlockId> {
12837        let blocks = self
12838            .display_map
12839            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12840        if let Some(autoscroll) = autoscroll {
12841            self.request_autoscroll(autoscroll, cx);
12842        }
12843        cx.notify();
12844        blocks
12845    }
12846
12847    pub fn resize_blocks(
12848        &mut self,
12849        heights: HashMap<CustomBlockId, u32>,
12850        autoscroll: Option<Autoscroll>,
12851        cx: &mut Context<Self>,
12852    ) {
12853        self.display_map
12854            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12855        if let Some(autoscroll) = autoscroll {
12856            self.request_autoscroll(autoscroll, cx);
12857        }
12858        cx.notify();
12859    }
12860
12861    pub fn replace_blocks(
12862        &mut self,
12863        renderers: HashMap<CustomBlockId, RenderBlock>,
12864        autoscroll: Option<Autoscroll>,
12865        cx: &mut Context<Self>,
12866    ) {
12867        self.display_map
12868            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12869        if let Some(autoscroll) = autoscroll {
12870            self.request_autoscroll(autoscroll, cx);
12871        }
12872        cx.notify();
12873    }
12874
12875    pub fn remove_blocks(
12876        &mut self,
12877        block_ids: HashSet<CustomBlockId>,
12878        autoscroll: Option<Autoscroll>,
12879        cx: &mut Context<Self>,
12880    ) {
12881        self.display_map.update(cx, |display_map, cx| {
12882            display_map.remove_blocks(block_ids, cx)
12883        });
12884        if let Some(autoscroll) = autoscroll {
12885            self.request_autoscroll(autoscroll, cx);
12886        }
12887        cx.notify();
12888    }
12889
12890    pub fn row_for_block(
12891        &self,
12892        block_id: CustomBlockId,
12893        cx: &mut Context<Self>,
12894    ) -> Option<DisplayRow> {
12895        self.display_map
12896            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12897    }
12898
12899    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12900        self.focused_block = Some(focused_block);
12901    }
12902
12903    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12904        self.focused_block.take()
12905    }
12906
12907    pub fn insert_creases(
12908        &mut self,
12909        creases: impl IntoIterator<Item = Crease<Anchor>>,
12910        cx: &mut Context<Self>,
12911    ) -> Vec<CreaseId> {
12912        self.display_map
12913            .update(cx, |map, cx| map.insert_creases(creases, cx))
12914    }
12915
12916    pub fn remove_creases(
12917        &mut self,
12918        ids: impl IntoIterator<Item = CreaseId>,
12919        cx: &mut Context<Self>,
12920    ) {
12921        self.display_map
12922            .update(cx, |map, cx| map.remove_creases(ids, cx));
12923    }
12924
12925    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12926        self.display_map
12927            .update(cx, |map, cx| map.snapshot(cx))
12928            .longest_row()
12929    }
12930
12931    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12932        self.display_map
12933            .update(cx, |map, cx| map.snapshot(cx))
12934            .max_point()
12935    }
12936
12937    pub fn text(&self, cx: &App) -> String {
12938        self.buffer.read(cx).read(cx).text()
12939    }
12940
12941    pub fn is_empty(&self, cx: &App) -> bool {
12942        self.buffer.read(cx).read(cx).is_empty()
12943    }
12944
12945    pub fn text_option(&self, cx: &App) -> Option<String> {
12946        let text = self.text(cx);
12947        let text = text.trim();
12948
12949        if text.is_empty() {
12950            return None;
12951        }
12952
12953        Some(text.to_string())
12954    }
12955
12956    pub fn set_text(
12957        &mut self,
12958        text: impl Into<Arc<str>>,
12959        window: &mut Window,
12960        cx: &mut Context<Self>,
12961    ) {
12962        self.transact(window, cx, |this, _, cx| {
12963            this.buffer
12964                .read(cx)
12965                .as_singleton()
12966                .expect("you can only call set_text on editors for singleton buffers")
12967                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12968        });
12969    }
12970
12971    pub fn display_text(&self, cx: &mut App) -> String {
12972        self.display_map
12973            .update(cx, |map, cx| map.snapshot(cx))
12974            .text()
12975    }
12976
12977    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12978        let mut wrap_guides = smallvec::smallvec![];
12979
12980        if self.show_wrap_guides == Some(false) {
12981            return wrap_guides;
12982        }
12983
12984        let settings = self.buffer.read(cx).settings_at(0, cx);
12985        if settings.show_wrap_guides {
12986            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12987                wrap_guides.push((soft_wrap as usize, true));
12988            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12989                wrap_guides.push((soft_wrap as usize, true));
12990            }
12991            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12992        }
12993
12994        wrap_guides
12995    }
12996
12997    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12998        let settings = self.buffer.read(cx).settings_at(0, cx);
12999        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13000        match mode {
13001            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13002                SoftWrap::None
13003            }
13004            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13005            language_settings::SoftWrap::PreferredLineLength => {
13006                SoftWrap::Column(settings.preferred_line_length)
13007            }
13008            language_settings::SoftWrap::Bounded => {
13009                SoftWrap::Bounded(settings.preferred_line_length)
13010            }
13011        }
13012    }
13013
13014    pub fn set_soft_wrap_mode(
13015        &mut self,
13016        mode: language_settings::SoftWrap,
13017
13018        cx: &mut Context<Self>,
13019    ) {
13020        self.soft_wrap_mode_override = Some(mode);
13021        cx.notify();
13022    }
13023
13024    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13025        self.text_style_refinement = Some(style);
13026    }
13027
13028    /// called by the Element so we know what style we were most recently rendered with.
13029    pub(crate) fn set_style(
13030        &mut self,
13031        style: EditorStyle,
13032        window: &mut Window,
13033        cx: &mut Context<Self>,
13034    ) {
13035        let rem_size = window.rem_size();
13036        self.display_map.update(cx, |map, cx| {
13037            map.set_font(
13038                style.text.font(),
13039                style.text.font_size.to_pixels(rem_size),
13040                cx,
13041            )
13042        });
13043        self.style = Some(style);
13044    }
13045
13046    pub fn style(&self) -> Option<&EditorStyle> {
13047        self.style.as_ref()
13048    }
13049
13050    // Called by the element. This method is not designed to be called outside of the editor
13051    // element's layout code because it does not notify when rewrapping is computed synchronously.
13052    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13053        self.display_map
13054            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13055    }
13056
13057    pub fn set_soft_wrap(&mut self) {
13058        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13059    }
13060
13061    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13062        if self.soft_wrap_mode_override.is_some() {
13063            self.soft_wrap_mode_override.take();
13064        } else {
13065            let soft_wrap = match self.soft_wrap_mode(cx) {
13066                SoftWrap::GitDiff => return,
13067                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13068                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13069                    language_settings::SoftWrap::None
13070                }
13071            };
13072            self.soft_wrap_mode_override = Some(soft_wrap);
13073        }
13074        cx.notify();
13075    }
13076
13077    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13078        let Some(workspace) = self.workspace() else {
13079            return;
13080        };
13081        let fs = workspace.read(cx).app_state().fs.clone();
13082        let current_show = TabBarSettings::get_global(cx).show;
13083        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13084            setting.show = Some(!current_show);
13085        });
13086    }
13087
13088    pub fn toggle_indent_guides(
13089        &mut self,
13090        _: &ToggleIndentGuides,
13091        _: &mut Window,
13092        cx: &mut Context<Self>,
13093    ) {
13094        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13095            self.buffer
13096                .read(cx)
13097                .settings_at(0, cx)
13098                .indent_guides
13099                .enabled
13100        });
13101        self.show_indent_guides = Some(!currently_enabled);
13102        cx.notify();
13103    }
13104
13105    fn should_show_indent_guides(&self) -> Option<bool> {
13106        self.show_indent_guides
13107    }
13108
13109    pub fn toggle_line_numbers(
13110        &mut self,
13111        _: &ToggleLineNumbers,
13112        _: &mut Window,
13113        cx: &mut Context<Self>,
13114    ) {
13115        let mut editor_settings = EditorSettings::get_global(cx).clone();
13116        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13117        EditorSettings::override_global(editor_settings, cx);
13118    }
13119
13120    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13121        self.use_relative_line_numbers
13122            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13123    }
13124
13125    pub fn toggle_relative_line_numbers(
13126        &mut self,
13127        _: &ToggleRelativeLineNumbers,
13128        _: &mut Window,
13129        cx: &mut Context<Self>,
13130    ) {
13131        let is_relative = self.should_use_relative_line_numbers(cx);
13132        self.set_relative_line_number(Some(!is_relative), cx)
13133    }
13134
13135    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13136        self.use_relative_line_numbers = is_relative;
13137        cx.notify();
13138    }
13139
13140    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13141        self.show_gutter = show_gutter;
13142        cx.notify();
13143    }
13144
13145    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13146        self.show_scrollbars = show_scrollbars;
13147        cx.notify();
13148    }
13149
13150    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13151        self.show_line_numbers = Some(show_line_numbers);
13152        cx.notify();
13153    }
13154
13155    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13156        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13157        cx.notify();
13158    }
13159
13160    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13161        self.show_code_actions = Some(show_code_actions);
13162        cx.notify();
13163    }
13164
13165    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13166        self.show_runnables = Some(show_runnables);
13167        cx.notify();
13168    }
13169
13170    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13171        if self.display_map.read(cx).masked != masked {
13172            self.display_map.update(cx, |map, _| map.masked = masked);
13173        }
13174        cx.notify()
13175    }
13176
13177    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13178        self.show_wrap_guides = Some(show_wrap_guides);
13179        cx.notify();
13180    }
13181
13182    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13183        self.show_indent_guides = Some(show_indent_guides);
13184        cx.notify();
13185    }
13186
13187    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13188        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13189            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13190                if let Some(dir) = file.abs_path(cx).parent() {
13191                    return Some(dir.to_owned());
13192                }
13193            }
13194
13195            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13196                return Some(project_path.path.to_path_buf());
13197            }
13198        }
13199
13200        None
13201    }
13202
13203    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13204        self.active_excerpt(cx)?
13205            .1
13206            .read(cx)
13207            .file()
13208            .and_then(|f| f.as_local())
13209    }
13210
13211    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13212        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13213            let buffer = buffer.read(cx);
13214            if let Some(project_path) = buffer.project_path(cx) {
13215                let project = self.project.as_ref()?.read(cx);
13216                project.absolute_path(&project_path, cx)
13217            } else {
13218                buffer
13219                    .file()
13220                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13221            }
13222        })
13223    }
13224
13225    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13226        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13227            let project_path = buffer.read(cx).project_path(cx)?;
13228            let project = self.project.as_ref()?.read(cx);
13229            let entry = project.entry_for_path(&project_path, cx)?;
13230            let path = entry.path.to_path_buf();
13231            Some(path)
13232        })
13233    }
13234
13235    pub fn reveal_in_finder(
13236        &mut self,
13237        _: &RevealInFileManager,
13238        _window: &mut Window,
13239        cx: &mut Context<Self>,
13240    ) {
13241        if let Some(target) = self.target_file(cx) {
13242            cx.reveal_path(&target.abs_path(cx));
13243        }
13244    }
13245
13246    pub fn copy_path(
13247        &mut self,
13248        _: &zed_actions::workspace::CopyPath,
13249        _window: &mut Window,
13250        cx: &mut Context<Self>,
13251    ) {
13252        if let Some(path) = self.target_file_abs_path(cx) {
13253            if let Some(path) = path.to_str() {
13254                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13255            }
13256        }
13257    }
13258
13259    pub fn copy_relative_path(
13260        &mut self,
13261        _: &zed_actions::workspace::CopyRelativePath,
13262        _window: &mut Window,
13263        cx: &mut Context<Self>,
13264    ) {
13265        if let Some(path) = self.target_file_path(cx) {
13266            if let Some(path) = path.to_str() {
13267                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13268            }
13269        }
13270    }
13271
13272    pub fn copy_file_name_without_extension(
13273        &mut self,
13274        _: &CopyFileNameWithoutExtension,
13275        _: &mut Window,
13276        cx: &mut Context<Self>,
13277    ) {
13278        if let Some(file) = self.target_file(cx) {
13279            if let Some(file_stem) = file.path().file_stem() {
13280                if let Some(name) = file_stem.to_str() {
13281                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13282                }
13283            }
13284        }
13285    }
13286
13287    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13288        if let Some(file) = self.target_file(cx) {
13289            if let Some(file_name) = file.path().file_name() {
13290                if let Some(name) = file_name.to_str() {
13291                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13292                }
13293            }
13294        }
13295    }
13296
13297    pub fn toggle_git_blame(
13298        &mut self,
13299        _: &ToggleGitBlame,
13300        window: &mut Window,
13301        cx: &mut Context<Self>,
13302    ) {
13303        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13304
13305        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13306            self.start_git_blame(true, window, cx);
13307        }
13308
13309        cx.notify();
13310    }
13311
13312    pub fn toggle_git_blame_inline(
13313        &mut self,
13314        _: &ToggleGitBlameInline,
13315        window: &mut Window,
13316        cx: &mut Context<Self>,
13317    ) {
13318        self.toggle_git_blame_inline_internal(true, window, cx);
13319        cx.notify();
13320    }
13321
13322    pub fn git_blame_inline_enabled(&self) -> bool {
13323        self.git_blame_inline_enabled
13324    }
13325
13326    pub fn toggle_selection_menu(
13327        &mut self,
13328        _: &ToggleSelectionMenu,
13329        _: &mut Window,
13330        cx: &mut Context<Self>,
13331    ) {
13332        self.show_selection_menu = self
13333            .show_selection_menu
13334            .map(|show_selections_menu| !show_selections_menu)
13335            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13336
13337        cx.notify();
13338    }
13339
13340    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13341        self.show_selection_menu
13342            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13343    }
13344
13345    fn start_git_blame(
13346        &mut self,
13347        user_triggered: bool,
13348        window: &mut Window,
13349        cx: &mut Context<Self>,
13350    ) {
13351        if let Some(project) = self.project.as_ref() {
13352            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13353                return;
13354            };
13355
13356            if buffer.read(cx).file().is_none() {
13357                return;
13358            }
13359
13360            let focused = self.focus_handle(cx).contains_focused(window, cx);
13361
13362            let project = project.clone();
13363            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13364            self.blame_subscription =
13365                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13366            self.blame = Some(blame);
13367        }
13368    }
13369
13370    fn toggle_git_blame_inline_internal(
13371        &mut self,
13372        user_triggered: bool,
13373        window: &mut Window,
13374        cx: &mut Context<Self>,
13375    ) {
13376        if self.git_blame_inline_enabled {
13377            self.git_blame_inline_enabled = false;
13378            self.show_git_blame_inline = false;
13379            self.show_git_blame_inline_delay_task.take();
13380        } else {
13381            self.git_blame_inline_enabled = true;
13382            self.start_git_blame_inline(user_triggered, window, cx);
13383        }
13384
13385        cx.notify();
13386    }
13387
13388    fn start_git_blame_inline(
13389        &mut self,
13390        user_triggered: bool,
13391        window: &mut Window,
13392        cx: &mut Context<Self>,
13393    ) {
13394        self.start_git_blame(user_triggered, window, cx);
13395
13396        if ProjectSettings::get_global(cx)
13397            .git
13398            .inline_blame_delay()
13399            .is_some()
13400        {
13401            self.start_inline_blame_timer(window, cx);
13402        } else {
13403            self.show_git_blame_inline = true
13404        }
13405    }
13406
13407    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13408        self.blame.as_ref()
13409    }
13410
13411    pub fn show_git_blame_gutter(&self) -> bool {
13412        self.show_git_blame_gutter
13413    }
13414
13415    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13416        self.show_git_blame_gutter && self.has_blame_entries(cx)
13417    }
13418
13419    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13420        self.show_git_blame_inline
13421            && self.focus_handle.is_focused(window)
13422            && !self.newest_selection_head_on_empty_line(cx)
13423            && self.has_blame_entries(cx)
13424    }
13425
13426    fn has_blame_entries(&self, cx: &App) -> bool {
13427        self.blame()
13428            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13429    }
13430
13431    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13432        let cursor_anchor = self.selections.newest_anchor().head();
13433
13434        let snapshot = self.buffer.read(cx).snapshot(cx);
13435        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13436
13437        snapshot.line_len(buffer_row) == 0
13438    }
13439
13440    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13441        let buffer_and_selection = maybe!({
13442            let selection = self.selections.newest::<Point>(cx);
13443            let selection_range = selection.range();
13444
13445            let multi_buffer = self.buffer().read(cx);
13446            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13447            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13448
13449            let (buffer, range, _) = if selection.reversed {
13450                buffer_ranges.first()
13451            } else {
13452                buffer_ranges.last()
13453            }?;
13454
13455            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13456                ..text::ToPoint::to_point(&range.end, &buffer).row;
13457            Some((
13458                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13459                selection,
13460            ))
13461        });
13462
13463        let Some((buffer, selection)) = buffer_and_selection else {
13464            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13465        };
13466
13467        let Some(project) = self.project.as_ref() else {
13468            return Task::ready(Err(anyhow!("editor does not have project")));
13469        };
13470
13471        project.update(cx, |project, cx| {
13472            project.get_permalink_to_line(&buffer, selection, cx)
13473        })
13474    }
13475
13476    pub fn copy_permalink_to_line(
13477        &mut self,
13478        _: &CopyPermalinkToLine,
13479        window: &mut Window,
13480        cx: &mut Context<Self>,
13481    ) {
13482        let permalink_task = self.get_permalink_to_line(cx);
13483        let workspace = self.workspace();
13484
13485        cx.spawn_in(window, |_, mut cx| async move {
13486            match permalink_task.await {
13487                Ok(permalink) => {
13488                    cx.update(|_, cx| {
13489                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13490                    })
13491                    .ok();
13492                }
13493                Err(err) => {
13494                    let message = format!("Failed to copy permalink: {err}");
13495
13496                    Err::<(), anyhow::Error>(err).log_err();
13497
13498                    if let Some(workspace) = workspace {
13499                        workspace
13500                            .update_in(&mut cx, |workspace, _, cx| {
13501                                struct CopyPermalinkToLine;
13502
13503                                workspace.show_toast(
13504                                    Toast::new(
13505                                        NotificationId::unique::<CopyPermalinkToLine>(),
13506                                        message,
13507                                    ),
13508                                    cx,
13509                                )
13510                            })
13511                            .ok();
13512                    }
13513                }
13514            }
13515        })
13516        .detach();
13517    }
13518
13519    pub fn copy_file_location(
13520        &mut self,
13521        _: &CopyFileLocation,
13522        _: &mut Window,
13523        cx: &mut Context<Self>,
13524    ) {
13525        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13526        if let Some(file) = self.target_file(cx) {
13527            if let Some(path) = file.path().to_str() {
13528                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13529            }
13530        }
13531    }
13532
13533    pub fn open_permalink_to_line(
13534        &mut self,
13535        _: &OpenPermalinkToLine,
13536        window: &mut Window,
13537        cx: &mut Context<Self>,
13538    ) {
13539        let permalink_task = self.get_permalink_to_line(cx);
13540        let workspace = self.workspace();
13541
13542        cx.spawn_in(window, |_, mut cx| async move {
13543            match permalink_task.await {
13544                Ok(permalink) => {
13545                    cx.update(|_, cx| {
13546                        cx.open_url(permalink.as_ref());
13547                    })
13548                    .ok();
13549                }
13550                Err(err) => {
13551                    let message = format!("Failed to open permalink: {err}");
13552
13553                    Err::<(), anyhow::Error>(err).log_err();
13554
13555                    if let Some(workspace) = workspace {
13556                        workspace
13557                            .update(&mut cx, |workspace, cx| {
13558                                struct OpenPermalinkToLine;
13559
13560                                workspace.show_toast(
13561                                    Toast::new(
13562                                        NotificationId::unique::<OpenPermalinkToLine>(),
13563                                        message,
13564                                    ),
13565                                    cx,
13566                                )
13567                            })
13568                            .ok();
13569                    }
13570                }
13571            }
13572        })
13573        .detach();
13574    }
13575
13576    pub fn insert_uuid_v4(
13577        &mut self,
13578        _: &InsertUuidV4,
13579        window: &mut Window,
13580        cx: &mut Context<Self>,
13581    ) {
13582        self.insert_uuid(UuidVersion::V4, window, cx);
13583    }
13584
13585    pub fn insert_uuid_v7(
13586        &mut self,
13587        _: &InsertUuidV7,
13588        window: &mut Window,
13589        cx: &mut Context<Self>,
13590    ) {
13591        self.insert_uuid(UuidVersion::V7, window, cx);
13592    }
13593
13594    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13595        self.transact(window, cx, |this, window, cx| {
13596            let edits = this
13597                .selections
13598                .all::<Point>(cx)
13599                .into_iter()
13600                .map(|selection| {
13601                    let uuid = match version {
13602                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13603                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13604                    };
13605
13606                    (selection.range(), uuid.to_string())
13607                });
13608            this.edit(edits, cx);
13609            this.refresh_inline_completion(true, false, window, cx);
13610        });
13611    }
13612
13613    pub fn open_selections_in_multibuffer(
13614        &mut self,
13615        _: &OpenSelectionsInMultibuffer,
13616        window: &mut Window,
13617        cx: &mut Context<Self>,
13618    ) {
13619        let multibuffer = self.buffer.read(cx);
13620
13621        let Some(buffer) = multibuffer.as_singleton() else {
13622            return;
13623        };
13624
13625        let Some(workspace) = self.workspace() else {
13626            return;
13627        };
13628
13629        let locations = self
13630            .selections
13631            .disjoint_anchors()
13632            .iter()
13633            .map(|range| Location {
13634                buffer: buffer.clone(),
13635                range: range.start.text_anchor..range.end.text_anchor,
13636            })
13637            .collect::<Vec<_>>();
13638
13639        let title = multibuffer.title(cx).to_string();
13640
13641        cx.spawn_in(window, |_, mut cx| async move {
13642            workspace.update_in(&mut cx, |workspace, window, cx| {
13643                Self::open_locations_in_multibuffer(
13644                    workspace,
13645                    locations,
13646                    format!("Selections for '{title}'"),
13647                    false,
13648                    MultibufferSelectionMode::All,
13649                    window,
13650                    cx,
13651                );
13652            })
13653        })
13654        .detach();
13655    }
13656
13657    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13658    /// last highlight added will be used.
13659    ///
13660    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13661    pub fn highlight_rows<T: 'static>(
13662        &mut self,
13663        range: Range<Anchor>,
13664        color: Hsla,
13665        should_autoscroll: bool,
13666        cx: &mut Context<Self>,
13667    ) {
13668        let snapshot = self.buffer().read(cx).snapshot(cx);
13669        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13670        let ix = row_highlights.binary_search_by(|highlight| {
13671            Ordering::Equal
13672                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13673                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13674        });
13675
13676        if let Err(mut ix) = ix {
13677            let index = post_inc(&mut self.highlight_order);
13678
13679            // If this range intersects with the preceding highlight, then merge it with
13680            // the preceding highlight. Otherwise insert a new highlight.
13681            let mut merged = false;
13682            if ix > 0 {
13683                let prev_highlight = &mut row_highlights[ix - 1];
13684                if prev_highlight
13685                    .range
13686                    .end
13687                    .cmp(&range.start, &snapshot)
13688                    .is_ge()
13689                {
13690                    ix -= 1;
13691                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13692                        prev_highlight.range.end = range.end;
13693                    }
13694                    merged = true;
13695                    prev_highlight.index = index;
13696                    prev_highlight.color = color;
13697                    prev_highlight.should_autoscroll = should_autoscroll;
13698                }
13699            }
13700
13701            if !merged {
13702                row_highlights.insert(
13703                    ix,
13704                    RowHighlight {
13705                        range: range.clone(),
13706                        index,
13707                        color,
13708                        should_autoscroll,
13709                    },
13710                );
13711            }
13712
13713            // If any of the following highlights intersect with this one, merge them.
13714            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13715                let highlight = &row_highlights[ix];
13716                if next_highlight
13717                    .range
13718                    .start
13719                    .cmp(&highlight.range.end, &snapshot)
13720                    .is_le()
13721                {
13722                    if next_highlight
13723                        .range
13724                        .end
13725                        .cmp(&highlight.range.end, &snapshot)
13726                        .is_gt()
13727                    {
13728                        row_highlights[ix].range.end = next_highlight.range.end;
13729                    }
13730                    row_highlights.remove(ix + 1);
13731                } else {
13732                    break;
13733                }
13734            }
13735        }
13736    }
13737
13738    /// Remove any highlighted row ranges of the given type that intersect the
13739    /// given ranges.
13740    pub fn remove_highlighted_rows<T: 'static>(
13741        &mut self,
13742        ranges_to_remove: Vec<Range<Anchor>>,
13743        cx: &mut Context<Self>,
13744    ) {
13745        let snapshot = self.buffer().read(cx).snapshot(cx);
13746        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13747        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13748        row_highlights.retain(|highlight| {
13749            while let Some(range_to_remove) = ranges_to_remove.peek() {
13750                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13751                    Ordering::Less | Ordering::Equal => {
13752                        ranges_to_remove.next();
13753                    }
13754                    Ordering::Greater => {
13755                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13756                            Ordering::Less | Ordering::Equal => {
13757                                return false;
13758                            }
13759                            Ordering::Greater => break,
13760                        }
13761                    }
13762                }
13763            }
13764
13765            true
13766        })
13767    }
13768
13769    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13770    pub fn clear_row_highlights<T: 'static>(&mut self) {
13771        self.highlighted_rows.remove(&TypeId::of::<T>());
13772    }
13773
13774    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13775    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13776        self.highlighted_rows
13777            .get(&TypeId::of::<T>())
13778            .map_or(&[] as &[_], |vec| vec.as_slice())
13779            .iter()
13780            .map(|highlight| (highlight.range.clone(), highlight.color))
13781    }
13782
13783    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13784    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13785    /// Allows to ignore certain kinds of highlights.
13786    pub fn highlighted_display_rows(
13787        &self,
13788        window: &mut Window,
13789        cx: &mut App,
13790    ) -> BTreeMap<DisplayRow, Background> {
13791        let snapshot = self.snapshot(window, cx);
13792        let mut used_highlight_orders = HashMap::default();
13793        self.highlighted_rows
13794            .iter()
13795            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13796            .fold(
13797                BTreeMap::<DisplayRow, Background>::new(),
13798                |mut unique_rows, highlight| {
13799                    let start = highlight.range.start.to_display_point(&snapshot);
13800                    let end = highlight.range.end.to_display_point(&snapshot);
13801                    let start_row = start.row().0;
13802                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13803                        && end.column() == 0
13804                    {
13805                        end.row().0.saturating_sub(1)
13806                    } else {
13807                        end.row().0
13808                    };
13809                    for row in start_row..=end_row {
13810                        let used_index =
13811                            used_highlight_orders.entry(row).or_insert(highlight.index);
13812                        if highlight.index >= *used_index {
13813                            *used_index = highlight.index;
13814                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13815                        }
13816                    }
13817                    unique_rows
13818                },
13819            )
13820    }
13821
13822    pub fn highlighted_display_row_for_autoscroll(
13823        &self,
13824        snapshot: &DisplaySnapshot,
13825    ) -> Option<DisplayRow> {
13826        self.highlighted_rows
13827            .values()
13828            .flat_map(|highlighted_rows| highlighted_rows.iter())
13829            .filter_map(|highlight| {
13830                if highlight.should_autoscroll {
13831                    Some(highlight.range.start.to_display_point(snapshot).row())
13832                } else {
13833                    None
13834                }
13835            })
13836            .min()
13837    }
13838
13839    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13840        self.highlight_background::<SearchWithinRange>(
13841            ranges,
13842            |colors| colors.editor_document_highlight_read_background,
13843            cx,
13844        )
13845    }
13846
13847    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13848        self.breadcrumb_header = Some(new_header);
13849    }
13850
13851    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13852        self.clear_background_highlights::<SearchWithinRange>(cx);
13853    }
13854
13855    pub fn highlight_background<T: 'static>(
13856        &mut self,
13857        ranges: &[Range<Anchor>],
13858        color_fetcher: fn(&ThemeColors) -> Hsla,
13859        cx: &mut Context<Self>,
13860    ) {
13861        self.background_highlights
13862            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13863        self.scrollbar_marker_state.dirty = true;
13864        cx.notify();
13865    }
13866
13867    pub fn clear_background_highlights<T: 'static>(
13868        &mut self,
13869        cx: &mut Context<Self>,
13870    ) -> Option<BackgroundHighlight> {
13871        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13872        if !text_highlights.1.is_empty() {
13873            self.scrollbar_marker_state.dirty = true;
13874            cx.notify();
13875        }
13876        Some(text_highlights)
13877    }
13878
13879    pub fn highlight_gutter<T: 'static>(
13880        &mut self,
13881        ranges: &[Range<Anchor>],
13882        color_fetcher: fn(&App) -> Hsla,
13883        cx: &mut Context<Self>,
13884    ) {
13885        self.gutter_highlights
13886            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13887        cx.notify();
13888    }
13889
13890    pub fn clear_gutter_highlights<T: 'static>(
13891        &mut self,
13892        cx: &mut Context<Self>,
13893    ) -> Option<GutterHighlight> {
13894        cx.notify();
13895        self.gutter_highlights.remove(&TypeId::of::<T>())
13896    }
13897
13898    #[cfg(feature = "test-support")]
13899    pub fn all_text_background_highlights(
13900        &self,
13901        window: &mut Window,
13902        cx: &mut Context<Self>,
13903    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13904        let snapshot = self.snapshot(window, cx);
13905        let buffer = &snapshot.buffer_snapshot;
13906        let start = buffer.anchor_before(0);
13907        let end = buffer.anchor_after(buffer.len());
13908        let theme = cx.theme().colors();
13909        self.background_highlights_in_range(start..end, &snapshot, theme)
13910    }
13911
13912    #[cfg(feature = "test-support")]
13913    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13914        let snapshot = self.buffer().read(cx).snapshot(cx);
13915
13916        let highlights = self
13917            .background_highlights
13918            .get(&TypeId::of::<items::BufferSearchHighlights>());
13919
13920        if let Some((_color, ranges)) = highlights {
13921            ranges
13922                .iter()
13923                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13924                .collect_vec()
13925        } else {
13926            vec![]
13927        }
13928    }
13929
13930    fn document_highlights_for_position<'a>(
13931        &'a self,
13932        position: Anchor,
13933        buffer: &'a MultiBufferSnapshot,
13934    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13935        let read_highlights = self
13936            .background_highlights
13937            .get(&TypeId::of::<DocumentHighlightRead>())
13938            .map(|h| &h.1);
13939        let write_highlights = self
13940            .background_highlights
13941            .get(&TypeId::of::<DocumentHighlightWrite>())
13942            .map(|h| &h.1);
13943        let left_position = position.bias_left(buffer);
13944        let right_position = position.bias_right(buffer);
13945        read_highlights
13946            .into_iter()
13947            .chain(write_highlights)
13948            .flat_map(move |ranges| {
13949                let start_ix = match ranges.binary_search_by(|probe| {
13950                    let cmp = probe.end.cmp(&left_position, buffer);
13951                    if cmp.is_ge() {
13952                        Ordering::Greater
13953                    } else {
13954                        Ordering::Less
13955                    }
13956                }) {
13957                    Ok(i) | Err(i) => i,
13958                };
13959
13960                ranges[start_ix..]
13961                    .iter()
13962                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13963            })
13964    }
13965
13966    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13967        self.background_highlights
13968            .get(&TypeId::of::<T>())
13969            .map_or(false, |(_, highlights)| !highlights.is_empty())
13970    }
13971
13972    pub fn background_highlights_in_range(
13973        &self,
13974        search_range: Range<Anchor>,
13975        display_snapshot: &DisplaySnapshot,
13976        theme: &ThemeColors,
13977    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13978        let mut results = Vec::new();
13979        for (color_fetcher, ranges) in self.background_highlights.values() {
13980            let color = color_fetcher(theme);
13981            let start_ix = match ranges.binary_search_by(|probe| {
13982                let cmp = probe
13983                    .end
13984                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13985                if cmp.is_gt() {
13986                    Ordering::Greater
13987                } else {
13988                    Ordering::Less
13989                }
13990            }) {
13991                Ok(i) | Err(i) => i,
13992            };
13993            for range in &ranges[start_ix..] {
13994                if range
13995                    .start
13996                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13997                    .is_ge()
13998                {
13999                    break;
14000                }
14001
14002                let start = range.start.to_display_point(display_snapshot);
14003                let end = range.end.to_display_point(display_snapshot);
14004                results.push((start..end, color))
14005            }
14006        }
14007        results
14008    }
14009
14010    pub fn background_highlight_row_ranges<T: 'static>(
14011        &self,
14012        search_range: Range<Anchor>,
14013        display_snapshot: &DisplaySnapshot,
14014        count: usize,
14015    ) -> Vec<RangeInclusive<DisplayPoint>> {
14016        let mut results = Vec::new();
14017        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14018            return vec![];
14019        };
14020
14021        let start_ix = match ranges.binary_search_by(|probe| {
14022            let cmp = probe
14023                .end
14024                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14025            if cmp.is_gt() {
14026                Ordering::Greater
14027            } else {
14028                Ordering::Less
14029            }
14030        }) {
14031            Ok(i) | Err(i) => i,
14032        };
14033        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14034            if let (Some(start_display), Some(end_display)) = (start, end) {
14035                results.push(
14036                    start_display.to_display_point(display_snapshot)
14037                        ..=end_display.to_display_point(display_snapshot),
14038                );
14039            }
14040        };
14041        let mut start_row: Option<Point> = None;
14042        let mut end_row: Option<Point> = None;
14043        if ranges.len() > count {
14044            return Vec::new();
14045        }
14046        for range in &ranges[start_ix..] {
14047            if range
14048                .start
14049                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14050                .is_ge()
14051            {
14052                break;
14053            }
14054            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14055            if let Some(current_row) = &end_row {
14056                if end.row == current_row.row {
14057                    continue;
14058                }
14059            }
14060            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14061            if start_row.is_none() {
14062                assert_eq!(end_row, None);
14063                start_row = Some(start);
14064                end_row = Some(end);
14065                continue;
14066            }
14067            if let Some(current_end) = end_row.as_mut() {
14068                if start.row > current_end.row + 1 {
14069                    push_region(start_row, end_row);
14070                    start_row = Some(start);
14071                    end_row = Some(end);
14072                } else {
14073                    // Merge two hunks.
14074                    *current_end = end;
14075                }
14076            } else {
14077                unreachable!();
14078            }
14079        }
14080        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14081        push_region(start_row, end_row);
14082        results
14083    }
14084
14085    pub fn gutter_highlights_in_range(
14086        &self,
14087        search_range: Range<Anchor>,
14088        display_snapshot: &DisplaySnapshot,
14089        cx: &App,
14090    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14091        let mut results = Vec::new();
14092        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14093            let color = color_fetcher(cx);
14094            let start_ix = match ranges.binary_search_by(|probe| {
14095                let cmp = probe
14096                    .end
14097                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14098                if cmp.is_gt() {
14099                    Ordering::Greater
14100                } else {
14101                    Ordering::Less
14102                }
14103            }) {
14104                Ok(i) | Err(i) => i,
14105            };
14106            for range in &ranges[start_ix..] {
14107                if range
14108                    .start
14109                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14110                    .is_ge()
14111                {
14112                    break;
14113                }
14114
14115                let start = range.start.to_display_point(display_snapshot);
14116                let end = range.end.to_display_point(display_snapshot);
14117                results.push((start..end, color))
14118            }
14119        }
14120        results
14121    }
14122
14123    /// Get the text ranges corresponding to the redaction query
14124    pub fn redacted_ranges(
14125        &self,
14126        search_range: Range<Anchor>,
14127        display_snapshot: &DisplaySnapshot,
14128        cx: &App,
14129    ) -> Vec<Range<DisplayPoint>> {
14130        display_snapshot
14131            .buffer_snapshot
14132            .redacted_ranges(search_range, |file| {
14133                if let Some(file) = file {
14134                    file.is_private()
14135                        && EditorSettings::get(
14136                            Some(SettingsLocation {
14137                                worktree_id: file.worktree_id(cx),
14138                                path: file.path().as_ref(),
14139                            }),
14140                            cx,
14141                        )
14142                        .redact_private_values
14143                } else {
14144                    false
14145                }
14146            })
14147            .map(|range| {
14148                range.start.to_display_point(display_snapshot)
14149                    ..range.end.to_display_point(display_snapshot)
14150            })
14151            .collect()
14152    }
14153
14154    pub fn highlight_text<T: 'static>(
14155        &mut self,
14156        ranges: Vec<Range<Anchor>>,
14157        style: HighlightStyle,
14158        cx: &mut Context<Self>,
14159    ) {
14160        self.display_map.update(cx, |map, _| {
14161            map.highlight_text(TypeId::of::<T>(), ranges, style)
14162        });
14163        cx.notify();
14164    }
14165
14166    pub(crate) fn highlight_inlays<T: 'static>(
14167        &mut self,
14168        highlights: Vec<InlayHighlight>,
14169        style: HighlightStyle,
14170        cx: &mut Context<Self>,
14171    ) {
14172        self.display_map.update(cx, |map, _| {
14173            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14174        });
14175        cx.notify();
14176    }
14177
14178    pub fn text_highlights<'a, T: 'static>(
14179        &'a self,
14180        cx: &'a App,
14181    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14182        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14183    }
14184
14185    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14186        let cleared = self
14187            .display_map
14188            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14189        if cleared {
14190            cx.notify();
14191        }
14192    }
14193
14194    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14195        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14196            && self.focus_handle.is_focused(window)
14197    }
14198
14199    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14200        self.show_cursor_when_unfocused = is_enabled;
14201        cx.notify();
14202    }
14203
14204    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14205        cx.notify();
14206    }
14207
14208    fn on_buffer_event(
14209        &mut self,
14210        multibuffer: &Entity<MultiBuffer>,
14211        event: &multi_buffer::Event,
14212        window: &mut Window,
14213        cx: &mut Context<Self>,
14214    ) {
14215        match event {
14216            multi_buffer::Event::Edited {
14217                singleton_buffer_edited,
14218                edited_buffer: buffer_edited,
14219            } => {
14220                self.scrollbar_marker_state.dirty = true;
14221                self.active_indent_guides_state.dirty = true;
14222                self.refresh_active_diagnostics(cx);
14223                self.refresh_code_actions(window, cx);
14224                if self.has_active_inline_completion() {
14225                    self.update_visible_inline_completion(window, cx);
14226                }
14227                if let Some(buffer) = buffer_edited {
14228                    let buffer_id = buffer.read(cx).remote_id();
14229                    if !self.registered_buffers.contains_key(&buffer_id) {
14230                        if let Some(project) = self.project.as_ref() {
14231                            project.update(cx, |project, cx| {
14232                                self.registered_buffers.insert(
14233                                    buffer_id,
14234                                    project.register_buffer_with_language_servers(&buffer, cx),
14235                                );
14236                            })
14237                        }
14238                    }
14239                }
14240                cx.emit(EditorEvent::BufferEdited);
14241                cx.emit(SearchEvent::MatchesInvalidated);
14242                if *singleton_buffer_edited {
14243                    if let Some(project) = &self.project {
14244                        #[allow(clippy::mutable_key_type)]
14245                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14246                            multibuffer
14247                                .all_buffers()
14248                                .into_iter()
14249                                .filter_map(|buffer| {
14250                                    buffer.update(cx, |buffer, cx| {
14251                                        let language = buffer.language()?;
14252                                        let should_discard = project.update(cx, |project, cx| {
14253                                            project.is_local()
14254                                                && !project.has_language_servers_for(buffer, cx)
14255                                        });
14256                                        should_discard.not().then_some(language.clone())
14257                                    })
14258                                })
14259                                .collect::<HashSet<_>>()
14260                        });
14261                        if !languages_affected.is_empty() {
14262                            self.refresh_inlay_hints(
14263                                InlayHintRefreshReason::BufferEdited(languages_affected),
14264                                cx,
14265                            );
14266                        }
14267                    }
14268                }
14269
14270                let Some(project) = &self.project else { return };
14271                let (telemetry, is_via_ssh) = {
14272                    let project = project.read(cx);
14273                    let telemetry = project.client().telemetry().clone();
14274                    let is_via_ssh = project.is_via_ssh();
14275                    (telemetry, is_via_ssh)
14276                };
14277                refresh_linked_ranges(self, window, cx);
14278                telemetry.log_edit_event("editor", is_via_ssh);
14279            }
14280            multi_buffer::Event::ExcerptsAdded {
14281                buffer,
14282                predecessor,
14283                excerpts,
14284            } => {
14285                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14286                let buffer_id = buffer.read(cx).remote_id();
14287                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14288                    if let Some(project) = &self.project {
14289                        get_uncommitted_diff_for_buffer(
14290                            project,
14291                            [buffer.clone()],
14292                            self.buffer.clone(),
14293                            cx,
14294                        )
14295                        .detach();
14296                    }
14297                }
14298                cx.emit(EditorEvent::ExcerptsAdded {
14299                    buffer: buffer.clone(),
14300                    predecessor: *predecessor,
14301                    excerpts: excerpts.clone(),
14302                });
14303                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14304            }
14305            multi_buffer::Event::ExcerptsRemoved { ids } => {
14306                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14307                let buffer = self.buffer.read(cx);
14308                self.registered_buffers
14309                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14310                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14311            }
14312            multi_buffer::Event::ExcerptsEdited { ids } => {
14313                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14314            }
14315            multi_buffer::Event::ExcerptsExpanded { ids } => {
14316                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14317                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14318            }
14319            multi_buffer::Event::Reparsed(buffer_id) => {
14320                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14321
14322                cx.emit(EditorEvent::Reparsed(*buffer_id));
14323            }
14324            multi_buffer::Event::DiffHunksToggled => {
14325                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14326            }
14327            multi_buffer::Event::LanguageChanged(buffer_id) => {
14328                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14329                cx.emit(EditorEvent::Reparsed(*buffer_id));
14330                cx.notify();
14331            }
14332            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14333            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14334            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14335                cx.emit(EditorEvent::TitleChanged)
14336            }
14337            // multi_buffer::Event::DiffBaseChanged => {
14338            //     self.scrollbar_marker_state.dirty = true;
14339            //     cx.emit(EditorEvent::DiffBaseChanged);
14340            //     cx.notify();
14341            // }
14342            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14343            multi_buffer::Event::DiagnosticsUpdated => {
14344                self.refresh_active_diagnostics(cx);
14345                self.scrollbar_marker_state.dirty = true;
14346                cx.notify();
14347            }
14348            _ => {}
14349        };
14350    }
14351
14352    fn on_display_map_changed(
14353        &mut self,
14354        _: Entity<DisplayMap>,
14355        _: &mut Window,
14356        cx: &mut Context<Self>,
14357    ) {
14358        cx.notify();
14359    }
14360
14361    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14362        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14363        self.refresh_inline_completion(true, false, window, cx);
14364        self.refresh_inlay_hints(
14365            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14366                self.selections.newest_anchor().head(),
14367                &self.buffer.read(cx).snapshot(cx),
14368                cx,
14369            )),
14370            cx,
14371        );
14372
14373        let old_cursor_shape = self.cursor_shape;
14374
14375        {
14376            let editor_settings = EditorSettings::get_global(cx);
14377            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14378            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14379            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14380        }
14381
14382        if old_cursor_shape != self.cursor_shape {
14383            cx.emit(EditorEvent::CursorShapeChanged);
14384        }
14385
14386        let project_settings = ProjectSettings::get_global(cx);
14387        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14388
14389        if self.mode == EditorMode::Full {
14390            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14391            if self.git_blame_inline_enabled != inline_blame_enabled {
14392                self.toggle_git_blame_inline_internal(false, window, cx);
14393            }
14394        }
14395
14396        cx.notify();
14397    }
14398
14399    pub fn set_searchable(&mut self, searchable: bool) {
14400        self.searchable = searchable;
14401    }
14402
14403    pub fn searchable(&self) -> bool {
14404        self.searchable
14405    }
14406
14407    fn open_proposed_changes_editor(
14408        &mut self,
14409        _: &OpenProposedChangesEditor,
14410        window: &mut Window,
14411        cx: &mut Context<Self>,
14412    ) {
14413        let Some(workspace) = self.workspace() else {
14414            cx.propagate();
14415            return;
14416        };
14417
14418        let selections = self.selections.all::<usize>(cx);
14419        let multi_buffer = self.buffer.read(cx);
14420        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14421        let mut new_selections_by_buffer = HashMap::default();
14422        for selection in selections {
14423            for (buffer, range, _) in
14424                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14425            {
14426                let mut range = range.to_point(buffer);
14427                range.start.column = 0;
14428                range.end.column = buffer.line_len(range.end.row);
14429                new_selections_by_buffer
14430                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14431                    .or_insert(Vec::new())
14432                    .push(range)
14433            }
14434        }
14435
14436        let proposed_changes_buffers = new_selections_by_buffer
14437            .into_iter()
14438            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14439            .collect::<Vec<_>>();
14440        let proposed_changes_editor = cx.new(|cx| {
14441            ProposedChangesEditor::new(
14442                "Proposed changes",
14443                proposed_changes_buffers,
14444                self.project.clone(),
14445                window,
14446                cx,
14447            )
14448        });
14449
14450        window.defer(cx, move |window, cx| {
14451            workspace.update(cx, |workspace, cx| {
14452                workspace.active_pane().update(cx, |pane, cx| {
14453                    pane.add_item(
14454                        Box::new(proposed_changes_editor),
14455                        true,
14456                        true,
14457                        None,
14458                        window,
14459                        cx,
14460                    );
14461                });
14462            });
14463        });
14464    }
14465
14466    pub fn open_excerpts_in_split(
14467        &mut self,
14468        _: &OpenExcerptsSplit,
14469        window: &mut Window,
14470        cx: &mut Context<Self>,
14471    ) {
14472        self.open_excerpts_common(None, true, window, cx)
14473    }
14474
14475    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14476        self.open_excerpts_common(None, false, window, cx)
14477    }
14478
14479    fn open_excerpts_common(
14480        &mut self,
14481        jump_data: Option<JumpData>,
14482        split: bool,
14483        window: &mut Window,
14484        cx: &mut Context<Self>,
14485    ) {
14486        let Some(workspace) = self.workspace() else {
14487            cx.propagate();
14488            return;
14489        };
14490
14491        if self.buffer.read(cx).is_singleton() {
14492            cx.propagate();
14493            return;
14494        }
14495
14496        let mut new_selections_by_buffer = HashMap::default();
14497        match &jump_data {
14498            Some(JumpData::MultiBufferPoint {
14499                excerpt_id,
14500                position,
14501                anchor,
14502                line_offset_from_top,
14503            }) => {
14504                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14505                if let Some(buffer) = multi_buffer_snapshot
14506                    .buffer_id_for_excerpt(*excerpt_id)
14507                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14508                {
14509                    let buffer_snapshot = buffer.read(cx).snapshot();
14510                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14511                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14512                    } else {
14513                        buffer_snapshot.clip_point(*position, Bias::Left)
14514                    };
14515                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14516                    new_selections_by_buffer.insert(
14517                        buffer,
14518                        (
14519                            vec![jump_to_offset..jump_to_offset],
14520                            Some(*line_offset_from_top),
14521                        ),
14522                    );
14523                }
14524            }
14525            Some(JumpData::MultiBufferRow {
14526                row,
14527                line_offset_from_top,
14528            }) => {
14529                let point = MultiBufferPoint::new(row.0, 0);
14530                if let Some((buffer, buffer_point, _)) =
14531                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14532                {
14533                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14534                    new_selections_by_buffer
14535                        .entry(buffer)
14536                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14537                        .0
14538                        .push(buffer_offset..buffer_offset)
14539                }
14540            }
14541            None => {
14542                let selections = self.selections.all::<usize>(cx);
14543                let multi_buffer = self.buffer.read(cx);
14544                for selection in selections {
14545                    for (buffer, mut range, _) in multi_buffer
14546                        .snapshot(cx)
14547                        .range_to_buffer_ranges(selection.range())
14548                    {
14549                        // When editing branch buffers, jump to the corresponding location
14550                        // in their base buffer.
14551                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14552                        let buffer = buffer_handle.read(cx);
14553                        if let Some(base_buffer) = buffer.base_buffer() {
14554                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14555                            buffer_handle = base_buffer;
14556                        }
14557
14558                        if selection.reversed {
14559                            mem::swap(&mut range.start, &mut range.end);
14560                        }
14561                        new_selections_by_buffer
14562                            .entry(buffer_handle)
14563                            .or_insert((Vec::new(), None))
14564                            .0
14565                            .push(range)
14566                    }
14567                }
14568            }
14569        }
14570
14571        if new_selections_by_buffer.is_empty() {
14572            return;
14573        }
14574
14575        // We defer the pane interaction because we ourselves are a workspace item
14576        // and activating a new item causes the pane to call a method on us reentrantly,
14577        // which panics if we're on the stack.
14578        window.defer(cx, move |window, cx| {
14579            workspace.update(cx, |workspace, cx| {
14580                let pane = if split {
14581                    workspace.adjacent_pane(window, cx)
14582                } else {
14583                    workspace.active_pane().clone()
14584                };
14585
14586                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14587                    let editor = buffer
14588                        .read(cx)
14589                        .file()
14590                        .is_none()
14591                        .then(|| {
14592                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14593                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14594                            // Instead, we try to activate the existing editor in the pane first.
14595                            let (editor, pane_item_index) =
14596                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14597                                    let editor = item.downcast::<Editor>()?;
14598                                    let singleton_buffer =
14599                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14600                                    if singleton_buffer == buffer {
14601                                        Some((editor, i))
14602                                    } else {
14603                                        None
14604                                    }
14605                                })?;
14606                            pane.update(cx, |pane, cx| {
14607                                pane.activate_item(pane_item_index, true, true, window, cx)
14608                            });
14609                            Some(editor)
14610                        })
14611                        .flatten()
14612                        .unwrap_or_else(|| {
14613                            workspace.open_project_item::<Self>(
14614                                pane.clone(),
14615                                buffer,
14616                                true,
14617                                true,
14618                                window,
14619                                cx,
14620                            )
14621                        });
14622
14623                    editor.update(cx, |editor, cx| {
14624                        let autoscroll = match scroll_offset {
14625                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14626                            None => Autoscroll::newest(),
14627                        };
14628                        let nav_history = editor.nav_history.take();
14629                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14630                            s.select_ranges(ranges);
14631                        });
14632                        editor.nav_history = nav_history;
14633                    });
14634                }
14635            })
14636        });
14637    }
14638
14639    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14640        let snapshot = self.buffer.read(cx).read(cx);
14641        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14642        Some(
14643            ranges
14644                .iter()
14645                .map(move |range| {
14646                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14647                })
14648                .collect(),
14649        )
14650    }
14651
14652    fn selection_replacement_ranges(
14653        &self,
14654        range: Range<OffsetUtf16>,
14655        cx: &mut App,
14656    ) -> Vec<Range<OffsetUtf16>> {
14657        let selections = self.selections.all::<OffsetUtf16>(cx);
14658        let newest_selection = selections
14659            .iter()
14660            .max_by_key(|selection| selection.id)
14661            .unwrap();
14662        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14663        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14664        let snapshot = self.buffer.read(cx).read(cx);
14665        selections
14666            .into_iter()
14667            .map(|mut selection| {
14668                selection.start.0 =
14669                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14670                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14671                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14672                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14673            })
14674            .collect()
14675    }
14676
14677    fn report_editor_event(
14678        &self,
14679        event_type: &'static str,
14680        file_extension: Option<String>,
14681        cx: &App,
14682    ) {
14683        if cfg!(any(test, feature = "test-support")) {
14684            return;
14685        }
14686
14687        let Some(project) = &self.project else { return };
14688
14689        // If None, we are in a file without an extension
14690        let file = self
14691            .buffer
14692            .read(cx)
14693            .as_singleton()
14694            .and_then(|b| b.read(cx).file());
14695        let file_extension = file_extension.or(file
14696            .as_ref()
14697            .and_then(|file| Path::new(file.file_name(cx)).extension())
14698            .and_then(|e| e.to_str())
14699            .map(|a| a.to_string()));
14700
14701        let vim_mode = cx
14702            .global::<SettingsStore>()
14703            .raw_user_settings()
14704            .get("vim_mode")
14705            == Some(&serde_json::Value::Bool(true));
14706
14707        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14708        let copilot_enabled = edit_predictions_provider
14709            == language::language_settings::EditPredictionProvider::Copilot;
14710        let copilot_enabled_for_language = self
14711            .buffer
14712            .read(cx)
14713            .settings_at(0, cx)
14714            .show_edit_predictions;
14715
14716        let project = project.read(cx);
14717        telemetry::event!(
14718            event_type,
14719            file_extension,
14720            vim_mode,
14721            copilot_enabled,
14722            copilot_enabled_for_language,
14723            edit_predictions_provider,
14724            is_via_ssh = project.is_via_ssh(),
14725        );
14726    }
14727
14728    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14729    /// with each line being an array of {text, highlight} objects.
14730    fn copy_highlight_json(
14731        &mut self,
14732        _: &CopyHighlightJson,
14733        window: &mut Window,
14734        cx: &mut Context<Self>,
14735    ) {
14736        #[derive(Serialize)]
14737        struct Chunk<'a> {
14738            text: String,
14739            highlight: Option<&'a str>,
14740        }
14741
14742        let snapshot = self.buffer.read(cx).snapshot(cx);
14743        let range = self
14744            .selected_text_range(false, window, cx)
14745            .and_then(|selection| {
14746                if selection.range.is_empty() {
14747                    None
14748                } else {
14749                    Some(selection.range)
14750                }
14751            })
14752            .unwrap_or_else(|| 0..snapshot.len());
14753
14754        let chunks = snapshot.chunks(range, true);
14755        let mut lines = Vec::new();
14756        let mut line: VecDeque<Chunk> = VecDeque::new();
14757
14758        let Some(style) = self.style.as_ref() else {
14759            return;
14760        };
14761
14762        for chunk in chunks {
14763            let highlight = chunk
14764                .syntax_highlight_id
14765                .and_then(|id| id.name(&style.syntax));
14766            let mut chunk_lines = chunk.text.split('\n').peekable();
14767            while let Some(text) = chunk_lines.next() {
14768                let mut merged_with_last_token = false;
14769                if let Some(last_token) = line.back_mut() {
14770                    if last_token.highlight == highlight {
14771                        last_token.text.push_str(text);
14772                        merged_with_last_token = true;
14773                    }
14774                }
14775
14776                if !merged_with_last_token {
14777                    line.push_back(Chunk {
14778                        text: text.into(),
14779                        highlight,
14780                    });
14781                }
14782
14783                if chunk_lines.peek().is_some() {
14784                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14785                        line.pop_front();
14786                    }
14787                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14788                        line.pop_back();
14789                    }
14790
14791                    lines.push(mem::take(&mut line));
14792                }
14793            }
14794        }
14795
14796        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14797            return;
14798        };
14799        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14800    }
14801
14802    pub fn open_context_menu(
14803        &mut self,
14804        _: &OpenContextMenu,
14805        window: &mut Window,
14806        cx: &mut Context<Self>,
14807    ) {
14808        self.request_autoscroll(Autoscroll::newest(), cx);
14809        let position = self.selections.newest_display(cx).start;
14810        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14811    }
14812
14813    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14814        &self.inlay_hint_cache
14815    }
14816
14817    pub fn replay_insert_event(
14818        &mut self,
14819        text: &str,
14820        relative_utf16_range: Option<Range<isize>>,
14821        window: &mut Window,
14822        cx: &mut Context<Self>,
14823    ) {
14824        if !self.input_enabled {
14825            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14826            return;
14827        }
14828        if let Some(relative_utf16_range) = relative_utf16_range {
14829            let selections = self.selections.all::<OffsetUtf16>(cx);
14830            self.change_selections(None, window, cx, |s| {
14831                let new_ranges = selections.into_iter().map(|range| {
14832                    let start = OffsetUtf16(
14833                        range
14834                            .head()
14835                            .0
14836                            .saturating_add_signed(relative_utf16_range.start),
14837                    );
14838                    let end = OffsetUtf16(
14839                        range
14840                            .head()
14841                            .0
14842                            .saturating_add_signed(relative_utf16_range.end),
14843                    );
14844                    start..end
14845                });
14846                s.select_ranges(new_ranges);
14847            });
14848        }
14849
14850        self.handle_input(text, window, cx);
14851    }
14852
14853    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14854        let Some(provider) = self.semantics_provider.as_ref() else {
14855            return false;
14856        };
14857
14858        let mut supports = false;
14859        self.buffer().update(cx, |this, cx| {
14860            this.for_each_buffer(|buffer| {
14861                supports |= provider.supports_inlay_hints(buffer, cx);
14862            });
14863        });
14864
14865        supports
14866    }
14867
14868    pub fn is_focused(&self, window: &Window) -> bool {
14869        self.focus_handle.is_focused(window)
14870    }
14871
14872    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14873        cx.emit(EditorEvent::Focused);
14874
14875        if let Some(descendant) = self
14876            .last_focused_descendant
14877            .take()
14878            .and_then(|descendant| descendant.upgrade())
14879        {
14880            window.focus(&descendant);
14881        } else {
14882            if let Some(blame) = self.blame.as_ref() {
14883                blame.update(cx, GitBlame::focus)
14884            }
14885
14886            self.blink_manager.update(cx, BlinkManager::enable);
14887            self.show_cursor_names(window, cx);
14888            self.buffer.update(cx, |buffer, cx| {
14889                buffer.finalize_last_transaction(cx);
14890                if self.leader_peer_id.is_none() {
14891                    buffer.set_active_selections(
14892                        &self.selections.disjoint_anchors(),
14893                        self.selections.line_mode,
14894                        self.cursor_shape,
14895                        cx,
14896                    );
14897                }
14898            });
14899        }
14900    }
14901
14902    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14903        cx.emit(EditorEvent::FocusedIn)
14904    }
14905
14906    fn handle_focus_out(
14907        &mut self,
14908        event: FocusOutEvent,
14909        _window: &mut Window,
14910        _cx: &mut Context<Self>,
14911    ) {
14912        if event.blurred != self.focus_handle {
14913            self.last_focused_descendant = Some(event.blurred);
14914        }
14915    }
14916
14917    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14918        self.blink_manager.update(cx, BlinkManager::disable);
14919        self.buffer
14920            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14921
14922        if let Some(blame) = self.blame.as_ref() {
14923            blame.update(cx, GitBlame::blur)
14924        }
14925        if !self.hover_state.focused(window, cx) {
14926            hide_hover(self, cx);
14927        }
14928
14929        self.hide_context_menu(window, cx);
14930        self.discard_inline_completion(false, cx);
14931        cx.emit(EditorEvent::Blurred);
14932        cx.notify();
14933    }
14934
14935    pub fn register_action<A: Action>(
14936        &mut self,
14937        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14938    ) -> Subscription {
14939        let id = self.next_editor_action_id.post_inc();
14940        let listener = Arc::new(listener);
14941        self.editor_actions.borrow_mut().insert(
14942            id,
14943            Box::new(move |window, _| {
14944                let listener = listener.clone();
14945                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14946                    let action = action.downcast_ref().unwrap();
14947                    if phase == DispatchPhase::Bubble {
14948                        listener(action, window, cx)
14949                    }
14950                })
14951            }),
14952        );
14953
14954        let editor_actions = self.editor_actions.clone();
14955        Subscription::new(move || {
14956            editor_actions.borrow_mut().remove(&id);
14957        })
14958    }
14959
14960    pub fn file_header_size(&self) -> u32 {
14961        FILE_HEADER_HEIGHT
14962    }
14963
14964    pub fn revert(
14965        &mut self,
14966        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14967        window: &mut Window,
14968        cx: &mut Context<Self>,
14969    ) {
14970        self.buffer().update(cx, |multi_buffer, cx| {
14971            for (buffer_id, changes) in revert_changes {
14972                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14973                    buffer.update(cx, |buffer, cx| {
14974                        buffer.edit(
14975                            changes.into_iter().map(|(range, text)| {
14976                                (range, text.to_string().map(Arc::<str>::from))
14977                            }),
14978                            None,
14979                            cx,
14980                        );
14981                    });
14982                }
14983            }
14984        });
14985        self.change_selections(None, window, cx, |selections| selections.refresh());
14986    }
14987
14988    pub fn to_pixel_point(
14989        &self,
14990        source: multi_buffer::Anchor,
14991        editor_snapshot: &EditorSnapshot,
14992        window: &mut Window,
14993    ) -> Option<gpui::Point<Pixels>> {
14994        let source_point = source.to_display_point(editor_snapshot);
14995        self.display_to_pixel_point(source_point, editor_snapshot, window)
14996    }
14997
14998    pub fn display_to_pixel_point(
14999        &self,
15000        source: DisplayPoint,
15001        editor_snapshot: &EditorSnapshot,
15002        window: &mut Window,
15003    ) -> Option<gpui::Point<Pixels>> {
15004        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15005        let text_layout_details = self.text_layout_details(window);
15006        let scroll_top = text_layout_details
15007            .scroll_anchor
15008            .scroll_position(editor_snapshot)
15009            .y;
15010
15011        if source.row().as_f32() < scroll_top.floor() {
15012            return None;
15013        }
15014        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15015        let source_y = line_height * (source.row().as_f32() - scroll_top);
15016        Some(gpui::Point::new(source_x, source_y))
15017    }
15018
15019    pub fn has_visible_completions_menu(&self) -> bool {
15020        !self.edit_prediction_preview_is_active()
15021            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15022                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15023            })
15024    }
15025
15026    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15027        self.addons
15028            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15029    }
15030
15031    pub fn unregister_addon<T: Addon>(&mut self) {
15032        self.addons.remove(&std::any::TypeId::of::<T>());
15033    }
15034
15035    pub fn addon<T: Addon>(&self) -> Option<&T> {
15036        let type_id = std::any::TypeId::of::<T>();
15037        self.addons
15038            .get(&type_id)
15039            .and_then(|item| item.to_any().downcast_ref::<T>())
15040    }
15041
15042    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15043        let text_layout_details = self.text_layout_details(window);
15044        let style = &text_layout_details.editor_style;
15045        let font_id = window.text_system().resolve_font(&style.text.font());
15046        let font_size = style.text.font_size.to_pixels(window.rem_size());
15047        let line_height = style.text.line_height_in_pixels(window.rem_size());
15048        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15049
15050        gpui::Size::new(em_width, line_height)
15051    }
15052
15053    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15054        self.load_diff_task.clone()
15055    }
15056
15057    fn read_selections_from_db(
15058        &mut self,
15059        item_id: u64,
15060        workspace_id: WorkspaceId,
15061        window: &mut Window,
15062        cx: &mut Context<Editor>,
15063    ) {
15064        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
15065            return;
15066        }
15067        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15068            return;
15069        };
15070        if selections.is_empty() {
15071            return;
15072        }
15073
15074        let snapshot = self.buffer.read(cx).snapshot(cx);
15075        self.change_selections(None, window, cx, |s| {
15076            s.select_ranges(selections.into_iter().map(|(start, end)| {
15077                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15078            }));
15079        });
15080    }
15081}
15082
15083fn get_uncommitted_diff_for_buffer(
15084    project: &Entity<Project>,
15085    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15086    buffer: Entity<MultiBuffer>,
15087    cx: &mut App,
15088) -> Task<()> {
15089    let mut tasks = Vec::new();
15090    project.update(cx, |project, cx| {
15091        for buffer in buffers {
15092            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15093        }
15094    });
15095    cx.spawn(|mut cx| async move {
15096        let diffs = futures::future::join_all(tasks).await;
15097        buffer
15098            .update(&mut cx, |buffer, cx| {
15099                for diff in diffs.into_iter().flatten() {
15100                    buffer.add_diff(diff, cx);
15101                }
15102            })
15103            .ok();
15104    })
15105}
15106
15107fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15108    let tab_size = tab_size.get() as usize;
15109    let mut width = offset;
15110
15111    for ch in text.chars() {
15112        width += if ch == '\t' {
15113            tab_size - (width % tab_size)
15114        } else {
15115            1
15116        };
15117    }
15118
15119    width - offset
15120}
15121
15122#[cfg(test)]
15123mod tests {
15124    use super::*;
15125
15126    #[test]
15127    fn test_string_size_with_expanded_tabs() {
15128        let nz = |val| NonZeroU32::new(val).unwrap();
15129        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15130        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15131        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15132        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15133        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15134        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15135        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15136        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15137    }
15138}
15139
15140/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15141struct WordBreakingTokenizer<'a> {
15142    input: &'a str,
15143}
15144
15145impl<'a> WordBreakingTokenizer<'a> {
15146    fn new(input: &'a str) -> Self {
15147        Self { input }
15148    }
15149}
15150
15151fn is_char_ideographic(ch: char) -> bool {
15152    use unicode_script::Script::*;
15153    use unicode_script::UnicodeScript;
15154    matches!(ch.script(), Han | Tangut | Yi)
15155}
15156
15157fn is_grapheme_ideographic(text: &str) -> bool {
15158    text.chars().any(is_char_ideographic)
15159}
15160
15161fn is_grapheme_whitespace(text: &str) -> bool {
15162    text.chars().any(|x| x.is_whitespace())
15163}
15164
15165fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15166    text.chars().next().map_or(false, |ch| {
15167        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15168    })
15169}
15170
15171#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15172struct WordBreakToken<'a> {
15173    token: &'a str,
15174    grapheme_len: usize,
15175    is_whitespace: bool,
15176}
15177
15178impl<'a> Iterator for WordBreakingTokenizer<'a> {
15179    /// Yields a span, the count of graphemes in the token, and whether it was
15180    /// whitespace. Note that it also breaks at word boundaries.
15181    type Item = WordBreakToken<'a>;
15182
15183    fn next(&mut self) -> Option<Self::Item> {
15184        use unicode_segmentation::UnicodeSegmentation;
15185        if self.input.is_empty() {
15186            return None;
15187        }
15188
15189        let mut iter = self.input.graphemes(true).peekable();
15190        let mut offset = 0;
15191        let mut graphemes = 0;
15192        if let Some(first_grapheme) = iter.next() {
15193            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15194            offset += first_grapheme.len();
15195            graphemes += 1;
15196            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15197                if let Some(grapheme) = iter.peek().copied() {
15198                    if should_stay_with_preceding_ideograph(grapheme) {
15199                        offset += grapheme.len();
15200                        graphemes += 1;
15201                    }
15202                }
15203            } else {
15204                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15205                let mut next_word_bound = words.peek().copied();
15206                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15207                    next_word_bound = words.next();
15208                }
15209                while let Some(grapheme) = iter.peek().copied() {
15210                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15211                        break;
15212                    };
15213                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15214                        break;
15215                    };
15216                    offset += grapheme.len();
15217                    graphemes += 1;
15218                    iter.next();
15219                }
15220            }
15221            let token = &self.input[..offset];
15222            self.input = &self.input[offset..];
15223            if is_whitespace {
15224                Some(WordBreakToken {
15225                    token: " ",
15226                    grapheme_len: 1,
15227                    is_whitespace: true,
15228                })
15229            } else {
15230                Some(WordBreakToken {
15231                    token,
15232                    grapheme_len: graphemes,
15233                    is_whitespace: false,
15234                })
15235            }
15236        } else {
15237            None
15238        }
15239    }
15240}
15241
15242#[test]
15243fn test_word_breaking_tokenizer() {
15244    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15245        ("", &[]),
15246        ("  ", &[(" ", 1, true)]),
15247        ("Ʒ", &[("Ʒ", 1, false)]),
15248        ("Ǽ", &[("Ǽ", 1, false)]),
15249        ("", &[("", 1, false)]),
15250        ("⋑⋑", &[("⋑⋑", 2, false)]),
15251        (
15252            "原理,进而",
15253            &[
15254                ("", 1, false),
15255                ("理,", 2, false),
15256                ("", 1, false),
15257                ("", 1, false),
15258            ],
15259        ),
15260        (
15261            "hello world",
15262            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15263        ),
15264        (
15265            "hello, world",
15266            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15267        ),
15268        (
15269            "  hello world",
15270            &[
15271                (" ", 1, true),
15272                ("hello", 5, false),
15273                (" ", 1, true),
15274                ("world", 5, false),
15275            ],
15276        ),
15277        (
15278            "这是什么 \n 钢笔",
15279            &[
15280                ("", 1, false),
15281                ("", 1, false),
15282                ("", 1, false),
15283                ("", 1, false),
15284                (" ", 1, true),
15285                ("", 1, false),
15286                ("", 1, false),
15287            ],
15288        ),
15289        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15290    ];
15291
15292    for (input, result) in tests {
15293        assert_eq!(
15294            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15295            result
15296                .iter()
15297                .copied()
15298                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15299                    token,
15300                    grapheme_len,
15301                    is_whitespace,
15302                })
15303                .collect::<Vec<_>>()
15304        );
15305    }
15306}
15307
15308fn wrap_with_prefix(
15309    line_prefix: String,
15310    unwrapped_text: String,
15311    wrap_column: usize,
15312    tab_size: NonZeroU32,
15313) -> String {
15314    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15315    let mut wrapped_text = String::new();
15316    let mut current_line = line_prefix.clone();
15317
15318    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15319    let mut current_line_len = line_prefix_len;
15320    for WordBreakToken {
15321        token,
15322        grapheme_len,
15323        is_whitespace,
15324    } in tokenizer
15325    {
15326        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15327            wrapped_text.push_str(current_line.trim_end());
15328            wrapped_text.push('\n');
15329            current_line.truncate(line_prefix.len());
15330            current_line_len = line_prefix_len;
15331            if !is_whitespace {
15332                current_line.push_str(token);
15333                current_line_len += grapheme_len;
15334            }
15335        } else if !is_whitespace {
15336            current_line.push_str(token);
15337            current_line_len += grapheme_len;
15338        } else if current_line_len != line_prefix_len {
15339            current_line.push(' ');
15340            current_line_len += 1;
15341        }
15342    }
15343
15344    if !current_line.is_empty() {
15345        wrapped_text.push_str(&current_line);
15346    }
15347    wrapped_text
15348}
15349
15350#[test]
15351fn test_wrap_with_prefix() {
15352    assert_eq!(
15353        wrap_with_prefix(
15354            "# ".to_string(),
15355            "abcdefg".to_string(),
15356            4,
15357            NonZeroU32::new(4).unwrap()
15358        ),
15359        "# abcdefg"
15360    );
15361    assert_eq!(
15362        wrap_with_prefix(
15363            "".to_string(),
15364            "\thello world".to_string(),
15365            8,
15366            NonZeroU32::new(4).unwrap()
15367        ),
15368        "hello\nworld"
15369    );
15370    assert_eq!(
15371        wrap_with_prefix(
15372            "// ".to_string(),
15373            "xx \nyy zz aa bb cc".to_string(),
15374            12,
15375            NonZeroU32::new(4).unwrap()
15376        ),
15377        "// xx yy zz\n// aa bb cc"
15378    );
15379    assert_eq!(
15380        wrap_with_prefix(
15381            String::new(),
15382            "这是什么 \n 钢笔".to_string(),
15383            3,
15384            NonZeroU32::new(4).unwrap()
15385        ),
15386        "这是什\n么 钢\n"
15387    );
15388}
15389
15390pub trait CollaborationHub {
15391    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15392    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15393    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15394}
15395
15396impl CollaborationHub for Entity<Project> {
15397    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15398        self.read(cx).collaborators()
15399    }
15400
15401    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15402        self.read(cx).user_store().read(cx).participant_indices()
15403    }
15404
15405    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15406        let this = self.read(cx);
15407        let user_ids = this.collaborators().values().map(|c| c.user_id);
15408        this.user_store().read_with(cx, |user_store, cx| {
15409            user_store.participant_names(user_ids, cx)
15410        })
15411    }
15412}
15413
15414pub trait SemanticsProvider {
15415    fn hover(
15416        &self,
15417        buffer: &Entity<Buffer>,
15418        position: text::Anchor,
15419        cx: &mut App,
15420    ) -> Option<Task<Vec<project::Hover>>>;
15421
15422    fn inlay_hints(
15423        &self,
15424        buffer_handle: Entity<Buffer>,
15425        range: Range<text::Anchor>,
15426        cx: &mut App,
15427    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15428
15429    fn resolve_inlay_hint(
15430        &self,
15431        hint: InlayHint,
15432        buffer_handle: Entity<Buffer>,
15433        server_id: LanguageServerId,
15434        cx: &mut App,
15435    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15436
15437    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15438
15439    fn document_highlights(
15440        &self,
15441        buffer: &Entity<Buffer>,
15442        position: text::Anchor,
15443        cx: &mut App,
15444    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15445
15446    fn definitions(
15447        &self,
15448        buffer: &Entity<Buffer>,
15449        position: text::Anchor,
15450        kind: GotoDefinitionKind,
15451        cx: &mut App,
15452    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15453
15454    fn range_for_rename(
15455        &self,
15456        buffer: &Entity<Buffer>,
15457        position: text::Anchor,
15458        cx: &mut App,
15459    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15460
15461    fn perform_rename(
15462        &self,
15463        buffer: &Entity<Buffer>,
15464        position: text::Anchor,
15465        new_name: String,
15466        cx: &mut App,
15467    ) -> Option<Task<Result<ProjectTransaction>>>;
15468}
15469
15470pub trait CompletionProvider {
15471    fn completions(
15472        &self,
15473        buffer: &Entity<Buffer>,
15474        buffer_position: text::Anchor,
15475        trigger: CompletionContext,
15476        window: &mut Window,
15477        cx: &mut Context<Editor>,
15478    ) -> Task<Result<Vec<Completion>>>;
15479
15480    fn resolve_completions(
15481        &self,
15482        buffer: Entity<Buffer>,
15483        completion_indices: Vec<usize>,
15484        completions: Rc<RefCell<Box<[Completion]>>>,
15485        cx: &mut Context<Editor>,
15486    ) -> Task<Result<bool>>;
15487
15488    fn apply_additional_edits_for_completion(
15489        &self,
15490        _buffer: Entity<Buffer>,
15491        _completions: Rc<RefCell<Box<[Completion]>>>,
15492        _completion_index: usize,
15493        _push_to_history: bool,
15494        _cx: &mut Context<Editor>,
15495    ) -> Task<Result<Option<language::Transaction>>> {
15496        Task::ready(Ok(None))
15497    }
15498
15499    fn is_completion_trigger(
15500        &self,
15501        buffer: &Entity<Buffer>,
15502        position: language::Anchor,
15503        text: &str,
15504        trigger_in_words: bool,
15505        cx: &mut Context<Editor>,
15506    ) -> bool;
15507
15508    fn sort_completions(&self) -> bool {
15509        true
15510    }
15511}
15512
15513pub trait CodeActionProvider {
15514    fn id(&self) -> Arc<str>;
15515
15516    fn code_actions(
15517        &self,
15518        buffer: &Entity<Buffer>,
15519        range: Range<text::Anchor>,
15520        window: &mut Window,
15521        cx: &mut App,
15522    ) -> Task<Result<Vec<CodeAction>>>;
15523
15524    fn apply_code_action(
15525        &self,
15526        buffer_handle: Entity<Buffer>,
15527        action: CodeAction,
15528        excerpt_id: ExcerptId,
15529        push_to_history: bool,
15530        window: &mut Window,
15531        cx: &mut App,
15532    ) -> Task<Result<ProjectTransaction>>;
15533}
15534
15535impl CodeActionProvider for Entity<Project> {
15536    fn id(&self) -> Arc<str> {
15537        "project".into()
15538    }
15539
15540    fn code_actions(
15541        &self,
15542        buffer: &Entity<Buffer>,
15543        range: Range<text::Anchor>,
15544        _window: &mut Window,
15545        cx: &mut App,
15546    ) -> Task<Result<Vec<CodeAction>>> {
15547        self.update(cx, |project, cx| {
15548            project.code_actions(buffer, range, None, cx)
15549        })
15550    }
15551
15552    fn apply_code_action(
15553        &self,
15554        buffer_handle: Entity<Buffer>,
15555        action: CodeAction,
15556        _excerpt_id: ExcerptId,
15557        push_to_history: bool,
15558        _window: &mut Window,
15559        cx: &mut App,
15560    ) -> Task<Result<ProjectTransaction>> {
15561        self.update(cx, |project, cx| {
15562            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15563        })
15564    }
15565}
15566
15567fn snippet_completions(
15568    project: &Project,
15569    buffer: &Entity<Buffer>,
15570    buffer_position: text::Anchor,
15571    cx: &mut App,
15572) -> Task<Result<Vec<Completion>>> {
15573    let language = buffer.read(cx).language_at(buffer_position);
15574    let language_name = language.as_ref().map(|language| language.lsp_id());
15575    let snippet_store = project.snippets().read(cx);
15576    let snippets = snippet_store.snippets_for(language_name, cx);
15577
15578    if snippets.is_empty() {
15579        return Task::ready(Ok(vec![]));
15580    }
15581    let snapshot = buffer.read(cx).text_snapshot();
15582    let chars: String = snapshot
15583        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15584        .collect();
15585
15586    let scope = language.map(|language| language.default_scope());
15587    let executor = cx.background_executor().clone();
15588
15589    cx.background_spawn(async move {
15590        let classifier = CharClassifier::new(scope).for_completion(true);
15591        let mut last_word = chars
15592            .chars()
15593            .take_while(|c| classifier.is_word(*c))
15594            .collect::<String>();
15595        last_word = last_word.chars().rev().collect();
15596
15597        if last_word.is_empty() {
15598            return Ok(vec![]);
15599        }
15600
15601        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15602        let to_lsp = |point: &text::Anchor| {
15603            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15604            point_to_lsp(end)
15605        };
15606        let lsp_end = to_lsp(&buffer_position);
15607
15608        let candidates = snippets
15609            .iter()
15610            .enumerate()
15611            .flat_map(|(ix, snippet)| {
15612                snippet
15613                    .prefix
15614                    .iter()
15615                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15616            })
15617            .collect::<Vec<StringMatchCandidate>>();
15618
15619        let mut matches = fuzzy::match_strings(
15620            &candidates,
15621            &last_word,
15622            last_word.chars().any(|c| c.is_uppercase()),
15623            100,
15624            &Default::default(),
15625            executor,
15626        )
15627        .await;
15628
15629        // Remove all candidates where the query's start does not match the start of any word in the candidate
15630        if let Some(query_start) = last_word.chars().next() {
15631            matches.retain(|string_match| {
15632                split_words(&string_match.string).any(|word| {
15633                    // Check that the first codepoint of the word as lowercase matches the first
15634                    // codepoint of the query as lowercase
15635                    word.chars()
15636                        .flat_map(|codepoint| codepoint.to_lowercase())
15637                        .zip(query_start.to_lowercase())
15638                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15639                })
15640            });
15641        }
15642
15643        let matched_strings = matches
15644            .into_iter()
15645            .map(|m| m.string)
15646            .collect::<HashSet<_>>();
15647
15648        let result: Vec<Completion> = snippets
15649            .into_iter()
15650            .filter_map(|snippet| {
15651                let matching_prefix = snippet
15652                    .prefix
15653                    .iter()
15654                    .find(|prefix| matched_strings.contains(*prefix))?;
15655                let start = as_offset - last_word.len();
15656                let start = snapshot.anchor_before(start);
15657                let range = start..buffer_position;
15658                let lsp_start = to_lsp(&start);
15659                let lsp_range = lsp::Range {
15660                    start: lsp_start,
15661                    end: lsp_end,
15662                };
15663                Some(Completion {
15664                    old_range: range,
15665                    new_text: snippet.body.clone(),
15666                    resolved: false,
15667                    label: CodeLabel {
15668                        text: matching_prefix.clone(),
15669                        runs: vec![],
15670                        filter_range: 0..matching_prefix.len(),
15671                    },
15672                    server_id: LanguageServerId(usize::MAX),
15673                    documentation: snippet
15674                        .description
15675                        .clone()
15676                        .map(CompletionDocumentation::SingleLine),
15677                    lsp_completion: lsp::CompletionItem {
15678                        label: snippet.prefix.first().unwrap().clone(),
15679                        kind: Some(CompletionItemKind::SNIPPET),
15680                        label_details: snippet.description.as_ref().map(|description| {
15681                            lsp::CompletionItemLabelDetails {
15682                                detail: Some(description.clone()),
15683                                description: None,
15684                            }
15685                        }),
15686                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15687                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15688                            lsp::InsertReplaceEdit {
15689                                new_text: snippet.body.clone(),
15690                                insert: lsp_range,
15691                                replace: lsp_range,
15692                            },
15693                        )),
15694                        filter_text: Some(snippet.body.clone()),
15695                        sort_text: Some(char::MAX.to_string()),
15696                        ..Default::default()
15697                    },
15698                    confirm: None,
15699                })
15700            })
15701            .collect();
15702
15703        Ok(result)
15704    })
15705}
15706
15707impl CompletionProvider for Entity<Project> {
15708    fn completions(
15709        &self,
15710        buffer: &Entity<Buffer>,
15711        buffer_position: text::Anchor,
15712        options: CompletionContext,
15713        _window: &mut Window,
15714        cx: &mut Context<Editor>,
15715    ) -> Task<Result<Vec<Completion>>> {
15716        self.update(cx, |project, cx| {
15717            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15718            let project_completions = project.completions(buffer, buffer_position, options, cx);
15719            cx.background_spawn(async move {
15720                let mut completions = project_completions.await?;
15721                let snippets_completions = snippets.await?;
15722                completions.extend(snippets_completions);
15723                Ok(completions)
15724            })
15725        })
15726    }
15727
15728    fn resolve_completions(
15729        &self,
15730        buffer: Entity<Buffer>,
15731        completion_indices: Vec<usize>,
15732        completions: Rc<RefCell<Box<[Completion]>>>,
15733        cx: &mut Context<Editor>,
15734    ) -> Task<Result<bool>> {
15735        self.update(cx, |project, cx| {
15736            project.lsp_store().update(cx, |lsp_store, cx| {
15737                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15738            })
15739        })
15740    }
15741
15742    fn apply_additional_edits_for_completion(
15743        &self,
15744        buffer: Entity<Buffer>,
15745        completions: Rc<RefCell<Box<[Completion]>>>,
15746        completion_index: usize,
15747        push_to_history: bool,
15748        cx: &mut Context<Editor>,
15749    ) -> Task<Result<Option<language::Transaction>>> {
15750        self.update(cx, |project, cx| {
15751            project.lsp_store().update(cx, |lsp_store, cx| {
15752                lsp_store.apply_additional_edits_for_completion(
15753                    buffer,
15754                    completions,
15755                    completion_index,
15756                    push_to_history,
15757                    cx,
15758                )
15759            })
15760        })
15761    }
15762
15763    fn is_completion_trigger(
15764        &self,
15765        buffer: &Entity<Buffer>,
15766        position: language::Anchor,
15767        text: &str,
15768        trigger_in_words: bool,
15769        cx: &mut Context<Editor>,
15770    ) -> bool {
15771        let mut chars = text.chars();
15772        let char = if let Some(char) = chars.next() {
15773            char
15774        } else {
15775            return false;
15776        };
15777        if chars.next().is_some() {
15778            return false;
15779        }
15780
15781        let buffer = buffer.read(cx);
15782        let snapshot = buffer.snapshot();
15783        if !snapshot.settings_at(position, cx).show_completions_on_input {
15784            return false;
15785        }
15786        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15787        if trigger_in_words && classifier.is_word(char) {
15788            return true;
15789        }
15790
15791        buffer.completion_triggers().contains(text)
15792    }
15793}
15794
15795impl SemanticsProvider for Entity<Project> {
15796    fn hover(
15797        &self,
15798        buffer: &Entity<Buffer>,
15799        position: text::Anchor,
15800        cx: &mut App,
15801    ) -> Option<Task<Vec<project::Hover>>> {
15802        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15803    }
15804
15805    fn document_highlights(
15806        &self,
15807        buffer: &Entity<Buffer>,
15808        position: text::Anchor,
15809        cx: &mut App,
15810    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15811        Some(self.update(cx, |project, cx| {
15812            project.document_highlights(buffer, position, cx)
15813        }))
15814    }
15815
15816    fn definitions(
15817        &self,
15818        buffer: &Entity<Buffer>,
15819        position: text::Anchor,
15820        kind: GotoDefinitionKind,
15821        cx: &mut App,
15822    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15823        Some(self.update(cx, |project, cx| match kind {
15824            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15825            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15826            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15827            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15828        }))
15829    }
15830
15831    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15832        // TODO: make this work for remote projects
15833        self.update(cx, |this, cx| {
15834            buffer.update(cx, |buffer, cx| {
15835                this.any_language_server_supports_inlay_hints(buffer, cx)
15836            })
15837        })
15838    }
15839
15840    fn inlay_hints(
15841        &self,
15842        buffer_handle: Entity<Buffer>,
15843        range: Range<text::Anchor>,
15844        cx: &mut App,
15845    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15846        Some(self.update(cx, |project, cx| {
15847            project.inlay_hints(buffer_handle, range, cx)
15848        }))
15849    }
15850
15851    fn resolve_inlay_hint(
15852        &self,
15853        hint: InlayHint,
15854        buffer_handle: Entity<Buffer>,
15855        server_id: LanguageServerId,
15856        cx: &mut App,
15857    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15858        Some(self.update(cx, |project, cx| {
15859            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15860        }))
15861    }
15862
15863    fn range_for_rename(
15864        &self,
15865        buffer: &Entity<Buffer>,
15866        position: text::Anchor,
15867        cx: &mut App,
15868    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15869        Some(self.update(cx, |project, cx| {
15870            let buffer = buffer.clone();
15871            let task = project.prepare_rename(buffer.clone(), position, cx);
15872            cx.spawn(|_, mut cx| async move {
15873                Ok(match task.await? {
15874                    PrepareRenameResponse::Success(range) => Some(range),
15875                    PrepareRenameResponse::InvalidPosition => None,
15876                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15877                        // Fallback on using TreeSitter info to determine identifier range
15878                        buffer.update(&mut cx, |buffer, _| {
15879                            let snapshot = buffer.snapshot();
15880                            let (range, kind) = snapshot.surrounding_word(position);
15881                            if kind != Some(CharKind::Word) {
15882                                return None;
15883                            }
15884                            Some(
15885                                snapshot.anchor_before(range.start)
15886                                    ..snapshot.anchor_after(range.end),
15887                            )
15888                        })?
15889                    }
15890                })
15891            })
15892        }))
15893    }
15894
15895    fn perform_rename(
15896        &self,
15897        buffer: &Entity<Buffer>,
15898        position: text::Anchor,
15899        new_name: String,
15900        cx: &mut App,
15901    ) -> Option<Task<Result<ProjectTransaction>>> {
15902        Some(self.update(cx, |project, cx| {
15903            project.perform_rename(buffer.clone(), position, new_name, cx)
15904        }))
15905    }
15906}
15907
15908fn inlay_hint_settings(
15909    location: Anchor,
15910    snapshot: &MultiBufferSnapshot,
15911    cx: &mut Context<Editor>,
15912) -> InlayHintSettings {
15913    let file = snapshot.file_at(location);
15914    let language = snapshot.language_at(location).map(|l| l.name());
15915    language_settings(language, file, cx).inlay_hints
15916}
15917
15918fn consume_contiguous_rows(
15919    contiguous_row_selections: &mut Vec<Selection<Point>>,
15920    selection: &Selection<Point>,
15921    display_map: &DisplaySnapshot,
15922    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15923) -> (MultiBufferRow, MultiBufferRow) {
15924    contiguous_row_selections.push(selection.clone());
15925    let start_row = MultiBufferRow(selection.start.row);
15926    let mut end_row = ending_row(selection, display_map);
15927
15928    while let Some(next_selection) = selections.peek() {
15929        if next_selection.start.row <= end_row.0 {
15930            end_row = ending_row(next_selection, display_map);
15931            contiguous_row_selections.push(selections.next().unwrap().clone());
15932        } else {
15933            break;
15934        }
15935    }
15936    (start_row, end_row)
15937}
15938
15939fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15940    if next_selection.end.column > 0 || next_selection.is_empty() {
15941        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15942    } else {
15943        MultiBufferRow(next_selection.end.row)
15944    }
15945}
15946
15947impl EditorSnapshot {
15948    pub fn remote_selections_in_range<'a>(
15949        &'a self,
15950        range: &'a Range<Anchor>,
15951        collaboration_hub: &dyn CollaborationHub,
15952        cx: &'a App,
15953    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15954        let participant_names = collaboration_hub.user_names(cx);
15955        let participant_indices = collaboration_hub.user_participant_indices(cx);
15956        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15957        let collaborators_by_replica_id = collaborators_by_peer_id
15958            .iter()
15959            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15960            .collect::<HashMap<_, _>>();
15961        self.buffer_snapshot
15962            .selections_in_range(range, false)
15963            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15964                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15965                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15966                let user_name = participant_names.get(&collaborator.user_id).cloned();
15967                Some(RemoteSelection {
15968                    replica_id,
15969                    selection,
15970                    cursor_shape,
15971                    line_mode,
15972                    participant_index,
15973                    peer_id: collaborator.peer_id,
15974                    user_name,
15975                })
15976            })
15977    }
15978
15979    pub fn hunks_for_ranges(
15980        &self,
15981        ranges: impl Iterator<Item = Range<Point>>,
15982    ) -> Vec<MultiBufferDiffHunk> {
15983        let mut hunks = Vec::new();
15984        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15985            HashMap::default();
15986        for query_range in ranges {
15987            let query_rows =
15988                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15989            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15990                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15991            ) {
15992                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15993                // when the caret is just above or just below the deleted hunk.
15994                let allow_adjacent = hunk.status().is_removed();
15995                let related_to_selection = if allow_adjacent {
15996                    hunk.row_range.overlaps(&query_rows)
15997                        || hunk.row_range.start == query_rows.end
15998                        || hunk.row_range.end == query_rows.start
15999                } else {
16000                    hunk.row_range.overlaps(&query_rows)
16001                };
16002                if related_to_selection {
16003                    if !processed_buffer_rows
16004                        .entry(hunk.buffer_id)
16005                        .or_default()
16006                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16007                    {
16008                        continue;
16009                    }
16010                    hunks.push(hunk);
16011                }
16012            }
16013        }
16014
16015        hunks
16016    }
16017
16018    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16019        self.display_snapshot.buffer_snapshot.language_at(position)
16020    }
16021
16022    pub fn is_focused(&self) -> bool {
16023        self.is_focused
16024    }
16025
16026    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16027        self.placeholder_text.as_ref()
16028    }
16029
16030    pub fn scroll_position(&self) -> gpui::Point<f32> {
16031        self.scroll_anchor.scroll_position(&self.display_snapshot)
16032    }
16033
16034    fn gutter_dimensions(
16035        &self,
16036        font_id: FontId,
16037        font_size: Pixels,
16038        max_line_number_width: Pixels,
16039        cx: &App,
16040    ) -> Option<GutterDimensions> {
16041        if !self.show_gutter {
16042            return None;
16043        }
16044
16045        let descent = cx.text_system().descent(font_id, font_size);
16046        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16047        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16048
16049        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16050            matches!(
16051                ProjectSettings::get_global(cx).git.git_gutter,
16052                Some(GitGutterSetting::TrackedFiles)
16053            )
16054        });
16055        let gutter_settings = EditorSettings::get_global(cx).gutter;
16056        let show_line_numbers = self
16057            .show_line_numbers
16058            .unwrap_or(gutter_settings.line_numbers);
16059        let line_gutter_width = if show_line_numbers {
16060            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16061            let min_width_for_number_on_gutter = em_advance * 4.0;
16062            max_line_number_width.max(min_width_for_number_on_gutter)
16063        } else {
16064            0.0.into()
16065        };
16066
16067        let show_code_actions = self
16068            .show_code_actions
16069            .unwrap_or(gutter_settings.code_actions);
16070
16071        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16072
16073        let git_blame_entries_width =
16074            self.git_blame_gutter_max_author_length
16075                .map(|max_author_length| {
16076                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16077
16078                    /// The number of characters to dedicate to gaps and margins.
16079                    const SPACING_WIDTH: usize = 4;
16080
16081                    let max_char_count = max_author_length
16082                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16083                        + ::git::SHORT_SHA_LENGTH
16084                        + MAX_RELATIVE_TIMESTAMP.len()
16085                        + SPACING_WIDTH;
16086
16087                    em_advance * max_char_count
16088                });
16089
16090        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16091        left_padding += if show_code_actions || show_runnables {
16092            em_width * 3.0
16093        } else if show_git_gutter && show_line_numbers {
16094            em_width * 2.0
16095        } else if show_git_gutter || show_line_numbers {
16096            em_width
16097        } else {
16098            px(0.)
16099        };
16100
16101        let right_padding = if gutter_settings.folds && show_line_numbers {
16102            em_width * 4.0
16103        } else if gutter_settings.folds {
16104            em_width * 3.0
16105        } else if show_line_numbers {
16106            em_width
16107        } else {
16108            px(0.)
16109        };
16110
16111        Some(GutterDimensions {
16112            left_padding,
16113            right_padding,
16114            width: line_gutter_width + left_padding + right_padding,
16115            margin: -descent,
16116            git_blame_entries_width,
16117        })
16118    }
16119
16120    pub fn render_crease_toggle(
16121        &self,
16122        buffer_row: MultiBufferRow,
16123        row_contains_cursor: bool,
16124        editor: Entity<Editor>,
16125        window: &mut Window,
16126        cx: &mut App,
16127    ) -> Option<AnyElement> {
16128        let folded = self.is_line_folded(buffer_row);
16129        let mut is_foldable = false;
16130
16131        if let Some(crease) = self
16132            .crease_snapshot
16133            .query_row(buffer_row, &self.buffer_snapshot)
16134        {
16135            is_foldable = true;
16136            match crease {
16137                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16138                    if let Some(render_toggle) = render_toggle {
16139                        let toggle_callback =
16140                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16141                                if folded {
16142                                    editor.update(cx, |editor, cx| {
16143                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16144                                    });
16145                                } else {
16146                                    editor.update(cx, |editor, cx| {
16147                                        editor.unfold_at(
16148                                            &crate::UnfoldAt { buffer_row },
16149                                            window,
16150                                            cx,
16151                                        )
16152                                    });
16153                                }
16154                            });
16155                        return Some((render_toggle)(
16156                            buffer_row,
16157                            folded,
16158                            toggle_callback,
16159                            window,
16160                            cx,
16161                        ));
16162                    }
16163                }
16164            }
16165        }
16166
16167        is_foldable |= self.starts_indent(buffer_row);
16168
16169        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16170            Some(
16171                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16172                    .toggle_state(folded)
16173                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16174                        if folded {
16175                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16176                        } else {
16177                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16178                        }
16179                    }))
16180                    .into_any_element(),
16181            )
16182        } else {
16183            None
16184        }
16185    }
16186
16187    pub fn render_crease_trailer(
16188        &self,
16189        buffer_row: MultiBufferRow,
16190        window: &mut Window,
16191        cx: &mut App,
16192    ) -> Option<AnyElement> {
16193        let folded = self.is_line_folded(buffer_row);
16194        if let Crease::Inline { render_trailer, .. } = self
16195            .crease_snapshot
16196            .query_row(buffer_row, &self.buffer_snapshot)?
16197        {
16198            let render_trailer = render_trailer.as_ref()?;
16199            Some(render_trailer(buffer_row, folded, window, cx))
16200        } else {
16201            None
16202        }
16203    }
16204}
16205
16206impl Deref for EditorSnapshot {
16207    type Target = DisplaySnapshot;
16208
16209    fn deref(&self) -> &Self::Target {
16210        &self.display_snapshot
16211    }
16212}
16213
16214#[derive(Clone, Debug, PartialEq, Eq)]
16215pub enum EditorEvent {
16216    InputIgnored {
16217        text: Arc<str>,
16218    },
16219    InputHandled {
16220        utf16_range_to_replace: Option<Range<isize>>,
16221        text: Arc<str>,
16222    },
16223    ExcerptsAdded {
16224        buffer: Entity<Buffer>,
16225        predecessor: ExcerptId,
16226        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16227    },
16228    ExcerptsRemoved {
16229        ids: Vec<ExcerptId>,
16230    },
16231    BufferFoldToggled {
16232        ids: Vec<ExcerptId>,
16233        folded: bool,
16234    },
16235    ExcerptsEdited {
16236        ids: Vec<ExcerptId>,
16237    },
16238    ExcerptsExpanded {
16239        ids: Vec<ExcerptId>,
16240    },
16241    BufferEdited,
16242    Edited {
16243        transaction_id: clock::Lamport,
16244    },
16245    Reparsed(BufferId),
16246    Focused,
16247    FocusedIn,
16248    Blurred,
16249    DirtyChanged,
16250    Saved,
16251    TitleChanged,
16252    DiffBaseChanged,
16253    SelectionsChanged {
16254        local: bool,
16255    },
16256    ScrollPositionChanged {
16257        local: bool,
16258        autoscroll: bool,
16259    },
16260    Closed,
16261    TransactionUndone {
16262        transaction_id: clock::Lamport,
16263    },
16264    TransactionBegun {
16265        transaction_id: clock::Lamport,
16266    },
16267    Reloaded,
16268    CursorShapeChanged,
16269}
16270
16271impl EventEmitter<EditorEvent> for Editor {}
16272
16273impl Focusable for Editor {
16274    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16275        self.focus_handle.clone()
16276    }
16277}
16278
16279impl Render for Editor {
16280    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16281        let settings = ThemeSettings::get_global(cx);
16282
16283        let mut text_style = match self.mode {
16284            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16285                color: cx.theme().colors().editor_foreground,
16286                font_family: settings.ui_font.family.clone(),
16287                font_features: settings.ui_font.features.clone(),
16288                font_fallbacks: settings.ui_font.fallbacks.clone(),
16289                font_size: rems(0.875).into(),
16290                font_weight: settings.ui_font.weight,
16291                line_height: relative(settings.buffer_line_height.value()),
16292                ..Default::default()
16293            },
16294            EditorMode::Full => TextStyle {
16295                color: cx.theme().colors().editor_foreground,
16296                font_family: settings.buffer_font.family.clone(),
16297                font_features: settings.buffer_font.features.clone(),
16298                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16299                font_size: settings.buffer_font_size(cx).into(),
16300                font_weight: settings.buffer_font.weight,
16301                line_height: relative(settings.buffer_line_height.value()),
16302                ..Default::default()
16303            },
16304        };
16305        if let Some(text_style_refinement) = &self.text_style_refinement {
16306            text_style.refine(text_style_refinement)
16307        }
16308
16309        let background = match self.mode {
16310            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16311            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16312            EditorMode::Full => cx.theme().colors().editor_background,
16313        };
16314
16315        EditorElement::new(
16316            &cx.entity(),
16317            EditorStyle {
16318                background,
16319                local_player: cx.theme().players().local(),
16320                text: text_style,
16321                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16322                syntax: cx.theme().syntax().clone(),
16323                status: cx.theme().status().clone(),
16324                inlay_hints_style: make_inlay_hints_style(cx),
16325                inline_completion_styles: make_suggestion_styles(cx),
16326                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16327            },
16328        )
16329    }
16330}
16331
16332impl EntityInputHandler for Editor {
16333    fn text_for_range(
16334        &mut self,
16335        range_utf16: Range<usize>,
16336        adjusted_range: &mut Option<Range<usize>>,
16337        _: &mut Window,
16338        cx: &mut Context<Self>,
16339    ) -> Option<String> {
16340        let snapshot = self.buffer.read(cx).read(cx);
16341        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16342        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16343        if (start.0..end.0) != range_utf16 {
16344            adjusted_range.replace(start.0..end.0);
16345        }
16346        Some(snapshot.text_for_range(start..end).collect())
16347    }
16348
16349    fn selected_text_range(
16350        &mut self,
16351        ignore_disabled_input: bool,
16352        _: &mut Window,
16353        cx: &mut Context<Self>,
16354    ) -> Option<UTF16Selection> {
16355        // Prevent the IME menu from appearing when holding down an alphabetic key
16356        // while input is disabled.
16357        if !ignore_disabled_input && !self.input_enabled {
16358            return None;
16359        }
16360
16361        let selection = self.selections.newest::<OffsetUtf16>(cx);
16362        let range = selection.range();
16363
16364        Some(UTF16Selection {
16365            range: range.start.0..range.end.0,
16366            reversed: selection.reversed,
16367        })
16368    }
16369
16370    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16371        let snapshot = self.buffer.read(cx).read(cx);
16372        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16373        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16374    }
16375
16376    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16377        self.clear_highlights::<InputComposition>(cx);
16378        self.ime_transaction.take();
16379    }
16380
16381    fn replace_text_in_range(
16382        &mut self,
16383        range_utf16: Option<Range<usize>>,
16384        text: &str,
16385        window: &mut Window,
16386        cx: &mut Context<Self>,
16387    ) {
16388        if !self.input_enabled {
16389            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16390            return;
16391        }
16392
16393        self.transact(window, cx, |this, window, cx| {
16394            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16395                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16396                Some(this.selection_replacement_ranges(range_utf16, cx))
16397            } else {
16398                this.marked_text_ranges(cx)
16399            };
16400
16401            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16402                let newest_selection_id = this.selections.newest_anchor().id;
16403                this.selections
16404                    .all::<OffsetUtf16>(cx)
16405                    .iter()
16406                    .zip(ranges_to_replace.iter())
16407                    .find_map(|(selection, range)| {
16408                        if selection.id == newest_selection_id {
16409                            Some(
16410                                (range.start.0 as isize - selection.head().0 as isize)
16411                                    ..(range.end.0 as isize - selection.head().0 as isize),
16412                            )
16413                        } else {
16414                            None
16415                        }
16416                    })
16417            });
16418
16419            cx.emit(EditorEvent::InputHandled {
16420                utf16_range_to_replace: range_to_replace,
16421                text: text.into(),
16422            });
16423
16424            if let Some(new_selected_ranges) = new_selected_ranges {
16425                this.change_selections(None, window, cx, |selections| {
16426                    selections.select_ranges(new_selected_ranges)
16427                });
16428                this.backspace(&Default::default(), window, cx);
16429            }
16430
16431            this.handle_input(text, window, cx);
16432        });
16433
16434        if let Some(transaction) = self.ime_transaction {
16435            self.buffer.update(cx, |buffer, cx| {
16436                buffer.group_until_transaction(transaction, cx);
16437            });
16438        }
16439
16440        self.unmark_text(window, cx);
16441    }
16442
16443    fn replace_and_mark_text_in_range(
16444        &mut self,
16445        range_utf16: Option<Range<usize>>,
16446        text: &str,
16447        new_selected_range_utf16: Option<Range<usize>>,
16448        window: &mut Window,
16449        cx: &mut Context<Self>,
16450    ) {
16451        if !self.input_enabled {
16452            return;
16453        }
16454
16455        let transaction = self.transact(window, cx, |this, window, cx| {
16456            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16457                let snapshot = this.buffer.read(cx).read(cx);
16458                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16459                    for marked_range in &mut marked_ranges {
16460                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16461                        marked_range.start.0 += relative_range_utf16.start;
16462                        marked_range.start =
16463                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16464                        marked_range.end =
16465                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16466                    }
16467                }
16468                Some(marked_ranges)
16469            } else if let Some(range_utf16) = range_utf16 {
16470                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16471                Some(this.selection_replacement_ranges(range_utf16, cx))
16472            } else {
16473                None
16474            };
16475
16476            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16477                let newest_selection_id = this.selections.newest_anchor().id;
16478                this.selections
16479                    .all::<OffsetUtf16>(cx)
16480                    .iter()
16481                    .zip(ranges_to_replace.iter())
16482                    .find_map(|(selection, range)| {
16483                        if selection.id == newest_selection_id {
16484                            Some(
16485                                (range.start.0 as isize - selection.head().0 as isize)
16486                                    ..(range.end.0 as isize - selection.head().0 as isize),
16487                            )
16488                        } else {
16489                            None
16490                        }
16491                    })
16492            });
16493
16494            cx.emit(EditorEvent::InputHandled {
16495                utf16_range_to_replace: range_to_replace,
16496                text: text.into(),
16497            });
16498
16499            if let Some(ranges) = ranges_to_replace {
16500                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16501            }
16502
16503            let marked_ranges = {
16504                let snapshot = this.buffer.read(cx).read(cx);
16505                this.selections
16506                    .disjoint_anchors()
16507                    .iter()
16508                    .map(|selection| {
16509                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16510                    })
16511                    .collect::<Vec<_>>()
16512            };
16513
16514            if text.is_empty() {
16515                this.unmark_text(window, cx);
16516            } else {
16517                this.highlight_text::<InputComposition>(
16518                    marked_ranges.clone(),
16519                    HighlightStyle {
16520                        underline: Some(UnderlineStyle {
16521                            thickness: px(1.),
16522                            color: None,
16523                            wavy: false,
16524                        }),
16525                        ..Default::default()
16526                    },
16527                    cx,
16528                );
16529            }
16530
16531            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16532            let use_autoclose = this.use_autoclose;
16533            let use_auto_surround = this.use_auto_surround;
16534            this.set_use_autoclose(false);
16535            this.set_use_auto_surround(false);
16536            this.handle_input(text, window, cx);
16537            this.set_use_autoclose(use_autoclose);
16538            this.set_use_auto_surround(use_auto_surround);
16539
16540            if let Some(new_selected_range) = new_selected_range_utf16 {
16541                let snapshot = this.buffer.read(cx).read(cx);
16542                let new_selected_ranges = marked_ranges
16543                    .into_iter()
16544                    .map(|marked_range| {
16545                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16546                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16547                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16548                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16549                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16550                    })
16551                    .collect::<Vec<_>>();
16552
16553                drop(snapshot);
16554                this.change_selections(None, window, cx, |selections| {
16555                    selections.select_ranges(new_selected_ranges)
16556                });
16557            }
16558        });
16559
16560        self.ime_transaction = self.ime_transaction.or(transaction);
16561        if let Some(transaction) = self.ime_transaction {
16562            self.buffer.update(cx, |buffer, cx| {
16563                buffer.group_until_transaction(transaction, cx);
16564            });
16565        }
16566
16567        if self.text_highlights::<InputComposition>(cx).is_none() {
16568            self.ime_transaction.take();
16569        }
16570    }
16571
16572    fn bounds_for_range(
16573        &mut self,
16574        range_utf16: Range<usize>,
16575        element_bounds: gpui::Bounds<Pixels>,
16576        window: &mut Window,
16577        cx: &mut Context<Self>,
16578    ) -> Option<gpui::Bounds<Pixels>> {
16579        let text_layout_details = self.text_layout_details(window);
16580        let gpui::Size {
16581            width: em_width,
16582            height: line_height,
16583        } = self.character_size(window);
16584
16585        let snapshot = self.snapshot(window, cx);
16586        let scroll_position = snapshot.scroll_position();
16587        let scroll_left = scroll_position.x * em_width;
16588
16589        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16590        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16591            + self.gutter_dimensions.width
16592            + self.gutter_dimensions.margin;
16593        let y = line_height * (start.row().as_f32() - scroll_position.y);
16594
16595        Some(Bounds {
16596            origin: element_bounds.origin + point(x, y),
16597            size: size(em_width, line_height),
16598        })
16599    }
16600
16601    fn character_index_for_point(
16602        &mut self,
16603        point: gpui::Point<Pixels>,
16604        _window: &mut Window,
16605        _cx: &mut Context<Self>,
16606    ) -> Option<usize> {
16607        let position_map = self.last_position_map.as_ref()?;
16608        if !position_map.text_hitbox.contains(&point) {
16609            return None;
16610        }
16611        let display_point = position_map.point_for_position(point).previous_valid;
16612        let anchor = position_map
16613            .snapshot
16614            .display_point_to_anchor(display_point, Bias::Left);
16615        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16616        Some(utf16_offset.0)
16617    }
16618}
16619
16620trait SelectionExt {
16621    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16622    fn spanned_rows(
16623        &self,
16624        include_end_if_at_line_start: bool,
16625        map: &DisplaySnapshot,
16626    ) -> Range<MultiBufferRow>;
16627}
16628
16629impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16630    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16631        let start = self
16632            .start
16633            .to_point(&map.buffer_snapshot)
16634            .to_display_point(map);
16635        let end = self
16636            .end
16637            .to_point(&map.buffer_snapshot)
16638            .to_display_point(map);
16639        if self.reversed {
16640            end..start
16641        } else {
16642            start..end
16643        }
16644    }
16645
16646    fn spanned_rows(
16647        &self,
16648        include_end_if_at_line_start: bool,
16649        map: &DisplaySnapshot,
16650    ) -> Range<MultiBufferRow> {
16651        let start = self.start.to_point(&map.buffer_snapshot);
16652        let mut end = self.end.to_point(&map.buffer_snapshot);
16653        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16654            end.row -= 1;
16655        }
16656
16657        let buffer_start = map.prev_line_boundary(start).0;
16658        let buffer_end = map.next_line_boundary(end).0;
16659        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16660    }
16661}
16662
16663impl<T: InvalidationRegion> InvalidationStack<T> {
16664    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16665    where
16666        S: Clone + ToOffset,
16667    {
16668        while let Some(region) = self.last() {
16669            let all_selections_inside_invalidation_ranges =
16670                if selections.len() == region.ranges().len() {
16671                    selections
16672                        .iter()
16673                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16674                        .all(|(selection, invalidation_range)| {
16675                            let head = selection.head().to_offset(buffer);
16676                            invalidation_range.start <= head && invalidation_range.end >= head
16677                        })
16678                } else {
16679                    false
16680                };
16681
16682            if all_selections_inside_invalidation_ranges {
16683                break;
16684            } else {
16685                self.pop();
16686            }
16687        }
16688    }
16689}
16690
16691impl<T> Default for InvalidationStack<T> {
16692    fn default() -> Self {
16693        Self(Default::default())
16694    }
16695}
16696
16697impl<T> Deref for InvalidationStack<T> {
16698    type Target = Vec<T>;
16699
16700    fn deref(&self) -> &Self::Target {
16701        &self.0
16702    }
16703}
16704
16705impl<T> DerefMut for InvalidationStack<T> {
16706    fn deref_mut(&mut self) -> &mut Self::Target {
16707        &mut self.0
16708    }
16709}
16710
16711impl InvalidationRegion for SnippetState {
16712    fn ranges(&self) -> &[Range<Anchor>] {
16713        &self.ranges[self.active_index]
16714    }
16715}
16716
16717pub fn diagnostic_block_renderer(
16718    diagnostic: Diagnostic,
16719    max_message_rows: Option<u8>,
16720    allow_closing: bool,
16721    _is_valid: bool,
16722) -> RenderBlock {
16723    let (text_without_backticks, code_ranges) =
16724        highlight_diagnostic_message(&diagnostic, max_message_rows);
16725
16726    Arc::new(move |cx: &mut BlockContext| {
16727        let group_id: SharedString = cx.block_id.to_string().into();
16728
16729        let mut text_style = cx.window.text_style().clone();
16730        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16731        let theme_settings = ThemeSettings::get_global(cx);
16732        text_style.font_family = theme_settings.buffer_font.family.clone();
16733        text_style.font_style = theme_settings.buffer_font.style;
16734        text_style.font_features = theme_settings.buffer_font.features.clone();
16735        text_style.font_weight = theme_settings.buffer_font.weight;
16736
16737        let multi_line_diagnostic = diagnostic.message.contains('\n');
16738
16739        let buttons = |diagnostic: &Diagnostic| {
16740            if multi_line_diagnostic {
16741                v_flex()
16742            } else {
16743                h_flex()
16744            }
16745            .when(allow_closing, |div| {
16746                div.children(diagnostic.is_primary.then(|| {
16747                    IconButton::new("close-block", IconName::XCircle)
16748                        .icon_color(Color::Muted)
16749                        .size(ButtonSize::Compact)
16750                        .style(ButtonStyle::Transparent)
16751                        .visible_on_hover(group_id.clone())
16752                        .on_click(move |_click, window, cx| {
16753                            window.dispatch_action(Box::new(Cancel), cx)
16754                        })
16755                        .tooltip(|window, cx| {
16756                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16757                        })
16758                }))
16759            })
16760            .child(
16761                IconButton::new("copy-block", IconName::Copy)
16762                    .icon_color(Color::Muted)
16763                    .size(ButtonSize::Compact)
16764                    .style(ButtonStyle::Transparent)
16765                    .visible_on_hover(group_id.clone())
16766                    .on_click({
16767                        let message = diagnostic.message.clone();
16768                        move |_click, _, cx| {
16769                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16770                        }
16771                    })
16772                    .tooltip(Tooltip::text("Copy diagnostic message")),
16773            )
16774        };
16775
16776        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16777            AvailableSpace::min_size(),
16778            cx.window,
16779            cx.app,
16780        );
16781
16782        h_flex()
16783            .id(cx.block_id)
16784            .group(group_id.clone())
16785            .relative()
16786            .size_full()
16787            .block_mouse_down()
16788            .pl(cx.gutter_dimensions.width)
16789            .w(cx.max_width - cx.gutter_dimensions.full_width())
16790            .child(
16791                div()
16792                    .flex()
16793                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16794                    .flex_shrink(),
16795            )
16796            .child(buttons(&diagnostic))
16797            .child(div().flex().flex_shrink_0().child(
16798                StyledText::new(text_without_backticks.clone()).with_highlights(
16799                    &text_style,
16800                    code_ranges.iter().map(|range| {
16801                        (
16802                            range.clone(),
16803                            HighlightStyle {
16804                                font_weight: Some(FontWeight::BOLD),
16805                                ..Default::default()
16806                            },
16807                        )
16808                    }),
16809                ),
16810            ))
16811            .into_any_element()
16812    })
16813}
16814
16815fn inline_completion_edit_text(
16816    current_snapshot: &BufferSnapshot,
16817    edits: &[(Range<Anchor>, String)],
16818    edit_preview: &EditPreview,
16819    include_deletions: bool,
16820    cx: &App,
16821) -> HighlightedText {
16822    let edits = edits
16823        .iter()
16824        .map(|(anchor, text)| {
16825            (
16826                anchor.start.text_anchor..anchor.end.text_anchor,
16827                text.clone(),
16828            )
16829        })
16830        .collect::<Vec<_>>();
16831
16832    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16833}
16834
16835pub fn highlight_diagnostic_message(
16836    diagnostic: &Diagnostic,
16837    mut max_message_rows: Option<u8>,
16838) -> (SharedString, Vec<Range<usize>>) {
16839    let mut text_without_backticks = String::new();
16840    let mut code_ranges = Vec::new();
16841
16842    if let Some(source) = &diagnostic.source {
16843        text_without_backticks.push_str(source);
16844        code_ranges.push(0..source.len());
16845        text_without_backticks.push_str(": ");
16846    }
16847
16848    let mut prev_offset = 0;
16849    let mut in_code_block = false;
16850    let has_row_limit = max_message_rows.is_some();
16851    let mut newline_indices = diagnostic
16852        .message
16853        .match_indices('\n')
16854        .filter(|_| has_row_limit)
16855        .map(|(ix, _)| ix)
16856        .fuse()
16857        .peekable();
16858
16859    for (quote_ix, _) in diagnostic
16860        .message
16861        .match_indices('`')
16862        .chain([(diagnostic.message.len(), "")])
16863    {
16864        let mut first_newline_ix = None;
16865        let mut last_newline_ix = None;
16866        while let Some(newline_ix) = newline_indices.peek() {
16867            if *newline_ix < quote_ix {
16868                if first_newline_ix.is_none() {
16869                    first_newline_ix = Some(*newline_ix);
16870                }
16871                last_newline_ix = Some(*newline_ix);
16872
16873                if let Some(rows_left) = &mut max_message_rows {
16874                    if *rows_left == 0 {
16875                        break;
16876                    } else {
16877                        *rows_left -= 1;
16878                    }
16879                }
16880                let _ = newline_indices.next();
16881            } else {
16882                break;
16883            }
16884        }
16885        let prev_len = text_without_backticks.len();
16886        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16887        text_without_backticks.push_str(new_text);
16888        if in_code_block {
16889            code_ranges.push(prev_len..text_without_backticks.len());
16890        }
16891        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16892        in_code_block = !in_code_block;
16893        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16894            text_without_backticks.push_str("...");
16895            break;
16896        }
16897    }
16898
16899    (text_without_backticks.into(), code_ranges)
16900}
16901
16902fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16903    match severity {
16904        DiagnosticSeverity::ERROR => colors.error,
16905        DiagnosticSeverity::WARNING => colors.warning,
16906        DiagnosticSeverity::INFORMATION => colors.info,
16907        DiagnosticSeverity::HINT => colors.info,
16908        _ => colors.ignored,
16909    }
16910}
16911
16912pub fn styled_runs_for_code_label<'a>(
16913    label: &'a CodeLabel,
16914    syntax_theme: &'a theme::SyntaxTheme,
16915) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16916    let fade_out = HighlightStyle {
16917        fade_out: Some(0.35),
16918        ..Default::default()
16919    };
16920
16921    let mut prev_end = label.filter_range.end;
16922    label
16923        .runs
16924        .iter()
16925        .enumerate()
16926        .flat_map(move |(ix, (range, highlight_id))| {
16927            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16928                style
16929            } else {
16930                return Default::default();
16931            };
16932            let mut muted_style = style;
16933            muted_style.highlight(fade_out);
16934
16935            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16936            if range.start >= label.filter_range.end {
16937                if range.start > prev_end {
16938                    runs.push((prev_end..range.start, fade_out));
16939                }
16940                runs.push((range.clone(), muted_style));
16941            } else if range.end <= label.filter_range.end {
16942                runs.push((range.clone(), style));
16943            } else {
16944                runs.push((range.start..label.filter_range.end, style));
16945                runs.push((label.filter_range.end..range.end, muted_style));
16946            }
16947            prev_end = cmp::max(prev_end, range.end);
16948
16949            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16950                runs.push((prev_end..label.text.len(), fade_out));
16951            }
16952
16953            runs
16954        })
16955}
16956
16957pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16958    let mut prev_index = 0;
16959    let mut prev_codepoint: Option<char> = None;
16960    text.char_indices()
16961        .chain([(text.len(), '\0')])
16962        .filter_map(move |(index, codepoint)| {
16963            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16964            let is_boundary = index == text.len()
16965                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16966                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16967            if is_boundary {
16968                let chunk = &text[prev_index..index];
16969                prev_index = index;
16970                Some(chunk)
16971            } else {
16972                None
16973            }
16974        })
16975}
16976
16977pub trait RangeToAnchorExt: Sized {
16978    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16979
16980    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16981        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16982        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16983    }
16984}
16985
16986impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16987    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16988        let start_offset = self.start.to_offset(snapshot);
16989        let end_offset = self.end.to_offset(snapshot);
16990        if start_offset == end_offset {
16991            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16992        } else {
16993            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16994        }
16995    }
16996}
16997
16998pub trait RowExt {
16999    fn as_f32(&self) -> f32;
17000
17001    fn next_row(&self) -> Self;
17002
17003    fn previous_row(&self) -> Self;
17004
17005    fn minus(&self, other: Self) -> u32;
17006}
17007
17008impl RowExt for DisplayRow {
17009    fn as_f32(&self) -> f32 {
17010        self.0 as f32
17011    }
17012
17013    fn next_row(&self) -> Self {
17014        Self(self.0 + 1)
17015    }
17016
17017    fn previous_row(&self) -> Self {
17018        Self(self.0.saturating_sub(1))
17019    }
17020
17021    fn minus(&self, other: Self) -> u32 {
17022        self.0 - other.0
17023    }
17024}
17025
17026impl RowExt for MultiBufferRow {
17027    fn as_f32(&self) -> f32 {
17028        self.0 as f32
17029    }
17030
17031    fn next_row(&self) -> Self {
17032        Self(self.0 + 1)
17033    }
17034
17035    fn previous_row(&self) -> Self {
17036        Self(self.0.saturating_sub(1))
17037    }
17038
17039    fn minus(&self, other: Self) -> u32 {
17040        self.0 - other.0
17041    }
17042}
17043
17044trait RowRangeExt {
17045    type Row;
17046
17047    fn len(&self) -> usize;
17048
17049    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17050}
17051
17052impl RowRangeExt for Range<MultiBufferRow> {
17053    type Row = MultiBufferRow;
17054
17055    fn len(&self) -> usize {
17056        (self.end.0 - self.start.0) as usize
17057    }
17058
17059    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17060        (self.start.0..self.end.0).map(MultiBufferRow)
17061    }
17062}
17063
17064impl RowRangeExt for Range<DisplayRow> {
17065    type Row = DisplayRow;
17066
17067    fn len(&self) -> usize {
17068        (self.end.0 - self.start.0) as usize
17069    }
17070
17071    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17072        (self.start.0..self.end.0).map(DisplayRow)
17073    }
17074}
17075
17076/// If select range has more than one line, we
17077/// just point the cursor to range.start.
17078fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17079    if range.start.row == range.end.row {
17080        range
17081    } else {
17082        range.start..range.start
17083    }
17084}
17085pub struct KillRing(ClipboardItem);
17086impl Global for KillRing {}
17087
17088const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17089
17090fn all_edits_insertions_or_deletions(
17091    edits: &Vec<(Range<Anchor>, String)>,
17092    snapshot: &MultiBufferSnapshot,
17093) -> bool {
17094    let mut all_insertions = true;
17095    let mut all_deletions = true;
17096
17097    for (range, new_text) in edits.iter() {
17098        let range_is_empty = range.to_offset(&snapshot).is_empty();
17099        let text_is_empty = new_text.is_empty();
17100
17101        if range_is_empty != text_is_empty {
17102            if range_is_empty {
17103                all_deletions = false;
17104            } else {
17105                all_insertions = false;
17106            }
17107        } else {
17108            return false;
17109        }
17110
17111        if !all_insertions && !all_deletions {
17112            return false;
17113        }
17114    }
17115    all_insertions || all_deletions
17116}