editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use code_context_menus::{
   77    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   78    CompletionsMenu, ContextMenuOrigin,
   79};
   80use git::blame::GitBlame;
   81use gpui::{
   82    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   83    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   84    ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
   85    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   86    HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
   87    PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
   88    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   89    WeakEntity, WeakFocusHandle, Window,
   90};
   91use highlight_matching_bracket::refresh_matching_bracket_highlights;
   92use hover_popover::{hide_hover, HoverState};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview, HighlightedText,
  103    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  104    TransactionId, TreeSitterOptions,
  105};
  106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  107use linked_editing_ranges::refresh_linked_ranges;
  108use mouse_context_menu::MouseContextMenu;
  109use persistence::DB;
  110pub use proposed_changes_editor::{
  111    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  112};
  113use similar::{ChangeTag, TextDiff};
  114use std::iter::Peekable;
  115use task::{ResolvedTask, TaskTemplate, TaskVariables};
  116
  117use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  118pub use lsp::CompletionContext;
  119use lsp::{
  120    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  121    LanguageServerId, LanguageServerName,
  122};
  123
  124use language::BufferSnapshot;
  125use movement::TextLayoutDetails;
  126pub use multi_buffer::{
  127    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  128    ToOffset, ToPoint,
  129};
  130use multi_buffer::{
  131    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  132    ToOffsetUtf16,
  133};
  134use project::{
  135    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  136    project_settings::{GitGutterSetting, ProjectSettings},
  137    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  138    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  139};
  140use rand::prelude::*;
  141use rpc::{proto::*, ErrorExt};
  142use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  143use selections_collection::{
  144    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  145};
  146use serde::{Deserialize, Serialize};
  147use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  148use smallvec::SmallVec;
  149use snippet::Snippet;
  150use std::{
  151    any::TypeId,
  152    borrow::Cow,
  153    cell::RefCell,
  154    cmp::{self, Ordering, Reverse},
  155    mem,
  156    num::NonZeroU32,
  157    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  158    path::{Path, PathBuf},
  159    rc::Rc,
  160    sync::Arc,
  161    time::{Duration, Instant},
  162};
  163pub use sum_tree::Bias;
  164use sum_tree::TreeMap;
  165use text::{BufferId, OffsetUtf16, Rope};
  166use theme::{
  167    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  168    ThemeColors, ThemeSettings,
  169};
  170use ui::{
  171    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  172    Tooltip,
  173};
  174use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  175use workspace::{
  176    item::{ItemHandle, PreviewTabsSettings},
  177    ItemId, RestoreOnStartupBehavior,
  178};
  179use workspace::{
  180    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  181    WorkspaceSettings,
  182};
  183use workspace::{
  184    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  185};
  186use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  187
  188use crate::hover_links::{find_url, find_url_from_range};
  189use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  190
  191pub const FILE_HEADER_HEIGHT: u32 = 2;
  192pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  193pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  194pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  195const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  196const MAX_LINE_LEN: usize = 1024;
  197const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  198const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  199pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  200#[doc(hidden)]
  201pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  202
  203pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  204pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  205
  206pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  207pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  208
  209const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  210    alt: true,
  211    shift: true,
  212    control: false,
  213    platform: false,
  214    function: false,
  215};
  216
  217pub fn render_parsed_markdown(
  218    element_id: impl Into<ElementId>,
  219    parsed: &language::ParsedMarkdown,
  220    editor_style: &EditorStyle,
  221    workspace: Option<WeakEntity<Workspace>>,
  222    cx: &mut App,
  223) -> InteractiveText {
  224    let code_span_background_color = cx
  225        .theme()
  226        .colors()
  227        .editor_document_highlight_read_background;
  228
  229    let highlights = gpui::combine_highlights(
  230        parsed.highlights.iter().filter_map(|(range, highlight)| {
  231            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  232            Some((range.clone(), highlight))
  233        }),
  234        parsed
  235            .regions
  236            .iter()
  237            .zip(&parsed.region_ranges)
  238            .filter_map(|(region, range)| {
  239                if region.code {
  240                    Some((
  241                        range.clone(),
  242                        HighlightStyle {
  243                            background_color: Some(code_span_background_color),
  244                            ..Default::default()
  245                        },
  246                    ))
  247                } else {
  248                    None
  249                }
  250            }),
  251    );
  252
  253    let mut links = Vec::new();
  254    let mut link_ranges = Vec::new();
  255    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  256        if let Some(link) = region.link.clone() {
  257            links.push(link);
  258            link_ranges.push(range.clone());
  259        }
  260    }
  261
  262    InteractiveText::new(
  263        element_id,
  264        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  265    )
  266    .on_click(
  267        link_ranges,
  268        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  269            markdown::Link::Web { url } => cx.open_url(url),
  270            markdown::Link::Path { path } => {
  271                if let Some(workspace) = &workspace {
  272                    _ = workspace.update(cx, |workspace, cx| {
  273                        workspace
  274                            .open_abs_path(path.clone(), false, window, cx)
  275                            .detach();
  276                    });
  277                }
  278            }
  279        },
  280    )
  281}
  282
  283#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  284pub enum InlayId {
  285    InlineCompletion(usize),
  286    Hint(usize),
  287}
  288
  289impl InlayId {
  290    fn id(&self) -> usize {
  291        match self {
  292            Self::InlineCompletion(id) => *id,
  293            Self::Hint(id) => *id,
  294        }
  295    }
  296}
  297
  298enum DocumentHighlightRead {}
  299enum DocumentHighlightWrite {}
  300enum InputComposition {}
  301enum SelectedTextHighlight {}
  302
  303#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  304pub enum Navigated {
  305    Yes,
  306    No,
  307}
  308
  309impl Navigated {
  310    pub fn from_bool(yes: bool) -> Navigated {
  311        if yes {
  312            Navigated::Yes
  313        } else {
  314            Navigated::No
  315        }
  316    }
  317}
  318
  319pub fn init_settings(cx: &mut App) {
  320    EditorSettings::register(cx);
  321}
  322
  323pub fn init(cx: &mut App) {
  324    init_settings(cx);
  325
  326    workspace::register_project_item::<Editor>(cx);
  327    workspace::FollowableViewRegistry::register::<Editor>(cx);
  328    workspace::register_serializable_item::<Editor>(cx);
  329
  330    cx.observe_new(
  331        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  332            workspace.register_action(Editor::new_file);
  333            workspace.register_action(Editor::new_file_vertical);
  334            workspace.register_action(Editor::new_file_horizontal);
  335            workspace.register_action(Editor::cancel_language_server_work);
  336        },
  337    )
  338    .detach();
  339
  340    cx.on_action(move |_: &workspace::NewFile, cx| {
  341        let app_state = workspace::AppState::global(cx);
  342        if let Some(app_state) = app_state.upgrade() {
  343            workspace::open_new(
  344                Default::default(),
  345                app_state,
  346                cx,
  347                |workspace, window, cx| {
  348                    Editor::new_file(workspace, &Default::default(), window, cx)
  349                },
  350            )
  351            .detach();
  352        }
  353    });
  354    cx.on_action(move |_: &workspace::NewWindow, cx| {
  355        let app_state = workspace::AppState::global(cx);
  356        if let Some(app_state) = app_state.upgrade() {
  357            workspace::open_new(
  358                Default::default(),
  359                app_state,
  360                cx,
  361                |workspace, window, cx| {
  362                    cx.activate(true);
  363                    Editor::new_file(workspace, &Default::default(), window, cx)
  364                },
  365            )
  366            .detach();
  367        }
  368    });
  369}
  370
  371pub struct SearchWithinRange;
  372
  373trait InvalidationRegion {
  374    fn ranges(&self) -> &[Range<Anchor>];
  375}
  376
  377#[derive(Clone, Debug, PartialEq)]
  378pub enum SelectPhase {
  379    Begin {
  380        position: DisplayPoint,
  381        add: bool,
  382        click_count: usize,
  383    },
  384    BeginColumnar {
  385        position: DisplayPoint,
  386        reset: bool,
  387        goal_column: u32,
  388    },
  389    Extend {
  390        position: DisplayPoint,
  391        click_count: usize,
  392    },
  393    Update {
  394        position: DisplayPoint,
  395        goal_column: u32,
  396        scroll_delta: gpui::Point<f32>,
  397    },
  398    End,
  399}
  400
  401#[derive(Clone, Debug)]
  402pub enum SelectMode {
  403    Character,
  404    Word(Range<Anchor>),
  405    Line(Range<Anchor>),
  406    All,
  407}
  408
  409#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  410pub enum EditorMode {
  411    SingleLine { auto_width: bool },
  412    AutoHeight { max_lines: usize },
  413    Full,
  414}
  415
  416#[derive(Copy, Clone, Debug)]
  417pub enum SoftWrap {
  418    /// Prefer not to wrap at all.
  419    ///
  420    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  421    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  422    GitDiff,
  423    /// Prefer a single line generally, unless an overly long line is encountered.
  424    None,
  425    /// Soft wrap lines that exceed the editor width.
  426    EditorWidth,
  427    /// Soft wrap lines at the preferred line length.
  428    Column(u32),
  429    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  430    Bounded(u32),
  431}
  432
  433#[derive(Clone)]
  434pub struct EditorStyle {
  435    pub background: Hsla,
  436    pub local_player: PlayerColor,
  437    pub text: TextStyle,
  438    pub scrollbar_width: Pixels,
  439    pub syntax: Arc<SyntaxTheme>,
  440    pub status: StatusColors,
  441    pub inlay_hints_style: HighlightStyle,
  442    pub inline_completion_styles: InlineCompletionStyles,
  443    pub unnecessary_code_fade: f32,
  444}
  445
  446impl Default for EditorStyle {
  447    fn default() -> Self {
  448        Self {
  449            background: Hsla::default(),
  450            local_player: PlayerColor::default(),
  451            text: TextStyle::default(),
  452            scrollbar_width: Pixels::default(),
  453            syntax: Default::default(),
  454            // HACK: Status colors don't have a real default.
  455            // We should look into removing the status colors from the editor
  456            // style and retrieve them directly from the theme.
  457            status: StatusColors::dark(),
  458            inlay_hints_style: HighlightStyle::default(),
  459            inline_completion_styles: InlineCompletionStyles {
  460                insertion: HighlightStyle::default(),
  461                whitespace: HighlightStyle::default(),
  462            },
  463            unnecessary_code_fade: Default::default(),
  464        }
  465    }
  466}
  467
  468pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  469    let show_background = language_settings::language_settings(None, None, cx)
  470        .inlay_hints
  471        .show_background;
  472
  473    HighlightStyle {
  474        color: Some(cx.theme().status().hint),
  475        background_color: show_background.then(|| cx.theme().status().hint_background),
  476        ..HighlightStyle::default()
  477    }
  478}
  479
  480pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  481    InlineCompletionStyles {
  482        insertion: HighlightStyle {
  483            color: Some(cx.theme().status().predictive),
  484            ..HighlightStyle::default()
  485        },
  486        whitespace: HighlightStyle {
  487            background_color: Some(cx.theme().status().created_background),
  488            ..HighlightStyle::default()
  489        },
  490    }
  491}
  492
  493type CompletionId = usize;
  494
  495pub(crate) enum EditDisplayMode {
  496    TabAccept,
  497    DiffPopover,
  498    Inline,
  499}
  500
  501enum InlineCompletion {
  502    Edit {
  503        edits: Vec<(Range<Anchor>, String)>,
  504        edit_preview: Option<EditPreview>,
  505        display_mode: EditDisplayMode,
  506        snapshot: BufferSnapshot,
  507    },
  508    Move {
  509        target: Anchor,
  510        snapshot: BufferSnapshot,
  511    },
  512}
  513
  514struct InlineCompletionState {
  515    inlay_ids: Vec<InlayId>,
  516    completion: InlineCompletion,
  517    completion_id: Option<SharedString>,
  518    invalidation_range: Range<Anchor>,
  519}
  520
  521enum EditPredictionSettings {
  522    Disabled,
  523    Enabled {
  524        show_in_menu: bool,
  525        preview_requires_modifier: bool,
  526    },
  527}
  528
  529enum InlineCompletionHighlight {}
  530
  531pub enum MenuInlineCompletionsPolicy {
  532    Never,
  533    ByProvider,
  534}
  535
  536pub enum EditPredictionPreview {
  537    /// Modifier is not pressed
  538    Inactive,
  539    /// Modifier pressed
  540    Active {
  541        previous_scroll_position: Option<ScrollAnchor>,
  542    },
  543}
  544
  545#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  546struct EditorActionId(usize);
  547
  548impl EditorActionId {
  549    pub fn post_inc(&mut self) -> Self {
  550        let answer = self.0;
  551
  552        *self = Self(answer + 1);
  553
  554        Self(answer)
  555    }
  556}
  557
  558// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  559// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  560
  561type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  562type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  563
  564#[derive(Default)]
  565struct ScrollbarMarkerState {
  566    scrollbar_size: Size<Pixels>,
  567    dirty: bool,
  568    markers: Arc<[PaintQuad]>,
  569    pending_refresh: Option<Task<Result<()>>>,
  570}
  571
  572impl ScrollbarMarkerState {
  573    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  574        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  575    }
  576}
  577
  578#[derive(Clone, Debug)]
  579struct RunnableTasks {
  580    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  581    offset: MultiBufferOffset,
  582    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  583    column: u32,
  584    // Values of all named captures, including those starting with '_'
  585    extra_variables: HashMap<String, String>,
  586    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  587    context_range: Range<BufferOffset>,
  588}
  589
  590impl RunnableTasks {
  591    fn resolve<'a>(
  592        &'a self,
  593        cx: &'a task::TaskContext,
  594    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  595        self.templates.iter().filter_map(|(kind, template)| {
  596            template
  597                .resolve_task(&kind.to_id_base(), cx)
  598                .map(|task| (kind.clone(), task))
  599        })
  600    }
  601}
  602
  603#[derive(Clone)]
  604struct ResolvedTasks {
  605    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  606    position: Anchor,
  607}
  608#[derive(Copy, Clone, Debug)]
  609struct MultiBufferOffset(usize);
  610#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  611struct BufferOffset(usize);
  612
  613// Addons allow storing per-editor state in other crates (e.g. Vim)
  614pub trait Addon: 'static {
  615    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  616
  617    fn render_buffer_header_controls(
  618        &self,
  619        _: &ExcerptInfo,
  620        _: &Window,
  621        _: &App,
  622    ) -> Option<AnyElement> {
  623        None
  624    }
  625
  626    fn to_any(&self) -> &dyn std::any::Any;
  627}
  628
  629#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  630pub enum IsVimMode {
  631    Yes,
  632    No,
  633}
  634
  635/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  636///
  637/// See the [module level documentation](self) for more information.
  638pub struct Editor {
  639    focus_handle: FocusHandle,
  640    last_focused_descendant: Option<WeakFocusHandle>,
  641    /// The text buffer being edited
  642    buffer: Entity<MultiBuffer>,
  643    /// Map of how text in the buffer should be displayed.
  644    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  645    pub display_map: Entity<DisplayMap>,
  646    pub selections: SelectionsCollection,
  647    pub scroll_manager: ScrollManager,
  648    /// When inline assist editors are linked, they all render cursors because
  649    /// typing enters text into each of them, even the ones that aren't focused.
  650    pub(crate) show_cursor_when_unfocused: bool,
  651    columnar_selection_tail: Option<Anchor>,
  652    add_selections_state: Option<AddSelectionsState>,
  653    select_next_state: Option<SelectNextState>,
  654    select_prev_state: Option<SelectNextState>,
  655    selection_history: SelectionHistory,
  656    autoclose_regions: Vec<AutocloseRegion>,
  657    snippet_stack: InvalidationStack<SnippetState>,
  658    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  659    ime_transaction: Option<TransactionId>,
  660    active_diagnostics: Option<ActiveDiagnosticGroup>,
  661    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  662
  663    // TODO: make this a access method
  664    pub project: Option<Entity<Project>>,
  665    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  666    completion_provider: Option<Box<dyn CompletionProvider>>,
  667    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  668    blink_manager: Entity<BlinkManager>,
  669    show_cursor_names: bool,
  670    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  671    pub show_local_selections: bool,
  672    mode: EditorMode,
  673    show_breadcrumbs: bool,
  674    show_gutter: bool,
  675    show_scrollbars: bool,
  676    show_line_numbers: Option<bool>,
  677    use_relative_line_numbers: Option<bool>,
  678    show_git_diff_gutter: Option<bool>,
  679    show_code_actions: Option<bool>,
  680    show_runnables: Option<bool>,
  681    show_wrap_guides: Option<bool>,
  682    show_indent_guides: Option<bool>,
  683    placeholder_text: Option<Arc<str>>,
  684    highlight_order: usize,
  685    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  686    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  687    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  688    scrollbar_marker_state: ScrollbarMarkerState,
  689    active_indent_guides_state: ActiveIndentGuidesState,
  690    nav_history: Option<ItemNavHistory>,
  691    context_menu: RefCell<Option<CodeContextMenu>>,
  692    mouse_context_menu: Option<MouseContextMenu>,
  693    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  694    signature_help_state: SignatureHelpState,
  695    auto_signature_help: Option<bool>,
  696    find_all_references_task_sources: Vec<Anchor>,
  697    next_completion_id: CompletionId,
  698    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  699    code_actions_task: Option<Task<Result<()>>>,
  700    selection_highlight_task: Option<Task<()>>,
  701    document_highlights_task: Option<Task<()>>,
  702    linked_editing_range_task: Option<Task<Option<()>>>,
  703    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  704    pending_rename: Option<RenameState>,
  705    searchable: bool,
  706    cursor_shape: CursorShape,
  707    current_line_highlight: Option<CurrentLineHighlight>,
  708    collapse_matches: bool,
  709    autoindent_mode: Option<AutoindentMode>,
  710    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  711    input_enabled: bool,
  712    use_modal_editing: bool,
  713    read_only: bool,
  714    leader_peer_id: Option<PeerId>,
  715    remote_id: Option<ViewId>,
  716    hover_state: HoverState,
  717    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  718    gutter_hovered: bool,
  719    hovered_link_state: Option<HoveredLinkState>,
  720    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  721    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  722    active_inline_completion: Option<InlineCompletionState>,
  723    /// Used to prevent flickering as the user types while the menu is open
  724    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  725    edit_prediction_settings: EditPredictionSettings,
  726    inline_completions_hidden_for_vim_mode: bool,
  727    show_inline_completions_override: Option<bool>,
  728    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  729    edit_prediction_preview: EditPredictionPreview,
  730    edit_prediction_cursor_on_leading_whitespace: bool,
  731    edit_prediction_requires_modifier_in_leading_space: bool,
  732    inlay_hint_cache: InlayHintCache,
  733    next_inlay_id: usize,
  734    _subscriptions: Vec<Subscription>,
  735    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  736    gutter_dimensions: GutterDimensions,
  737    style: Option<EditorStyle>,
  738    text_style_refinement: Option<TextStyleRefinement>,
  739    next_editor_action_id: EditorActionId,
  740    editor_actions:
  741        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  742    use_autoclose: bool,
  743    use_auto_surround: bool,
  744    auto_replace_emoji_shortcode: bool,
  745    show_git_blame_gutter: bool,
  746    show_git_blame_inline: bool,
  747    show_git_blame_inline_delay_task: Option<Task<()>>,
  748    distinguish_unstaged_diff_hunks: bool,
  749    git_blame_inline_enabled: bool,
  750    serialize_dirty_buffers: bool,
  751    show_selection_menu: Option<bool>,
  752    blame: Option<Entity<GitBlame>>,
  753    blame_subscription: Option<Subscription>,
  754    custom_context_menu: Option<
  755        Box<
  756            dyn 'static
  757                + Fn(
  758                    &mut Self,
  759                    DisplayPoint,
  760                    &mut Window,
  761                    &mut Context<Self>,
  762                ) -> Option<Entity<ui::ContextMenu>>,
  763        >,
  764    >,
  765    last_bounds: Option<Bounds<Pixels>>,
  766    last_position_map: Option<Rc<PositionMap>>,
  767    expect_bounds_change: Option<Bounds<Pixels>>,
  768    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  769    tasks_update_task: Option<Task<()>>,
  770    in_project_search: bool,
  771    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  772    breadcrumb_header: Option<String>,
  773    focused_block: Option<FocusedBlock>,
  774    next_scroll_position: NextScrollCursorCenterTopBottom,
  775    addons: HashMap<TypeId, Box<dyn Addon>>,
  776    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  777    load_diff_task: Option<Shared<Task<()>>>,
  778    selection_mark_mode: bool,
  779    toggle_fold_multiple_buffers: Task<()>,
  780    _scroll_cursor_center_top_bottom_task: Task<()>,
  781    serialize_selections: Task<()>,
  782}
  783
  784#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  785enum NextScrollCursorCenterTopBottom {
  786    #[default]
  787    Center,
  788    Top,
  789    Bottom,
  790}
  791
  792impl NextScrollCursorCenterTopBottom {
  793    fn next(&self) -> Self {
  794        match self {
  795            Self::Center => Self::Top,
  796            Self::Top => Self::Bottom,
  797            Self::Bottom => Self::Center,
  798        }
  799    }
  800}
  801
  802#[derive(Clone)]
  803pub struct EditorSnapshot {
  804    pub mode: EditorMode,
  805    show_gutter: bool,
  806    show_line_numbers: Option<bool>,
  807    show_git_diff_gutter: Option<bool>,
  808    show_code_actions: Option<bool>,
  809    show_runnables: Option<bool>,
  810    git_blame_gutter_max_author_length: Option<usize>,
  811    pub display_snapshot: DisplaySnapshot,
  812    pub placeholder_text: Option<Arc<str>>,
  813    is_focused: bool,
  814    scroll_anchor: ScrollAnchor,
  815    ongoing_scroll: OngoingScroll,
  816    current_line_highlight: CurrentLineHighlight,
  817    gutter_hovered: bool,
  818}
  819
  820const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  821
  822#[derive(Default, Debug, Clone, Copy)]
  823pub struct GutterDimensions {
  824    pub left_padding: Pixels,
  825    pub right_padding: Pixels,
  826    pub width: Pixels,
  827    pub margin: Pixels,
  828    pub git_blame_entries_width: Option<Pixels>,
  829}
  830
  831impl GutterDimensions {
  832    /// The full width of the space taken up by the gutter.
  833    pub fn full_width(&self) -> Pixels {
  834        self.margin + self.width
  835    }
  836
  837    /// The width of the space reserved for the fold indicators,
  838    /// use alongside 'justify_end' and `gutter_width` to
  839    /// right align content with the line numbers
  840    pub fn fold_area_width(&self) -> Pixels {
  841        self.margin + self.right_padding
  842    }
  843}
  844
  845#[derive(Debug)]
  846pub struct RemoteSelection {
  847    pub replica_id: ReplicaId,
  848    pub selection: Selection<Anchor>,
  849    pub cursor_shape: CursorShape,
  850    pub peer_id: PeerId,
  851    pub line_mode: bool,
  852    pub participant_index: Option<ParticipantIndex>,
  853    pub user_name: Option<SharedString>,
  854}
  855
  856#[derive(Clone, Debug)]
  857struct SelectionHistoryEntry {
  858    selections: Arc<[Selection<Anchor>]>,
  859    select_next_state: Option<SelectNextState>,
  860    select_prev_state: Option<SelectNextState>,
  861    add_selections_state: Option<AddSelectionsState>,
  862}
  863
  864enum SelectionHistoryMode {
  865    Normal,
  866    Undoing,
  867    Redoing,
  868}
  869
  870#[derive(Clone, PartialEq, Eq, Hash)]
  871struct HoveredCursor {
  872    replica_id: u16,
  873    selection_id: usize,
  874}
  875
  876impl Default for SelectionHistoryMode {
  877    fn default() -> Self {
  878        Self::Normal
  879    }
  880}
  881
  882#[derive(Default)]
  883struct SelectionHistory {
  884    #[allow(clippy::type_complexity)]
  885    selections_by_transaction:
  886        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  887    mode: SelectionHistoryMode,
  888    undo_stack: VecDeque<SelectionHistoryEntry>,
  889    redo_stack: VecDeque<SelectionHistoryEntry>,
  890}
  891
  892impl SelectionHistory {
  893    fn insert_transaction(
  894        &mut self,
  895        transaction_id: TransactionId,
  896        selections: Arc<[Selection<Anchor>]>,
  897    ) {
  898        self.selections_by_transaction
  899            .insert(transaction_id, (selections, None));
  900    }
  901
  902    #[allow(clippy::type_complexity)]
  903    fn transaction(
  904        &self,
  905        transaction_id: TransactionId,
  906    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  907        self.selections_by_transaction.get(&transaction_id)
  908    }
  909
  910    #[allow(clippy::type_complexity)]
  911    fn transaction_mut(
  912        &mut self,
  913        transaction_id: TransactionId,
  914    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  915        self.selections_by_transaction.get_mut(&transaction_id)
  916    }
  917
  918    fn push(&mut self, entry: SelectionHistoryEntry) {
  919        if !entry.selections.is_empty() {
  920            match self.mode {
  921                SelectionHistoryMode::Normal => {
  922                    self.push_undo(entry);
  923                    self.redo_stack.clear();
  924                }
  925                SelectionHistoryMode::Undoing => self.push_redo(entry),
  926                SelectionHistoryMode::Redoing => self.push_undo(entry),
  927            }
  928        }
  929    }
  930
  931    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  932        if self
  933            .undo_stack
  934            .back()
  935            .map_or(true, |e| e.selections != entry.selections)
  936        {
  937            self.undo_stack.push_back(entry);
  938            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  939                self.undo_stack.pop_front();
  940            }
  941        }
  942    }
  943
  944    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  945        if self
  946            .redo_stack
  947            .back()
  948            .map_or(true, |e| e.selections != entry.selections)
  949        {
  950            self.redo_stack.push_back(entry);
  951            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  952                self.redo_stack.pop_front();
  953            }
  954        }
  955    }
  956}
  957
  958struct RowHighlight {
  959    index: usize,
  960    range: Range<Anchor>,
  961    color: Hsla,
  962    should_autoscroll: bool,
  963}
  964
  965#[derive(Clone, Debug)]
  966struct AddSelectionsState {
  967    above: bool,
  968    stack: Vec<usize>,
  969}
  970
  971#[derive(Clone)]
  972struct SelectNextState {
  973    query: AhoCorasick,
  974    wordwise: bool,
  975    done: bool,
  976}
  977
  978impl std::fmt::Debug for SelectNextState {
  979    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  980        f.debug_struct(std::any::type_name::<Self>())
  981            .field("wordwise", &self.wordwise)
  982            .field("done", &self.done)
  983            .finish()
  984    }
  985}
  986
  987#[derive(Debug)]
  988struct AutocloseRegion {
  989    selection_id: usize,
  990    range: Range<Anchor>,
  991    pair: BracketPair,
  992}
  993
  994#[derive(Debug)]
  995struct SnippetState {
  996    ranges: Vec<Vec<Range<Anchor>>>,
  997    active_index: usize,
  998    choices: Vec<Option<Vec<String>>>,
  999}
 1000
 1001#[doc(hidden)]
 1002pub struct RenameState {
 1003    pub range: Range<Anchor>,
 1004    pub old_name: Arc<str>,
 1005    pub editor: Entity<Editor>,
 1006    block_id: CustomBlockId,
 1007}
 1008
 1009struct InvalidationStack<T>(Vec<T>);
 1010
 1011struct RegisteredInlineCompletionProvider {
 1012    provider: Arc<dyn InlineCompletionProviderHandle>,
 1013    _subscription: Subscription,
 1014}
 1015
 1016#[derive(Debug)]
 1017struct ActiveDiagnosticGroup {
 1018    primary_range: Range<Anchor>,
 1019    primary_message: String,
 1020    group_id: usize,
 1021    blocks: HashMap<CustomBlockId, Diagnostic>,
 1022    is_valid: bool,
 1023}
 1024
 1025#[derive(Serialize, Deserialize, Clone, Debug)]
 1026pub struct ClipboardSelection {
 1027    pub len: usize,
 1028    pub is_entire_line: bool,
 1029    pub first_line_indent: u32,
 1030}
 1031
 1032#[derive(Debug)]
 1033pub(crate) struct NavigationData {
 1034    cursor_anchor: Anchor,
 1035    cursor_position: Point,
 1036    scroll_anchor: ScrollAnchor,
 1037    scroll_top_row: u32,
 1038}
 1039
 1040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1041pub enum GotoDefinitionKind {
 1042    Symbol,
 1043    Declaration,
 1044    Type,
 1045    Implementation,
 1046}
 1047
 1048#[derive(Debug, Clone)]
 1049enum InlayHintRefreshReason {
 1050    Toggle(bool),
 1051    SettingsChange(InlayHintSettings),
 1052    NewLinesShown,
 1053    BufferEdited(HashSet<Arc<Language>>),
 1054    RefreshRequested,
 1055    ExcerptsRemoved(Vec<ExcerptId>),
 1056}
 1057
 1058impl InlayHintRefreshReason {
 1059    fn description(&self) -> &'static str {
 1060        match self {
 1061            Self::Toggle(_) => "toggle",
 1062            Self::SettingsChange(_) => "settings change",
 1063            Self::NewLinesShown => "new lines shown",
 1064            Self::BufferEdited(_) => "buffer edited",
 1065            Self::RefreshRequested => "refresh requested",
 1066            Self::ExcerptsRemoved(_) => "excerpts removed",
 1067        }
 1068    }
 1069}
 1070
 1071pub enum FormatTarget {
 1072    Buffers,
 1073    Ranges(Vec<Range<MultiBufferPoint>>),
 1074}
 1075
 1076pub(crate) struct FocusedBlock {
 1077    id: BlockId,
 1078    focus_handle: WeakFocusHandle,
 1079}
 1080
 1081#[derive(Clone)]
 1082enum JumpData {
 1083    MultiBufferRow {
 1084        row: MultiBufferRow,
 1085        line_offset_from_top: u32,
 1086    },
 1087    MultiBufferPoint {
 1088        excerpt_id: ExcerptId,
 1089        position: Point,
 1090        anchor: text::Anchor,
 1091        line_offset_from_top: u32,
 1092    },
 1093}
 1094
 1095pub enum MultibufferSelectionMode {
 1096    First,
 1097    All,
 1098}
 1099
 1100impl Editor {
 1101    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1102        let buffer = cx.new(|cx| Buffer::local("", cx));
 1103        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1104        Self::new(
 1105            EditorMode::SingleLine { auto_width: false },
 1106            buffer,
 1107            None,
 1108            false,
 1109            window,
 1110            cx,
 1111        )
 1112    }
 1113
 1114    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1115        let buffer = cx.new(|cx| Buffer::local("", cx));
 1116        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1117        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1118    }
 1119
 1120    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1121        let buffer = cx.new(|cx| Buffer::local("", cx));
 1122        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1123        Self::new(
 1124            EditorMode::SingleLine { auto_width: true },
 1125            buffer,
 1126            None,
 1127            false,
 1128            window,
 1129            cx,
 1130        )
 1131    }
 1132
 1133    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1134        let buffer = cx.new(|cx| Buffer::local("", cx));
 1135        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1136        Self::new(
 1137            EditorMode::AutoHeight { max_lines },
 1138            buffer,
 1139            None,
 1140            false,
 1141            window,
 1142            cx,
 1143        )
 1144    }
 1145
 1146    pub fn for_buffer(
 1147        buffer: Entity<Buffer>,
 1148        project: Option<Entity<Project>>,
 1149        window: &mut Window,
 1150        cx: &mut Context<Self>,
 1151    ) -> Self {
 1152        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1153        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1154    }
 1155
 1156    pub fn for_multibuffer(
 1157        buffer: Entity<MultiBuffer>,
 1158        project: Option<Entity<Project>>,
 1159        show_excerpt_controls: bool,
 1160        window: &mut Window,
 1161        cx: &mut Context<Self>,
 1162    ) -> Self {
 1163        Self::new(
 1164            EditorMode::Full,
 1165            buffer,
 1166            project,
 1167            show_excerpt_controls,
 1168            window,
 1169            cx,
 1170        )
 1171    }
 1172
 1173    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1174        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1175        let mut clone = Self::new(
 1176            self.mode,
 1177            self.buffer.clone(),
 1178            self.project.clone(),
 1179            show_excerpt_controls,
 1180            window,
 1181            cx,
 1182        );
 1183        self.display_map.update(cx, |display_map, cx| {
 1184            let snapshot = display_map.snapshot(cx);
 1185            clone.display_map.update(cx, |display_map, cx| {
 1186                display_map.set_state(&snapshot, cx);
 1187            });
 1188        });
 1189        clone.selections.clone_state(&self.selections);
 1190        clone.scroll_manager.clone_state(&self.scroll_manager);
 1191        clone.searchable = self.searchable;
 1192        clone
 1193    }
 1194
 1195    pub fn new(
 1196        mode: EditorMode,
 1197        buffer: Entity<MultiBuffer>,
 1198        project: Option<Entity<Project>>,
 1199        show_excerpt_controls: bool,
 1200        window: &mut Window,
 1201        cx: &mut Context<Self>,
 1202    ) -> Self {
 1203        let style = window.text_style();
 1204        let font_size = style.font_size.to_pixels(window.rem_size());
 1205        let editor = cx.entity().downgrade();
 1206        let fold_placeholder = FoldPlaceholder {
 1207            constrain_width: true,
 1208            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1209                let editor = editor.clone();
 1210                div()
 1211                    .id(fold_id)
 1212                    .bg(cx.theme().colors().ghost_element_background)
 1213                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1214                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1215                    .rounded_sm()
 1216                    .size_full()
 1217                    .cursor_pointer()
 1218                    .child("")
 1219                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1220                    .on_click(move |_, _window, cx| {
 1221                        editor
 1222                            .update(cx, |editor, cx| {
 1223                                editor.unfold_ranges(
 1224                                    &[fold_range.start..fold_range.end],
 1225                                    true,
 1226                                    false,
 1227                                    cx,
 1228                                );
 1229                                cx.stop_propagation();
 1230                            })
 1231                            .ok();
 1232                    })
 1233                    .into_any()
 1234            }),
 1235            merge_adjacent: true,
 1236            ..Default::default()
 1237        };
 1238        let display_map = cx.new(|cx| {
 1239            DisplayMap::new(
 1240                buffer.clone(),
 1241                style.font(),
 1242                font_size,
 1243                None,
 1244                show_excerpt_controls,
 1245                FILE_HEADER_HEIGHT,
 1246                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1247                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1248                fold_placeholder,
 1249                cx,
 1250            )
 1251        });
 1252
 1253        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1254
 1255        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1256
 1257        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1258            .then(|| language_settings::SoftWrap::None);
 1259
 1260        let mut project_subscriptions = Vec::new();
 1261        if mode == EditorMode::Full {
 1262            if let Some(project) = project.as_ref() {
 1263                if buffer.read(cx).is_singleton() {
 1264                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1265                        cx.emit(EditorEvent::TitleChanged);
 1266                    }));
 1267                }
 1268                project_subscriptions.push(cx.subscribe_in(
 1269                    project,
 1270                    window,
 1271                    |editor, _, event, window, cx| {
 1272                        if let project::Event::RefreshInlayHints = event {
 1273                            editor
 1274                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1275                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1276                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1277                                let focus_handle = editor.focus_handle(cx);
 1278                                if focus_handle.is_focused(window) {
 1279                                    let snapshot = buffer.read(cx).snapshot();
 1280                                    for (range, snippet) in snippet_edits {
 1281                                        let editor_range =
 1282                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1283                                        editor
 1284                                            .insert_snippet(
 1285                                                &[editor_range],
 1286                                                snippet.clone(),
 1287                                                window,
 1288                                                cx,
 1289                                            )
 1290                                            .ok();
 1291                                    }
 1292                                }
 1293                            }
 1294                        }
 1295                    },
 1296                ));
 1297                if let Some(task_inventory) = project
 1298                    .read(cx)
 1299                    .task_store()
 1300                    .read(cx)
 1301                    .task_inventory()
 1302                    .cloned()
 1303                {
 1304                    project_subscriptions.push(cx.observe_in(
 1305                        &task_inventory,
 1306                        window,
 1307                        |editor, _, window, cx| {
 1308                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1309                        },
 1310                    ));
 1311                }
 1312            }
 1313        }
 1314
 1315        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1316
 1317        let inlay_hint_settings =
 1318            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1319        let focus_handle = cx.focus_handle();
 1320        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1321            .detach();
 1322        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1323            .detach();
 1324        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1325            .detach();
 1326        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1327            .detach();
 1328
 1329        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1330            Some(false)
 1331        } else {
 1332            None
 1333        };
 1334
 1335        let mut code_action_providers = Vec::new();
 1336        let mut load_uncommitted_diff = None;
 1337        if let Some(project) = project.clone() {
 1338            load_uncommitted_diff = Some(
 1339                get_uncommitted_diff_for_buffer(
 1340                    &project,
 1341                    buffer.read(cx).all_buffers(),
 1342                    buffer.clone(),
 1343                    cx,
 1344                )
 1345                .shared(),
 1346            );
 1347            code_action_providers.push(Rc::new(project) as Rc<_>);
 1348        }
 1349
 1350        let mut this = Self {
 1351            focus_handle,
 1352            show_cursor_when_unfocused: false,
 1353            last_focused_descendant: None,
 1354            buffer: buffer.clone(),
 1355            display_map: display_map.clone(),
 1356            selections,
 1357            scroll_manager: ScrollManager::new(cx),
 1358            columnar_selection_tail: None,
 1359            add_selections_state: None,
 1360            select_next_state: None,
 1361            select_prev_state: None,
 1362            selection_history: Default::default(),
 1363            autoclose_regions: Default::default(),
 1364            snippet_stack: Default::default(),
 1365            select_larger_syntax_node_stack: Vec::new(),
 1366            ime_transaction: Default::default(),
 1367            active_diagnostics: None,
 1368            soft_wrap_mode_override,
 1369            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1370            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1371            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1372            project,
 1373            blink_manager: blink_manager.clone(),
 1374            show_local_selections: true,
 1375            show_scrollbars: true,
 1376            mode,
 1377            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1378            show_gutter: mode == EditorMode::Full,
 1379            show_line_numbers: None,
 1380            use_relative_line_numbers: None,
 1381            show_git_diff_gutter: None,
 1382            show_code_actions: None,
 1383            show_runnables: None,
 1384            show_wrap_guides: None,
 1385            show_indent_guides,
 1386            placeholder_text: None,
 1387            highlight_order: 0,
 1388            highlighted_rows: HashMap::default(),
 1389            background_highlights: Default::default(),
 1390            gutter_highlights: TreeMap::default(),
 1391            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1392            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1393            nav_history: None,
 1394            context_menu: RefCell::new(None),
 1395            mouse_context_menu: None,
 1396            completion_tasks: Default::default(),
 1397            signature_help_state: SignatureHelpState::default(),
 1398            auto_signature_help: None,
 1399            find_all_references_task_sources: Vec::new(),
 1400            next_completion_id: 0,
 1401            next_inlay_id: 0,
 1402            code_action_providers,
 1403            available_code_actions: Default::default(),
 1404            code_actions_task: Default::default(),
 1405            selection_highlight_task: Default::default(),
 1406            document_highlights_task: Default::default(),
 1407            linked_editing_range_task: Default::default(),
 1408            pending_rename: Default::default(),
 1409            searchable: true,
 1410            cursor_shape: EditorSettings::get_global(cx)
 1411                .cursor_shape
 1412                .unwrap_or_default(),
 1413            current_line_highlight: None,
 1414            autoindent_mode: Some(AutoindentMode::EachLine),
 1415            collapse_matches: false,
 1416            workspace: None,
 1417            input_enabled: true,
 1418            use_modal_editing: mode == EditorMode::Full,
 1419            read_only: false,
 1420            use_autoclose: true,
 1421            use_auto_surround: true,
 1422            auto_replace_emoji_shortcode: false,
 1423            leader_peer_id: None,
 1424            remote_id: None,
 1425            hover_state: Default::default(),
 1426            pending_mouse_down: None,
 1427            hovered_link_state: Default::default(),
 1428            edit_prediction_provider: None,
 1429            active_inline_completion: None,
 1430            stale_inline_completion_in_menu: None,
 1431            edit_prediction_preview: EditPredictionPreview::Inactive,
 1432            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1433
 1434            gutter_hovered: false,
 1435            pixel_position_of_newest_cursor: None,
 1436            last_bounds: None,
 1437            last_position_map: None,
 1438            expect_bounds_change: None,
 1439            gutter_dimensions: GutterDimensions::default(),
 1440            style: None,
 1441            show_cursor_names: false,
 1442            hovered_cursors: Default::default(),
 1443            next_editor_action_id: EditorActionId::default(),
 1444            editor_actions: Rc::default(),
 1445            inline_completions_hidden_for_vim_mode: false,
 1446            show_inline_completions_override: None,
 1447            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1448            edit_prediction_settings: EditPredictionSettings::Disabled,
 1449            edit_prediction_cursor_on_leading_whitespace: false,
 1450            edit_prediction_requires_modifier_in_leading_space: true,
 1451            custom_context_menu: None,
 1452            show_git_blame_gutter: false,
 1453            show_git_blame_inline: false,
 1454            distinguish_unstaged_diff_hunks: false,
 1455            show_selection_menu: None,
 1456            show_git_blame_inline_delay_task: None,
 1457            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1458            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1459                .session
 1460                .restore_unsaved_buffers,
 1461            blame: None,
 1462            blame_subscription: None,
 1463            tasks: Default::default(),
 1464            _subscriptions: vec![
 1465                cx.observe(&buffer, Self::on_buffer_changed),
 1466                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1467                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1468                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1469                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1470                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1471                cx.observe_window_activation(window, |editor, window, cx| {
 1472                    let active = window.is_window_active();
 1473                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1474                        if active {
 1475                            blink_manager.enable(cx);
 1476                        } else {
 1477                            blink_manager.disable(cx);
 1478                        }
 1479                    });
 1480                }),
 1481            ],
 1482            tasks_update_task: None,
 1483            linked_edit_ranges: Default::default(),
 1484            in_project_search: false,
 1485            previous_search_ranges: None,
 1486            breadcrumb_header: None,
 1487            focused_block: None,
 1488            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1489            addons: HashMap::default(),
 1490            registered_buffers: HashMap::default(),
 1491            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1492            selection_mark_mode: false,
 1493            toggle_fold_multiple_buffers: Task::ready(()),
 1494            serialize_selections: Task::ready(()),
 1495            text_style_refinement: None,
 1496            load_diff_task: load_uncommitted_diff,
 1497        };
 1498        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1499        this._subscriptions.extend(project_subscriptions);
 1500
 1501        this.end_selection(window, cx);
 1502        this.scroll_manager.show_scrollbar(window, cx);
 1503
 1504        if mode == EditorMode::Full {
 1505            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1506            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1507
 1508            if this.git_blame_inline_enabled {
 1509                this.git_blame_inline_enabled = true;
 1510                this.start_git_blame_inline(false, window, cx);
 1511            }
 1512
 1513            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1514                if let Some(project) = this.project.as_ref() {
 1515                    let handle = project.update(cx, |project, cx| {
 1516                        project.register_buffer_with_language_servers(&buffer, cx)
 1517                    });
 1518                    this.registered_buffers
 1519                        .insert(buffer.read(cx).remote_id(), handle);
 1520                }
 1521            }
 1522        }
 1523
 1524        this.report_editor_event("Editor Opened", None, cx);
 1525        this
 1526    }
 1527
 1528    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1529        self.mouse_context_menu
 1530            .as_ref()
 1531            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1532    }
 1533
 1534    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1535        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1536    }
 1537
 1538    fn key_context_internal(
 1539        &self,
 1540        has_active_edit_prediction: bool,
 1541        window: &Window,
 1542        cx: &App,
 1543    ) -> KeyContext {
 1544        let mut key_context = KeyContext::new_with_defaults();
 1545        key_context.add("Editor");
 1546        let mode = match self.mode {
 1547            EditorMode::SingleLine { .. } => "single_line",
 1548            EditorMode::AutoHeight { .. } => "auto_height",
 1549            EditorMode::Full => "full",
 1550        };
 1551
 1552        if EditorSettings::jupyter_enabled(cx) {
 1553            key_context.add("jupyter");
 1554        }
 1555
 1556        key_context.set("mode", mode);
 1557        if self.pending_rename.is_some() {
 1558            key_context.add("renaming");
 1559        }
 1560
 1561        match self.context_menu.borrow().as_ref() {
 1562            Some(CodeContextMenu::Completions(_)) => {
 1563                key_context.add("menu");
 1564                key_context.add("showing_completions");
 1565            }
 1566            Some(CodeContextMenu::CodeActions(_)) => {
 1567                key_context.add("menu");
 1568                key_context.add("showing_code_actions")
 1569            }
 1570            None => {}
 1571        }
 1572
 1573        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1574        if !self.focus_handle(cx).contains_focused(window, cx)
 1575            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1576        {
 1577            for addon in self.addons.values() {
 1578                addon.extend_key_context(&mut key_context, cx)
 1579            }
 1580        }
 1581
 1582        if let Some(extension) = self
 1583            .buffer
 1584            .read(cx)
 1585            .as_singleton()
 1586            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1587        {
 1588            key_context.set("extension", extension.to_string());
 1589        }
 1590
 1591        if has_active_edit_prediction {
 1592            if self.edit_prediction_in_conflict() {
 1593                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1594            } else {
 1595                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1596                key_context.add("copilot_suggestion");
 1597            }
 1598        }
 1599
 1600        if self.selection_mark_mode {
 1601            key_context.add("selection_mode");
 1602        }
 1603
 1604        key_context
 1605    }
 1606
 1607    pub fn edit_prediction_in_conflict(&self) -> bool {
 1608        if !self.show_edit_predictions_in_menu() {
 1609            return false;
 1610        }
 1611
 1612        let showing_completions = self
 1613            .context_menu
 1614            .borrow()
 1615            .as_ref()
 1616            .map_or(false, |context| {
 1617                matches!(context, CodeContextMenu::Completions(_))
 1618            });
 1619
 1620        showing_completions
 1621            || self.edit_prediction_requires_modifier()
 1622            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1623            // bindings to insert tab characters.
 1624            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1625    }
 1626
 1627    pub fn accept_edit_prediction_keybind(
 1628        &self,
 1629        window: &Window,
 1630        cx: &App,
 1631    ) -> AcceptEditPredictionBinding {
 1632        let key_context = self.key_context_internal(true, window, cx);
 1633        let in_conflict = self.edit_prediction_in_conflict();
 1634
 1635        AcceptEditPredictionBinding(
 1636            window
 1637                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1638                .into_iter()
 1639                .filter(|binding| {
 1640                    !in_conflict
 1641                        || binding
 1642                            .keystrokes()
 1643                            .first()
 1644                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1645                })
 1646                .rev()
 1647                .min_by_key(|binding| {
 1648                    binding
 1649                        .keystrokes()
 1650                        .first()
 1651                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1652                }),
 1653        )
 1654    }
 1655
 1656    pub fn new_file(
 1657        workspace: &mut Workspace,
 1658        _: &workspace::NewFile,
 1659        window: &mut Window,
 1660        cx: &mut Context<Workspace>,
 1661    ) {
 1662        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1663            "Failed to create buffer",
 1664            window,
 1665            cx,
 1666            |e, _, _| match e.error_code() {
 1667                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1668                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1669                e.error_tag("required").unwrap_or("the latest version")
 1670            )),
 1671                _ => None,
 1672            },
 1673        );
 1674    }
 1675
 1676    pub fn new_in_workspace(
 1677        workspace: &mut Workspace,
 1678        window: &mut Window,
 1679        cx: &mut Context<Workspace>,
 1680    ) -> Task<Result<Entity<Editor>>> {
 1681        let project = workspace.project().clone();
 1682        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1683
 1684        cx.spawn_in(window, |workspace, mut cx| async move {
 1685            let buffer = create.await?;
 1686            workspace.update_in(&mut cx, |workspace, window, cx| {
 1687                let editor =
 1688                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1689                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1690                editor
 1691            })
 1692        })
 1693    }
 1694
 1695    fn new_file_vertical(
 1696        workspace: &mut Workspace,
 1697        _: &workspace::NewFileSplitVertical,
 1698        window: &mut Window,
 1699        cx: &mut Context<Workspace>,
 1700    ) {
 1701        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1702    }
 1703
 1704    fn new_file_horizontal(
 1705        workspace: &mut Workspace,
 1706        _: &workspace::NewFileSplitHorizontal,
 1707        window: &mut Window,
 1708        cx: &mut Context<Workspace>,
 1709    ) {
 1710        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1711    }
 1712
 1713    fn new_file_in_direction(
 1714        workspace: &mut Workspace,
 1715        direction: SplitDirection,
 1716        window: &mut Window,
 1717        cx: &mut Context<Workspace>,
 1718    ) {
 1719        let project = workspace.project().clone();
 1720        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1721
 1722        cx.spawn_in(window, |workspace, mut cx| async move {
 1723            let buffer = create.await?;
 1724            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1725                workspace.split_item(
 1726                    direction,
 1727                    Box::new(
 1728                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1729                    ),
 1730                    window,
 1731                    cx,
 1732                )
 1733            })?;
 1734            anyhow::Ok(())
 1735        })
 1736        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1737            match e.error_code() {
 1738                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1739                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1740                e.error_tag("required").unwrap_or("the latest version")
 1741            )),
 1742                _ => None,
 1743            }
 1744        });
 1745    }
 1746
 1747    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1748        self.leader_peer_id
 1749    }
 1750
 1751    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1752        &self.buffer
 1753    }
 1754
 1755    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1756        self.workspace.as_ref()?.0.upgrade()
 1757    }
 1758
 1759    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1760        self.buffer().read(cx).title(cx)
 1761    }
 1762
 1763    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1764        let git_blame_gutter_max_author_length = self
 1765            .render_git_blame_gutter(cx)
 1766            .then(|| {
 1767                if let Some(blame) = self.blame.as_ref() {
 1768                    let max_author_length =
 1769                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1770                    Some(max_author_length)
 1771                } else {
 1772                    None
 1773                }
 1774            })
 1775            .flatten();
 1776
 1777        EditorSnapshot {
 1778            mode: self.mode,
 1779            show_gutter: self.show_gutter,
 1780            show_line_numbers: self.show_line_numbers,
 1781            show_git_diff_gutter: self.show_git_diff_gutter,
 1782            show_code_actions: self.show_code_actions,
 1783            show_runnables: self.show_runnables,
 1784            git_blame_gutter_max_author_length,
 1785            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1786            scroll_anchor: self.scroll_manager.anchor(),
 1787            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1788            placeholder_text: self.placeholder_text.clone(),
 1789            is_focused: self.focus_handle.is_focused(window),
 1790            current_line_highlight: self
 1791                .current_line_highlight
 1792                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1793            gutter_hovered: self.gutter_hovered,
 1794        }
 1795    }
 1796
 1797    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1798        self.buffer.read(cx).language_at(point, cx)
 1799    }
 1800
 1801    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1802        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1803    }
 1804
 1805    pub fn active_excerpt(
 1806        &self,
 1807        cx: &App,
 1808    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1809        self.buffer
 1810            .read(cx)
 1811            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1812    }
 1813
 1814    pub fn mode(&self) -> EditorMode {
 1815        self.mode
 1816    }
 1817
 1818    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1819        self.collaboration_hub.as_deref()
 1820    }
 1821
 1822    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1823        self.collaboration_hub = Some(hub);
 1824    }
 1825
 1826    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1827        self.in_project_search = in_project_search;
 1828    }
 1829
 1830    pub fn set_custom_context_menu(
 1831        &mut self,
 1832        f: impl 'static
 1833            + Fn(
 1834                &mut Self,
 1835                DisplayPoint,
 1836                &mut Window,
 1837                &mut Context<Self>,
 1838            ) -> Option<Entity<ui::ContextMenu>>,
 1839    ) {
 1840        self.custom_context_menu = Some(Box::new(f))
 1841    }
 1842
 1843    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1844        self.completion_provider = provider;
 1845    }
 1846
 1847    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1848        self.semantics_provider.clone()
 1849    }
 1850
 1851    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1852        self.semantics_provider = provider;
 1853    }
 1854
 1855    pub fn set_edit_prediction_provider<T>(
 1856        &mut self,
 1857        provider: Option<Entity<T>>,
 1858        window: &mut Window,
 1859        cx: &mut Context<Self>,
 1860    ) where
 1861        T: EditPredictionProvider,
 1862    {
 1863        self.edit_prediction_provider =
 1864            provider.map(|provider| RegisteredInlineCompletionProvider {
 1865                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1866                    if this.focus_handle.is_focused(window) {
 1867                        this.update_visible_inline_completion(window, cx);
 1868                    }
 1869                }),
 1870                provider: Arc::new(provider),
 1871            });
 1872        self.refresh_inline_completion(false, false, window, cx);
 1873    }
 1874
 1875    pub fn placeholder_text(&self) -> Option<&str> {
 1876        self.placeholder_text.as_deref()
 1877    }
 1878
 1879    pub fn set_placeholder_text(
 1880        &mut self,
 1881        placeholder_text: impl Into<Arc<str>>,
 1882        cx: &mut Context<Self>,
 1883    ) {
 1884        let placeholder_text = Some(placeholder_text.into());
 1885        if self.placeholder_text != placeholder_text {
 1886            self.placeholder_text = placeholder_text;
 1887            cx.notify();
 1888        }
 1889    }
 1890
 1891    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1892        self.cursor_shape = cursor_shape;
 1893
 1894        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1895        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1896
 1897        cx.notify();
 1898    }
 1899
 1900    pub fn set_current_line_highlight(
 1901        &mut self,
 1902        current_line_highlight: Option<CurrentLineHighlight>,
 1903    ) {
 1904        self.current_line_highlight = current_line_highlight;
 1905    }
 1906
 1907    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1908        self.collapse_matches = collapse_matches;
 1909    }
 1910
 1911    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1912        let buffers = self.buffer.read(cx).all_buffers();
 1913        let Some(project) = self.project.as_ref() else {
 1914            return;
 1915        };
 1916        project.update(cx, |project, cx| {
 1917            for buffer in buffers {
 1918                self.registered_buffers
 1919                    .entry(buffer.read(cx).remote_id())
 1920                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1921            }
 1922        })
 1923    }
 1924
 1925    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1926        if self.collapse_matches {
 1927            return range.start..range.start;
 1928        }
 1929        range.clone()
 1930    }
 1931
 1932    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1933        if self.display_map.read(cx).clip_at_line_ends != clip {
 1934            self.display_map
 1935                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1936        }
 1937    }
 1938
 1939    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1940        self.input_enabled = input_enabled;
 1941    }
 1942
 1943    pub fn set_inline_completions_hidden_for_vim_mode(
 1944        &mut self,
 1945        hidden: bool,
 1946        window: &mut Window,
 1947        cx: &mut Context<Self>,
 1948    ) {
 1949        if hidden != self.inline_completions_hidden_for_vim_mode {
 1950            self.inline_completions_hidden_for_vim_mode = hidden;
 1951            if hidden {
 1952                self.update_visible_inline_completion(window, cx);
 1953            } else {
 1954                self.refresh_inline_completion(true, false, window, cx);
 1955            }
 1956        }
 1957    }
 1958
 1959    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1960        self.menu_inline_completions_policy = value;
 1961    }
 1962
 1963    pub fn set_autoindent(&mut self, autoindent: bool) {
 1964        if autoindent {
 1965            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1966        } else {
 1967            self.autoindent_mode = None;
 1968        }
 1969    }
 1970
 1971    pub fn read_only(&self, cx: &App) -> bool {
 1972        self.read_only || self.buffer.read(cx).read_only()
 1973    }
 1974
 1975    pub fn set_read_only(&mut self, read_only: bool) {
 1976        self.read_only = read_only;
 1977    }
 1978
 1979    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1980        self.use_autoclose = autoclose;
 1981    }
 1982
 1983    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1984        self.use_auto_surround = auto_surround;
 1985    }
 1986
 1987    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1988        self.auto_replace_emoji_shortcode = auto_replace;
 1989    }
 1990
 1991    pub fn toggle_inline_completions(
 1992        &mut self,
 1993        _: &ToggleEditPrediction,
 1994        window: &mut Window,
 1995        cx: &mut Context<Self>,
 1996    ) {
 1997        if self.show_inline_completions_override.is_some() {
 1998            self.set_show_edit_predictions(None, window, cx);
 1999        } else {
 2000            let show_edit_predictions = !self.edit_predictions_enabled();
 2001            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2002        }
 2003    }
 2004
 2005    pub fn set_show_edit_predictions(
 2006        &mut self,
 2007        show_edit_predictions: Option<bool>,
 2008        window: &mut Window,
 2009        cx: &mut Context<Self>,
 2010    ) {
 2011        self.show_inline_completions_override = show_edit_predictions;
 2012        self.refresh_inline_completion(false, true, window, cx);
 2013    }
 2014
 2015    fn inline_completions_disabled_in_scope(
 2016        &self,
 2017        buffer: &Entity<Buffer>,
 2018        buffer_position: language::Anchor,
 2019        cx: &App,
 2020    ) -> bool {
 2021        let snapshot = buffer.read(cx).snapshot();
 2022        let settings = snapshot.settings_at(buffer_position, cx);
 2023
 2024        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2025            return false;
 2026        };
 2027
 2028        scope.override_name().map_or(false, |scope_name| {
 2029            settings
 2030                .edit_predictions_disabled_in
 2031                .iter()
 2032                .any(|s| s == scope_name)
 2033        })
 2034    }
 2035
 2036    pub fn set_use_modal_editing(&mut self, to: bool) {
 2037        self.use_modal_editing = to;
 2038    }
 2039
 2040    pub fn use_modal_editing(&self) -> bool {
 2041        self.use_modal_editing
 2042    }
 2043
 2044    fn selections_did_change(
 2045        &mut self,
 2046        local: bool,
 2047        old_cursor_position: &Anchor,
 2048        show_completions: bool,
 2049        window: &mut Window,
 2050        cx: &mut Context<Self>,
 2051    ) {
 2052        window.invalidate_character_coordinates();
 2053
 2054        // Copy selections to primary selection buffer
 2055        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2056        if local {
 2057            let selections = self.selections.all::<usize>(cx);
 2058            let buffer_handle = self.buffer.read(cx).read(cx);
 2059
 2060            let mut text = String::new();
 2061            for (index, selection) in selections.iter().enumerate() {
 2062                let text_for_selection = buffer_handle
 2063                    .text_for_range(selection.start..selection.end)
 2064                    .collect::<String>();
 2065
 2066                text.push_str(&text_for_selection);
 2067                if index != selections.len() - 1 {
 2068                    text.push('\n');
 2069                }
 2070            }
 2071
 2072            if !text.is_empty() {
 2073                cx.write_to_primary(ClipboardItem::new_string(text));
 2074            }
 2075        }
 2076
 2077        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2078            self.buffer.update(cx, |buffer, cx| {
 2079                buffer.set_active_selections(
 2080                    &self.selections.disjoint_anchors(),
 2081                    self.selections.line_mode,
 2082                    self.cursor_shape,
 2083                    cx,
 2084                )
 2085            });
 2086        }
 2087        let display_map = self
 2088            .display_map
 2089            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2090        let buffer = &display_map.buffer_snapshot;
 2091        self.add_selections_state = None;
 2092        self.select_next_state = None;
 2093        self.select_prev_state = None;
 2094        self.select_larger_syntax_node_stack.clear();
 2095        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2096        self.snippet_stack
 2097            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2098        self.take_rename(false, window, cx);
 2099
 2100        let new_cursor_position = self.selections.newest_anchor().head();
 2101
 2102        self.push_to_nav_history(
 2103            *old_cursor_position,
 2104            Some(new_cursor_position.to_point(buffer)),
 2105            cx,
 2106        );
 2107
 2108        if local {
 2109            let new_cursor_position = self.selections.newest_anchor().head();
 2110            let mut context_menu = self.context_menu.borrow_mut();
 2111            let completion_menu = match context_menu.as_ref() {
 2112                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2113                _ => {
 2114                    *context_menu = None;
 2115                    None
 2116                }
 2117            };
 2118            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2119                if !self.registered_buffers.contains_key(&buffer_id) {
 2120                    if let Some(project) = self.project.as_ref() {
 2121                        project.update(cx, |project, cx| {
 2122                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2123                                return;
 2124                            };
 2125                            self.registered_buffers.insert(
 2126                                buffer_id,
 2127                                project.register_buffer_with_language_servers(&buffer, cx),
 2128                            );
 2129                        })
 2130                    }
 2131                }
 2132            }
 2133
 2134            if let Some(completion_menu) = completion_menu {
 2135                let cursor_position = new_cursor_position.to_offset(buffer);
 2136                let (word_range, kind) =
 2137                    buffer.surrounding_word(completion_menu.initial_position, true);
 2138                if kind == Some(CharKind::Word)
 2139                    && word_range.to_inclusive().contains(&cursor_position)
 2140                {
 2141                    let mut completion_menu = completion_menu.clone();
 2142                    drop(context_menu);
 2143
 2144                    let query = Self::completion_query(buffer, cursor_position);
 2145                    cx.spawn(move |this, mut cx| async move {
 2146                        completion_menu
 2147                            .filter(query.as_deref(), cx.background_executor().clone())
 2148                            .await;
 2149
 2150                        this.update(&mut cx, |this, cx| {
 2151                            let mut context_menu = this.context_menu.borrow_mut();
 2152                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2153                            else {
 2154                                return;
 2155                            };
 2156
 2157                            if menu.id > completion_menu.id {
 2158                                return;
 2159                            }
 2160
 2161                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2162                            drop(context_menu);
 2163                            cx.notify();
 2164                        })
 2165                    })
 2166                    .detach();
 2167
 2168                    if show_completions {
 2169                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2170                    }
 2171                } else {
 2172                    drop(context_menu);
 2173                    self.hide_context_menu(window, cx);
 2174                }
 2175            } else {
 2176                drop(context_menu);
 2177            }
 2178
 2179            hide_hover(self, cx);
 2180
 2181            if old_cursor_position.to_display_point(&display_map).row()
 2182                != new_cursor_position.to_display_point(&display_map).row()
 2183            {
 2184                self.available_code_actions.take();
 2185            }
 2186            self.refresh_code_actions(window, cx);
 2187            self.refresh_document_highlights(cx);
 2188            self.refresh_selected_text_highlights(window, cx);
 2189            refresh_matching_bracket_highlights(self, window, cx);
 2190            self.update_visible_inline_completion(window, cx);
 2191            self.edit_prediction_requires_modifier_in_leading_space = true;
 2192            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2193            if self.git_blame_inline_enabled {
 2194                self.start_inline_blame_timer(window, cx);
 2195            }
 2196        }
 2197
 2198        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2199        cx.emit(EditorEvent::SelectionsChanged { local });
 2200
 2201        let selections = &self.selections.disjoint;
 2202        if selections.len() == 1 {
 2203            cx.emit(SearchEvent::ActiveMatchChanged)
 2204        }
 2205        if local
 2206            && self.is_singleton(cx)
 2207            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2208        {
 2209            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2210                let background_executor = cx.background_executor().clone();
 2211                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2212                let snapshot = self.buffer().read(cx).snapshot(cx);
 2213                let selections = selections.clone();
 2214                self.serialize_selections = cx.background_spawn(async move {
 2215                    background_executor.timer(Duration::from_millis(100)).await;
 2216                    let selections = selections
 2217                        .iter()
 2218                        .map(|selection| {
 2219                            (
 2220                                selection.start.to_offset(&snapshot),
 2221                                selection.end.to_offset(&snapshot),
 2222                            )
 2223                        })
 2224                        .collect();
 2225                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2226                        .await
 2227                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2228                        .log_err();
 2229                });
 2230            }
 2231        }
 2232
 2233        cx.notify();
 2234    }
 2235
 2236    pub fn change_selections<R>(
 2237        &mut self,
 2238        autoscroll: Option<Autoscroll>,
 2239        window: &mut Window,
 2240        cx: &mut Context<Self>,
 2241        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2242    ) -> R {
 2243        self.change_selections_inner(autoscroll, true, window, cx, change)
 2244    }
 2245
 2246    fn change_selections_inner<R>(
 2247        &mut self,
 2248        autoscroll: Option<Autoscroll>,
 2249        request_completions: bool,
 2250        window: &mut Window,
 2251        cx: &mut Context<Self>,
 2252        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2253    ) -> R {
 2254        let old_cursor_position = self.selections.newest_anchor().head();
 2255        self.push_to_selection_history();
 2256
 2257        let (changed, result) = self.selections.change_with(cx, change);
 2258
 2259        if changed {
 2260            if let Some(autoscroll) = autoscroll {
 2261                self.request_autoscroll(autoscroll, cx);
 2262            }
 2263            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2264
 2265            if self.should_open_signature_help_automatically(
 2266                &old_cursor_position,
 2267                self.signature_help_state.backspace_pressed(),
 2268                cx,
 2269            ) {
 2270                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2271            }
 2272            self.signature_help_state.set_backspace_pressed(false);
 2273        }
 2274
 2275        result
 2276    }
 2277
 2278    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2279    where
 2280        I: IntoIterator<Item = (Range<S>, T)>,
 2281        S: ToOffset,
 2282        T: Into<Arc<str>>,
 2283    {
 2284        if self.read_only(cx) {
 2285            return;
 2286        }
 2287
 2288        self.buffer
 2289            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2290    }
 2291
 2292    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2293    where
 2294        I: IntoIterator<Item = (Range<S>, T)>,
 2295        S: ToOffset,
 2296        T: Into<Arc<str>>,
 2297    {
 2298        if self.read_only(cx) {
 2299            return;
 2300        }
 2301
 2302        self.buffer.update(cx, |buffer, cx| {
 2303            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2304        });
 2305    }
 2306
 2307    pub fn edit_with_block_indent<I, S, T>(
 2308        &mut self,
 2309        edits: I,
 2310        original_indent_columns: Vec<u32>,
 2311        cx: &mut Context<Self>,
 2312    ) where
 2313        I: IntoIterator<Item = (Range<S>, T)>,
 2314        S: ToOffset,
 2315        T: Into<Arc<str>>,
 2316    {
 2317        if self.read_only(cx) {
 2318            return;
 2319        }
 2320
 2321        self.buffer.update(cx, |buffer, cx| {
 2322            buffer.edit(
 2323                edits,
 2324                Some(AutoindentMode::Block {
 2325                    original_indent_columns,
 2326                }),
 2327                cx,
 2328            )
 2329        });
 2330    }
 2331
 2332    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2333        self.hide_context_menu(window, cx);
 2334
 2335        match phase {
 2336            SelectPhase::Begin {
 2337                position,
 2338                add,
 2339                click_count,
 2340            } => self.begin_selection(position, add, click_count, window, cx),
 2341            SelectPhase::BeginColumnar {
 2342                position,
 2343                goal_column,
 2344                reset,
 2345            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2346            SelectPhase::Extend {
 2347                position,
 2348                click_count,
 2349            } => self.extend_selection(position, click_count, window, cx),
 2350            SelectPhase::Update {
 2351                position,
 2352                goal_column,
 2353                scroll_delta,
 2354            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2355            SelectPhase::End => self.end_selection(window, cx),
 2356        }
 2357    }
 2358
 2359    fn extend_selection(
 2360        &mut self,
 2361        position: DisplayPoint,
 2362        click_count: usize,
 2363        window: &mut Window,
 2364        cx: &mut Context<Self>,
 2365    ) {
 2366        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2367        let tail = self.selections.newest::<usize>(cx).tail();
 2368        self.begin_selection(position, false, click_count, window, cx);
 2369
 2370        let position = position.to_offset(&display_map, Bias::Left);
 2371        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2372
 2373        let mut pending_selection = self
 2374            .selections
 2375            .pending_anchor()
 2376            .expect("extend_selection not called with pending selection");
 2377        if position >= tail {
 2378            pending_selection.start = tail_anchor;
 2379        } else {
 2380            pending_selection.end = tail_anchor;
 2381            pending_selection.reversed = true;
 2382        }
 2383
 2384        let mut pending_mode = self.selections.pending_mode().unwrap();
 2385        match &mut pending_mode {
 2386            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2387            _ => {}
 2388        }
 2389
 2390        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2391            s.set_pending(pending_selection, pending_mode)
 2392        });
 2393    }
 2394
 2395    fn begin_selection(
 2396        &mut self,
 2397        position: DisplayPoint,
 2398        add: bool,
 2399        click_count: usize,
 2400        window: &mut Window,
 2401        cx: &mut Context<Self>,
 2402    ) {
 2403        if !self.focus_handle.is_focused(window) {
 2404            self.last_focused_descendant = None;
 2405            window.focus(&self.focus_handle);
 2406        }
 2407
 2408        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2409        let buffer = &display_map.buffer_snapshot;
 2410        let newest_selection = self.selections.newest_anchor().clone();
 2411        let position = display_map.clip_point(position, Bias::Left);
 2412
 2413        let start;
 2414        let end;
 2415        let mode;
 2416        let mut auto_scroll;
 2417        match click_count {
 2418            1 => {
 2419                start = buffer.anchor_before(position.to_point(&display_map));
 2420                end = start;
 2421                mode = SelectMode::Character;
 2422                auto_scroll = true;
 2423            }
 2424            2 => {
 2425                let range = movement::surrounding_word(&display_map, position);
 2426                start = buffer.anchor_before(range.start.to_point(&display_map));
 2427                end = buffer.anchor_before(range.end.to_point(&display_map));
 2428                mode = SelectMode::Word(start..end);
 2429                auto_scroll = true;
 2430            }
 2431            3 => {
 2432                let position = display_map
 2433                    .clip_point(position, Bias::Left)
 2434                    .to_point(&display_map);
 2435                let line_start = display_map.prev_line_boundary(position).0;
 2436                let next_line_start = buffer.clip_point(
 2437                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2438                    Bias::Left,
 2439                );
 2440                start = buffer.anchor_before(line_start);
 2441                end = buffer.anchor_before(next_line_start);
 2442                mode = SelectMode::Line(start..end);
 2443                auto_scroll = true;
 2444            }
 2445            _ => {
 2446                start = buffer.anchor_before(0);
 2447                end = buffer.anchor_before(buffer.len());
 2448                mode = SelectMode::All;
 2449                auto_scroll = false;
 2450            }
 2451        }
 2452        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2453
 2454        let point_to_delete: Option<usize> = {
 2455            let selected_points: Vec<Selection<Point>> =
 2456                self.selections.disjoint_in_range(start..end, cx);
 2457
 2458            if !add || click_count > 1 {
 2459                None
 2460            } else if !selected_points.is_empty() {
 2461                Some(selected_points[0].id)
 2462            } else {
 2463                let clicked_point_already_selected =
 2464                    self.selections.disjoint.iter().find(|selection| {
 2465                        selection.start.to_point(buffer) == start.to_point(buffer)
 2466                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2467                    });
 2468
 2469                clicked_point_already_selected.map(|selection| selection.id)
 2470            }
 2471        };
 2472
 2473        let selections_count = self.selections.count();
 2474
 2475        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2476            if let Some(point_to_delete) = point_to_delete {
 2477                s.delete(point_to_delete);
 2478
 2479                if selections_count == 1 {
 2480                    s.set_pending_anchor_range(start..end, mode);
 2481                }
 2482            } else {
 2483                if !add {
 2484                    s.clear_disjoint();
 2485                } else if click_count > 1 {
 2486                    s.delete(newest_selection.id)
 2487                }
 2488
 2489                s.set_pending_anchor_range(start..end, mode);
 2490            }
 2491        });
 2492    }
 2493
 2494    fn begin_columnar_selection(
 2495        &mut self,
 2496        position: DisplayPoint,
 2497        goal_column: u32,
 2498        reset: bool,
 2499        window: &mut Window,
 2500        cx: &mut Context<Self>,
 2501    ) {
 2502        if !self.focus_handle.is_focused(window) {
 2503            self.last_focused_descendant = None;
 2504            window.focus(&self.focus_handle);
 2505        }
 2506
 2507        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2508
 2509        if reset {
 2510            let pointer_position = display_map
 2511                .buffer_snapshot
 2512                .anchor_before(position.to_point(&display_map));
 2513
 2514            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2515                s.clear_disjoint();
 2516                s.set_pending_anchor_range(
 2517                    pointer_position..pointer_position,
 2518                    SelectMode::Character,
 2519                );
 2520            });
 2521        }
 2522
 2523        let tail = self.selections.newest::<Point>(cx).tail();
 2524        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2525
 2526        if !reset {
 2527            self.select_columns(
 2528                tail.to_display_point(&display_map),
 2529                position,
 2530                goal_column,
 2531                &display_map,
 2532                window,
 2533                cx,
 2534            );
 2535        }
 2536    }
 2537
 2538    fn update_selection(
 2539        &mut self,
 2540        position: DisplayPoint,
 2541        goal_column: u32,
 2542        scroll_delta: gpui::Point<f32>,
 2543        window: &mut Window,
 2544        cx: &mut Context<Self>,
 2545    ) {
 2546        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2547
 2548        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2549            let tail = tail.to_display_point(&display_map);
 2550            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2551        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2552            let buffer = self.buffer.read(cx).snapshot(cx);
 2553            let head;
 2554            let tail;
 2555            let mode = self.selections.pending_mode().unwrap();
 2556            match &mode {
 2557                SelectMode::Character => {
 2558                    head = position.to_point(&display_map);
 2559                    tail = pending.tail().to_point(&buffer);
 2560                }
 2561                SelectMode::Word(original_range) => {
 2562                    let original_display_range = original_range.start.to_display_point(&display_map)
 2563                        ..original_range.end.to_display_point(&display_map);
 2564                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2565                        ..original_display_range.end.to_point(&display_map);
 2566                    if movement::is_inside_word(&display_map, position)
 2567                        || original_display_range.contains(&position)
 2568                    {
 2569                        let word_range = movement::surrounding_word(&display_map, position);
 2570                        if word_range.start < original_display_range.start {
 2571                            head = word_range.start.to_point(&display_map);
 2572                        } else {
 2573                            head = word_range.end.to_point(&display_map);
 2574                        }
 2575                    } else {
 2576                        head = position.to_point(&display_map);
 2577                    }
 2578
 2579                    if head <= original_buffer_range.start {
 2580                        tail = original_buffer_range.end;
 2581                    } else {
 2582                        tail = original_buffer_range.start;
 2583                    }
 2584                }
 2585                SelectMode::Line(original_range) => {
 2586                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2587
 2588                    let position = display_map
 2589                        .clip_point(position, Bias::Left)
 2590                        .to_point(&display_map);
 2591                    let line_start = display_map.prev_line_boundary(position).0;
 2592                    let next_line_start = buffer.clip_point(
 2593                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2594                        Bias::Left,
 2595                    );
 2596
 2597                    if line_start < original_range.start {
 2598                        head = line_start
 2599                    } else {
 2600                        head = next_line_start
 2601                    }
 2602
 2603                    if head <= original_range.start {
 2604                        tail = original_range.end;
 2605                    } else {
 2606                        tail = original_range.start;
 2607                    }
 2608                }
 2609                SelectMode::All => {
 2610                    return;
 2611                }
 2612            };
 2613
 2614            if head < tail {
 2615                pending.start = buffer.anchor_before(head);
 2616                pending.end = buffer.anchor_before(tail);
 2617                pending.reversed = true;
 2618            } else {
 2619                pending.start = buffer.anchor_before(tail);
 2620                pending.end = buffer.anchor_before(head);
 2621                pending.reversed = false;
 2622            }
 2623
 2624            self.change_selections(None, window, cx, |s| {
 2625                s.set_pending(pending, mode);
 2626            });
 2627        } else {
 2628            log::error!("update_selection dispatched with no pending selection");
 2629            return;
 2630        }
 2631
 2632        self.apply_scroll_delta(scroll_delta, window, cx);
 2633        cx.notify();
 2634    }
 2635
 2636    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2637        self.columnar_selection_tail.take();
 2638        if self.selections.pending_anchor().is_some() {
 2639            let selections = self.selections.all::<usize>(cx);
 2640            self.change_selections(None, window, cx, |s| {
 2641                s.select(selections);
 2642                s.clear_pending();
 2643            });
 2644        }
 2645    }
 2646
 2647    fn select_columns(
 2648        &mut self,
 2649        tail: DisplayPoint,
 2650        head: DisplayPoint,
 2651        goal_column: u32,
 2652        display_map: &DisplaySnapshot,
 2653        window: &mut Window,
 2654        cx: &mut Context<Self>,
 2655    ) {
 2656        let start_row = cmp::min(tail.row(), head.row());
 2657        let end_row = cmp::max(tail.row(), head.row());
 2658        let start_column = cmp::min(tail.column(), goal_column);
 2659        let end_column = cmp::max(tail.column(), goal_column);
 2660        let reversed = start_column < tail.column();
 2661
 2662        let selection_ranges = (start_row.0..=end_row.0)
 2663            .map(DisplayRow)
 2664            .filter_map(|row| {
 2665                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2666                    let start = display_map
 2667                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2668                        .to_point(display_map);
 2669                    let end = display_map
 2670                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2671                        .to_point(display_map);
 2672                    if reversed {
 2673                        Some(end..start)
 2674                    } else {
 2675                        Some(start..end)
 2676                    }
 2677                } else {
 2678                    None
 2679                }
 2680            })
 2681            .collect::<Vec<_>>();
 2682
 2683        self.change_selections(None, window, cx, |s| {
 2684            s.select_ranges(selection_ranges);
 2685        });
 2686        cx.notify();
 2687    }
 2688
 2689    pub fn has_pending_nonempty_selection(&self) -> bool {
 2690        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2691            Some(Selection { start, end, .. }) => start != end,
 2692            None => false,
 2693        };
 2694
 2695        pending_nonempty_selection
 2696            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2697    }
 2698
 2699    pub fn has_pending_selection(&self) -> bool {
 2700        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2701    }
 2702
 2703    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2704        self.selection_mark_mode = false;
 2705
 2706        if self.clear_expanded_diff_hunks(cx) {
 2707            cx.notify();
 2708            return;
 2709        }
 2710        if self.dismiss_menus_and_popups(true, window, cx) {
 2711            return;
 2712        }
 2713
 2714        if self.mode == EditorMode::Full
 2715            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2716        {
 2717            return;
 2718        }
 2719
 2720        cx.propagate();
 2721    }
 2722
 2723    pub fn dismiss_menus_and_popups(
 2724        &mut self,
 2725        is_user_requested: bool,
 2726        window: &mut Window,
 2727        cx: &mut Context<Self>,
 2728    ) -> bool {
 2729        if self.take_rename(false, window, cx).is_some() {
 2730            return true;
 2731        }
 2732
 2733        if hide_hover(self, cx) {
 2734            return true;
 2735        }
 2736
 2737        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2738            return true;
 2739        }
 2740
 2741        if self.hide_context_menu(window, cx).is_some() {
 2742            return true;
 2743        }
 2744
 2745        if self.mouse_context_menu.take().is_some() {
 2746            return true;
 2747        }
 2748
 2749        if is_user_requested && self.discard_inline_completion(true, cx) {
 2750            return true;
 2751        }
 2752
 2753        if self.snippet_stack.pop().is_some() {
 2754            return true;
 2755        }
 2756
 2757        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2758            self.dismiss_diagnostics(cx);
 2759            return true;
 2760        }
 2761
 2762        false
 2763    }
 2764
 2765    fn linked_editing_ranges_for(
 2766        &self,
 2767        selection: Range<text::Anchor>,
 2768        cx: &App,
 2769    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2770        if self.linked_edit_ranges.is_empty() {
 2771            return None;
 2772        }
 2773        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2774            selection.end.buffer_id.and_then(|end_buffer_id| {
 2775                if selection.start.buffer_id != Some(end_buffer_id) {
 2776                    return None;
 2777                }
 2778                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2779                let snapshot = buffer.read(cx).snapshot();
 2780                self.linked_edit_ranges
 2781                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2782                    .map(|ranges| (ranges, snapshot, buffer))
 2783            })?;
 2784        use text::ToOffset as TO;
 2785        // find offset from the start of current range to current cursor position
 2786        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2787
 2788        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2789        let start_difference = start_offset - start_byte_offset;
 2790        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2791        let end_difference = end_offset - start_byte_offset;
 2792        // Current range has associated linked ranges.
 2793        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2794        for range in linked_ranges.iter() {
 2795            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2796            let end_offset = start_offset + end_difference;
 2797            let start_offset = start_offset + start_difference;
 2798            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2799                continue;
 2800            }
 2801            if self.selections.disjoint_anchor_ranges().any(|s| {
 2802                if s.start.buffer_id != selection.start.buffer_id
 2803                    || s.end.buffer_id != selection.end.buffer_id
 2804                {
 2805                    return false;
 2806                }
 2807                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2808                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2809            }) {
 2810                continue;
 2811            }
 2812            let start = buffer_snapshot.anchor_after(start_offset);
 2813            let end = buffer_snapshot.anchor_after(end_offset);
 2814            linked_edits
 2815                .entry(buffer.clone())
 2816                .or_default()
 2817                .push(start..end);
 2818        }
 2819        Some(linked_edits)
 2820    }
 2821
 2822    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2823        let text: Arc<str> = text.into();
 2824
 2825        if self.read_only(cx) {
 2826            return;
 2827        }
 2828
 2829        let selections = self.selections.all_adjusted(cx);
 2830        let mut bracket_inserted = false;
 2831        let mut edits = Vec::new();
 2832        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2833        let mut new_selections = Vec::with_capacity(selections.len());
 2834        let mut new_autoclose_regions = Vec::new();
 2835        let snapshot = self.buffer.read(cx).read(cx);
 2836
 2837        for (selection, autoclose_region) in
 2838            self.selections_with_autoclose_regions(selections, &snapshot)
 2839        {
 2840            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2841                // Determine if the inserted text matches the opening or closing
 2842                // bracket of any of this language's bracket pairs.
 2843                let mut bracket_pair = None;
 2844                let mut is_bracket_pair_start = false;
 2845                let mut is_bracket_pair_end = false;
 2846                if !text.is_empty() {
 2847                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2848                    //  and they are removing the character that triggered IME popup.
 2849                    for (pair, enabled) in scope.brackets() {
 2850                        if !pair.close && !pair.surround {
 2851                            continue;
 2852                        }
 2853
 2854                        if enabled && pair.start.ends_with(text.as_ref()) {
 2855                            let prefix_len = pair.start.len() - text.len();
 2856                            let preceding_text_matches_prefix = prefix_len == 0
 2857                                || (selection.start.column >= (prefix_len as u32)
 2858                                    && snapshot.contains_str_at(
 2859                                        Point::new(
 2860                                            selection.start.row,
 2861                                            selection.start.column - (prefix_len as u32),
 2862                                        ),
 2863                                        &pair.start[..prefix_len],
 2864                                    ));
 2865                            if preceding_text_matches_prefix {
 2866                                bracket_pair = Some(pair.clone());
 2867                                is_bracket_pair_start = true;
 2868                                break;
 2869                            }
 2870                        }
 2871                        if pair.end.as_str() == text.as_ref() {
 2872                            bracket_pair = Some(pair.clone());
 2873                            is_bracket_pair_end = true;
 2874                            break;
 2875                        }
 2876                    }
 2877                }
 2878
 2879                if let Some(bracket_pair) = bracket_pair {
 2880                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2881                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2882                    let auto_surround =
 2883                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2884                    if selection.is_empty() {
 2885                        if is_bracket_pair_start {
 2886                            // If the inserted text is a suffix of an opening bracket and the
 2887                            // selection is preceded by the rest of the opening bracket, then
 2888                            // insert the closing bracket.
 2889                            let following_text_allows_autoclose = snapshot
 2890                                .chars_at(selection.start)
 2891                                .next()
 2892                                .map_or(true, |c| scope.should_autoclose_before(c));
 2893
 2894                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2895                                && bracket_pair.start.len() == 1
 2896                            {
 2897                                let target = bracket_pair.start.chars().next().unwrap();
 2898                                let current_line_count = snapshot
 2899                                    .reversed_chars_at(selection.start)
 2900                                    .take_while(|&c| c != '\n')
 2901                                    .filter(|&c| c == target)
 2902                                    .count();
 2903                                current_line_count % 2 == 1
 2904                            } else {
 2905                                false
 2906                            };
 2907
 2908                            if autoclose
 2909                                && bracket_pair.close
 2910                                && following_text_allows_autoclose
 2911                                && !is_closing_quote
 2912                            {
 2913                                let anchor = snapshot.anchor_before(selection.end);
 2914                                new_selections.push((selection.map(|_| anchor), text.len()));
 2915                                new_autoclose_regions.push((
 2916                                    anchor,
 2917                                    text.len(),
 2918                                    selection.id,
 2919                                    bracket_pair.clone(),
 2920                                ));
 2921                                edits.push((
 2922                                    selection.range(),
 2923                                    format!("{}{}", text, bracket_pair.end).into(),
 2924                                ));
 2925                                bracket_inserted = true;
 2926                                continue;
 2927                            }
 2928                        }
 2929
 2930                        if let Some(region) = autoclose_region {
 2931                            // If the selection is followed by an auto-inserted closing bracket,
 2932                            // then don't insert that closing bracket again; just move the selection
 2933                            // past the closing bracket.
 2934                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2935                                && text.as_ref() == region.pair.end.as_str();
 2936                            if should_skip {
 2937                                let anchor = snapshot.anchor_after(selection.end);
 2938                                new_selections
 2939                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2940                                continue;
 2941                            }
 2942                        }
 2943
 2944                        let always_treat_brackets_as_autoclosed = snapshot
 2945                            .settings_at(selection.start, cx)
 2946                            .always_treat_brackets_as_autoclosed;
 2947                        if always_treat_brackets_as_autoclosed
 2948                            && is_bracket_pair_end
 2949                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2950                        {
 2951                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2952                            // and the inserted text is a closing bracket and the selection is followed
 2953                            // by the closing bracket then move the selection past the closing bracket.
 2954                            let anchor = snapshot.anchor_after(selection.end);
 2955                            new_selections.push((selection.map(|_| anchor), text.len()));
 2956                            continue;
 2957                        }
 2958                    }
 2959                    // If an opening bracket is 1 character long and is typed while
 2960                    // text is selected, then surround that text with the bracket pair.
 2961                    else if auto_surround
 2962                        && bracket_pair.surround
 2963                        && is_bracket_pair_start
 2964                        && bracket_pair.start.chars().count() == 1
 2965                    {
 2966                        edits.push((selection.start..selection.start, text.clone()));
 2967                        edits.push((
 2968                            selection.end..selection.end,
 2969                            bracket_pair.end.as_str().into(),
 2970                        ));
 2971                        bracket_inserted = true;
 2972                        new_selections.push((
 2973                            Selection {
 2974                                id: selection.id,
 2975                                start: snapshot.anchor_after(selection.start),
 2976                                end: snapshot.anchor_before(selection.end),
 2977                                reversed: selection.reversed,
 2978                                goal: selection.goal,
 2979                            },
 2980                            0,
 2981                        ));
 2982                        continue;
 2983                    }
 2984                }
 2985            }
 2986
 2987            if self.auto_replace_emoji_shortcode
 2988                && selection.is_empty()
 2989                && text.as_ref().ends_with(':')
 2990            {
 2991                if let Some(possible_emoji_short_code) =
 2992                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2993                {
 2994                    if !possible_emoji_short_code.is_empty() {
 2995                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2996                            let emoji_shortcode_start = Point::new(
 2997                                selection.start.row,
 2998                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2999                            );
 3000
 3001                            // Remove shortcode from buffer
 3002                            edits.push((
 3003                                emoji_shortcode_start..selection.start,
 3004                                "".to_string().into(),
 3005                            ));
 3006                            new_selections.push((
 3007                                Selection {
 3008                                    id: selection.id,
 3009                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3010                                    end: snapshot.anchor_before(selection.start),
 3011                                    reversed: selection.reversed,
 3012                                    goal: selection.goal,
 3013                                },
 3014                                0,
 3015                            ));
 3016
 3017                            // Insert emoji
 3018                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3019                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3020                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3021
 3022                            continue;
 3023                        }
 3024                    }
 3025                }
 3026            }
 3027
 3028            // If not handling any auto-close operation, then just replace the selected
 3029            // text with the given input and move the selection to the end of the
 3030            // newly inserted text.
 3031            let anchor = snapshot.anchor_after(selection.end);
 3032            if !self.linked_edit_ranges.is_empty() {
 3033                let start_anchor = snapshot.anchor_before(selection.start);
 3034
 3035                let is_word_char = text.chars().next().map_or(true, |char| {
 3036                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3037                    classifier.is_word(char)
 3038                });
 3039
 3040                if is_word_char {
 3041                    if let Some(ranges) = self
 3042                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3043                    {
 3044                        for (buffer, edits) in ranges {
 3045                            linked_edits
 3046                                .entry(buffer.clone())
 3047                                .or_default()
 3048                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3049                        }
 3050                    }
 3051                }
 3052            }
 3053
 3054            new_selections.push((selection.map(|_| anchor), 0));
 3055            edits.push((selection.start..selection.end, text.clone()));
 3056        }
 3057
 3058        drop(snapshot);
 3059
 3060        self.transact(window, cx, |this, window, cx| {
 3061            this.buffer.update(cx, |buffer, cx| {
 3062                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3063            });
 3064            for (buffer, edits) in linked_edits {
 3065                buffer.update(cx, |buffer, cx| {
 3066                    let snapshot = buffer.snapshot();
 3067                    let edits = edits
 3068                        .into_iter()
 3069                        .map(|(range, text)| {
 3070                            use text::ToPoint as TP;
 3071                            let end_point = TP::to_point(&range.end, &snapshot);
 3072                            let start_point = TP::to_point(&range.start, &snapshot);
 3073                            (start_point..end_point, text)
 3074                        })
 3075                        .sorted_by_key(|(range, _)| range.start)
 3076                        .collect::<Vec<_>>();
 3077                    buffer.edit(edits, None, cx);
 3078                })
 3079            }
 3080            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3081            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3082            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3083            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3084                .zip(new_selection_deltas)
 3085                .map(|(selection, delta)| Selection {
 3086                    id: selection.id,
 3087                    start: selection.start + delta,
 3088                    end: selection.end + delta,
 3089                    reversed: selection.reversed,
 3090                    goal: SelectionGoal::None,
 3091                })
 3092                .collect::<Vec<_>>();
 3093
 3094            let mut i = 0;
 3095            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3096                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3097                let start = map.buffer_snapshot.anchor_before(position);
 3098                let end = map.buffer_snapshot.anchor_after(position);
 3099                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3100                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3101                        Ordering::Less => i += 1,
 3102                        Ordering::Greater => break,
 3103                        Ordering::Equal => {
 3104                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3105                                Ordering::Less => i += 1,
 3106                                Ordering::Equal => break,
 3107                                Ordering::Greater => break,
 3108                            }
 3109                        }
 3110                    }
 3111                }
 3112                this.autoclose_regions.insert(
 3113                    i,
 3114                    AutocloseRegion {
 3115                        selection_id,
 3116                        range: start..end,
 3117                        pair,
 3118                    },
 3119                );
 3120            }
 3121
 3122            let had_active_inline_completion = this.has_active_inline_completion();
 3123            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3124                s.select(new_selections)
 3125            });
 3126
 3127            if !bracket_inserted {
 3128                if let Some(on_type_format_task) =
 3129                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3130                {
 3131                    on_type_format_task.detach_and_log_err(cx);
 3132                }
 3133            }
 3134
 3135            let editor_settings = EditorSettings::get_global(cx);
 3136            if bracket_inserted
 3137                && (editor_settings.auto_signature_help
 3138                    || editor_settings.show_signature_help_after_edits)
 3139            {
 3140                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3141            }
 3142
 3143            let trigger_in_words =
 3144                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3145            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3146            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3147            this.refresh_inline_completion(true, false, window, cx);
 3148        });
 3149    }
 3150
 3151    fn find_possible_emoji_shortcode_at_position(
 3152        snapshot: &MultiBufferSnapshot,
 3153        position: Point,
 3154    ) -> Option<String> {
 3155        let mut chars = Vec::new();
 3156        let mut found_colon = false;
 3157        for char in snapshot.reversed_chars_at(position).take(100) {
 3158            // Found a possible emoji shortcode in the middle of the buffer
 3159            if found_colon {
 3160                if char.is_whitespace() {
 3161                    chars.reverse();
 3162                    return Some(chars.iter().collect());
 3163                }
 3164                // If the previous character is not a whitespace, we are in the middle of a word
 3165                // and we only want to complete the shortcode if the word is made up of other emojis
 3166                let mut containing_word = String::new();
 3167                for ch in snapshot
 3168                    .reversed_chars_at(position)
 3169                    .skip(chars.len() + 1)
 3170                    .take(100)
 3171                {
 3172                    if ch.is_whitespace() {
 3173                        break;
 3174                    }
 3175                    containing_word.push(ch);
 3176                }
 3177                let containing_word = containing_word.chars().rev().collect::<String>();
 3178                if util::word_consists_of_emojis(containing_word.as_str()) {
 3179                    chars.reverse();
 3180                    return Some(chars.iter().collect());
 3181                }
 3182            }
 3183
 3184            if char.is_whitespace() || !char.is_ascii() {
 3185                return None;
 3186            }
 3187            if char == ':' {
 3188                found_colon = true;
 3189            } else {
 3190                chars.push(char);
 3191            }
 3192        }
 3193        // Found a possible emoji shortcode at the beginning of the buffer
 3194        chars.reverse();
 3195        Some(chars.iter().collect())
 3196    }
 3197
 3198    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3199        self.transact(window, cx, |this, window, cx| {
 3200            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3201                let selections = this.selections.all::<usize>(cx);
 3202                let multi_buffer = this.buffer.read(cx);
 3203                let buffer = multi_buffer.snapshot(cx);
 3204                selections
 3205                    .iter()
 3206                    .map(|selection| {
 3207                        let start_point = selection.start.to_point(&buffer);
 3208                        let mut indent =
 3209                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3210                        indent.len = cmp::min(indent.len, start_point.column);
 3211                        let start = selection.start;
 3212                        let end = selection.end;
 3213                        let selection_is_empty = start == end;
 3214                        let language_scope = buffer.language_scope_at(start);
 3215                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3216                            &language_scope
 3217                        {
 3218                            let leading_whitespace_len = buffer
 3219                                .reversed_chars_at(start)
 3220                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3221                                .map(|c| c.len_utf8())
 3222                                .sum::<usize>();
 3223
 3224                            let trailing_whitespace_len = buffer
 3225                                .chars_at(end)
 3226                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3227                                .map(|c| c.len_utf8())
 3228                                .sum::<usize>();
 3229
 3230                            let insert_extra_newline =
 3231                                language.brackets().any(|(pair, enabled)| {
 3232                                    let pair_start = pair.start.trim_end();
 3233                                    let pair_end = pair.end.trim_start();
 3234
 3235                                    enabled
 3236                                        && pair.newline
 3237                                        && buffer.contains_str_at(
 3238                                            end + trailing_whitespace_len,
 3239                                            pair_end,
 3240                                        )
 3241                                        && buffer.contains_str_at(
 3242                                            (start - leading_whitespace_len)
 3243                                                .saturating_sub(pair_start.len()),
 3244                                            pair_start,
 3245                                        )
 3246                                });
 3247
 3248                            // Comment extension on newline is allowed only for cursor selections
 3249                            let comment_delimiter = maybe!({
 3250                                if !selection_is_empty {
 3251                                    return None;
 3252                                }
 3253
 3254                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3255                                    return None;
 3256                                }
 3257
 3258                                let delimiters = language.line_comment_prefixes();
 3259                                let max_len_of_delimiter =
 3260                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3261                                let (snapshot, range) =
 3262                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3263
 3264                                let mut index_of_first_non_whitespace = 0;
 3265                                let comment_candidate = snapshot
 3266                                    .chars_for_range(range)
 3267                                    .skip_while(|c| {
 3268                                        let should_skip = c.is_whitespace();
 3269                                        if should_skip {
 3270                                            index_of_first_non_whitespace += 1;
 3271                                        }
 3272                                        should_skip
 3273                                    })
 3274                                    .take(max_len_of_delimiter)
 3275                                    .collect::<String>();
 3276                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3277                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3278                                })?;
 3279                                let cursor_is_placed_after_comment_marker =
 3280                                    index_of_first_non_whitespace + comment_prefix.len()
 3281                                        <= start_point.column as usize;
 3282                                if cursor_is_placed_after_comment_marker {
 3283                                    Some(comment_prefix.clone())
 3284                                } else {
 3285                                    None
 3286                                }
 3287                            });
 3288                            (comment_delimiter, insert_extra_newline)
 3289                        } else {
 3290                            (None, false)
 3291                        };
 3292
 3293                        let capacity_for_delimiter = comment_delimiter
 3294                            .as_deref()
 3295                            .map(str::len)
 3296                            .unwrap_or_default();
 3297                        let mut new_text =
 3298                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3299                        new_text.push('\n');
 3300                        new_text.extend(indent.chars());
 3301                        if let Some(delimiter) = &comment_delimiter {
 3302                            new_text.push_str(delimiter);
 3303                        }
 3304                        if insert_extra_newline {
 3305                            new_text = new_text.repeat(2);
 3306                        }
 3307
 3308                        let anchor = buffer.anchor_after(end);
 3309                        let new_selection = selection.map(|_| anchor);
 3310                        (
 3311                            (start..end, new_text),
 3312                            (insert_extra_newline, new_selection),
 3313                        )
 3314                    })
 3315                    .unzip()
 3316            };
 3317
 3318            this.edit_with_autoindent(edits, cx);
 3319            let buffer = this.buffer.read(cx).snapshot(cx);
 3320            let new_selections = selection_fixup_info
 3321                .into_iter()
 3322                .map(|(extra_newline_inserted, new_selection)| {
 3323                    let mut cursor = new_selection.end.to_point(&buffer);
 3324                    if extra_newline_inserted {
 3325                        cursor.row -= 1;
 3326                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3327                    }
 3328                    new_selection.map(|_| cursor)
 3329                })
 3330                .collect();
 3331
 3332            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3333                s.select(new_selections)
 3334            });
 3335            this.refresh_inline_completion(true, false, window, cx);
 3336        });
 3337    }
 3338
 3339    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3340        let buffer = self.buffer.read(cx);
 3341        let snapshot = buffer.snapshot(cx);
 3342
 3343        let mut edits = Vec::new();
 3344        let mut rows = Vec::new();
 3345
 3346        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3347            let cursor = selection.head();
 3348            let row = cursor.row;
 3349
 3350            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3351
 3352            let newline = "\n".to_string();
 3353            edits.push((start_of_line..start_of_line, newline));
 3354
 3355            rows.push(row + rows_inserted as u32);
 3356        }
 3357
 3358        self.transact(window, cx, |editor, window, cx| {
 3359            editor.edit(edits, cx);
 3360
 3361            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3362                let mut index = 0;
 3363                s.move_cursors_with(|map, _, _| {
 3364                    let row = rows[index];
 3365                    index += 1;
 3366
 3367                    let point = Point::new(row, 0);
 3368                    let boundary = map.next_line_boundary(point).1;
 3369                    let clipped = map.clip_point(boundary, Bias::Left);
 3370
 3371                    (clipped, SelectionGoal::None)
 3372                });
 3373            });
 3374
 3375            let mut indent_edits = Vec::new();
 3376            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3377            for row in rows {
 3378                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3379                for (row, indent) in indents {
 3380                    if indent.len == 0 {
 3381                        continue;
 3382                    }
 3383
 3384                    let text = match indent.kind {
 3385                        IndentKind::Space => " ".repeat(indent.len as usize),
 3386                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3387                    };
 3388                    let point = Point::new(row.0, 0);
 3389                    indent_edits.push((point..point, text));
 3390                }
 3391            }
 3392            editor.edit(indent_edits, cx);
 3393        });
 3394    }
 3395
 3396    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3397        let buffer = self.buffer.read(cx);
 3398        let snapshot = buffer.snapshot(cx);
 3399
 3400        let mut edits = Vec::new();
 3401        let mut rows = Vec::new();
 3402        let mut rows_inserted = 0;
 3403
 3404        for selection in self.selections.all_adjusted(cx) {
 3405            let cursor = selection.head();
 3406            let row = cursor.row;
 3407
 3408            let point = Point::new(row + 1, 0);
 3409            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3410
 3411            let newline = "\n".to_string();
 3412            edits.push((start_of_line..start_of_line, newline));
 3413
 3414            rows_inserted += 1;
 3415            rows.push(row + rows_inserted);
 3416        }
 3417
 3418        self.transact(window, cx, |editor, window, cx| {
 3419            editor.edit(edits, cx);
 3420
 3421            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3422                let mut index = 0;
 3423                s.move_cursors_with(|map, _, _| {
 3424                    let row = rows[index];
 3425                    index += 1;
 3426
 3427                    let point = Point::new(row, 0);
 3428                    let boundary = map.next_line_boundary(point).1;
 3429                    let clipped = map.clip_point(boundary, Bias::Left);
 3430
 3431                    (clipped, SelectionGoal::None)
 3432                });
 3433            });
 3434
 3435            let mut indent_edits = Vec::new();
 3436            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3437            for row in rows {
 3438                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3439                for (row, indent) in indents {
 3440                    if indent.len == 0 {
 3441                        continue;
 3442                    }
 3443
 3444                    let text = match indent.kind {
 3445                        IndentKind::Space => " ".repeat(indent.len as usize),
 3446                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3447                    };
 3448                    let point = Point::new(row.0, 0);
 3449                    indent_edits.push((point..point, text));
 3450                }
 3451            }
 3452            editor.edit(indent_edits, cx);
 3453        });
 3454    }
 3455
 3456    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3457        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3458            original_indent_columns: Vec::new(),
 3459        });
 3460        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3461    }
 3462
 3463    fn insert_with_autoindent_mode(
 3464        &mut self,
 3465        text: &str,
 3466        autoindent_mode: Option<AutoindentMode>,
 3467        window: &mut Window,
 3468        cx: &mut Context<Self>,
 3469    ) {
 3470        if self.read_only(cx) {
 3471            return;
 3472        }
 3473
 3474        let text: Arc<str> = text.into();
 3475        self.transact(window, cx, |this, window, cx| {
 3476            let old_selections = this.selections.all_adjusted(cx);
 3477            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3478                let anchors = {
 3479                    let snapshot = buffer.read(cx);
 3480                    old_selections
 3481                        .iter()
 3482                        .map(|s| {
 3483                            let anchor = snapshot.anchor_after(s.head());
 3484                            s.map(|_| anchor)
 3485                        })
 3486                        .collect::<Vec<_>>()
 3487                };
 3488                buffer.edit(
 3489                    old_selections
 3490                        .iter()
 3491                        .map(|s| (s.start..s.end, text.clone())),
 3492                    autoindent_mode,
 3493                    cx,
 3494                );
 3495                anchors
 3496            });
 3497
 3498            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3499                s.select_anchors(selection_anchors);
 3500            });
 3501
 3502            cx.notify();
 3503        });
 3504    }
 3505
 3506    fn trigger_completion_on_input(
 3507        &mut self,
 3508        text: &str,
 3509        trigger_in_words: bool,
 3510        window: &mut Window,
 3511        cx: &mut Context<Self>,
 3512    ) {
 3513        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3514            self.show_completions(
 3515                &ShowCompletions {
 3516                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3517                },
 3518                window,
 3519                cx,
 3520            );
 3521        } else {
 3522            self.hide_context_menu(window, cx);
 3523        }
 3524    }
 3525
 3526    fn is_completion_trigger(
 3527        &self,
 3528        text: &str,
 3529        trigger_in_words: bool,
 3530        cx: &mut Context<Self>,
 3531    ) -> bool {
 3532        let position = self.selections.newest_anchor().head();
 3533        let multibuffer = self.buffer.read(cx);
 3534        let Some(buffer) = position
 3535            .buffer_id
 3536            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3537        else {
 3538            return false;
 3539        };
 3540
 3541        if let Some(completion_provider) = &self.completion_provider {
 3542            completion_provider.is_completion_trigger(
 3543                &buffer,
 3544                position.text_anchor,
 3545                text,
 3546                trigger_in_words,
 3547                cx,
 3548            )
 3549        } else {
 3550            false
 3551        }
 3552    }
 3553
 3554    /// If any empty selections is touching the start of its innermost containing autoclose
 3555    /// region, expand it to select the brackets.
 3556    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3557        let selections = self.selections.all::<usize>(cx);
 3558        let buffer = self.buffer.read(cx).read(cx);
 3559        let new_selections = self
 3560            .selections_with_autoclose_regions(selections, &buffer)
 3561            .map(|(mut selection, region)| {
 3562                if !selection.is_empty() {
 3563                    return selection;
 3564                }
 3565
 3566                if let Some(region) = region {
 3567                    let mut range = region.range.to_offset(&buffer);
 3568                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3569                        range.start -= region.pair.start.len();
 3570                        if buffer.contains_str_at(range.start, &region.pair.start)
 3571                            && buffer.contains_str_at(range.end, &region.pair.end)
 3572                        {
 3573                            range.end += region.pair.end.len();
 3574                            selection.start = range.start;
 3575                            selection.end = range.end;
 3576
 3577                            return selection;
 3578                        }
 3579                    }
 3580                }
 3581
 3582                let always_treat_brackets_as_autoclosed = buffer
 3583                    .settings_at(selection.start, cx)
 3584                    .always_treat_brackets_as_autoclosed;
 3585
 3586                if !always_treat_brackets_as_autoclosed {
 3587                    return selection;
 3588                }
 3589
 3590                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3591                    for (pair, enabled) in scope.brackets() {
 3592                        if !enabled || !pair.close {
 3593                            continue;
 3594                        }
 3595
 3596                        if buffer.contains_str_at(selection.start, &pair.end) {
 3597                            let pair_start_len = pair.start.len();
 3598                            if buffer.contains_str_at(
 3599                                selection.start.saturating_sub(pair_start_len),
 3600                                &pair.start,
 3601                            ) {
 3602                                selection.start -= pair_start_len;
 3603                                selection.end += pair.end.len();
 3604
 3605                                return selection;
 3606                            }
 3607                        }
 3608                    }
 3609                }
 3610
 3611                selection
 3612            })
 3613            .collect();
 3614
 3615        drop(buffer);
 3616        self.change_selections(None, window, cx, |selections| {
 3617            selections.select(new_selections)
 3618        });
 3619    }
 3620
 3621    /// Iterate the given selections, and for each one, find the smallest surrounding
 3622    /// autoclose region. This uses the ordering of the selections and the autoclose
 3623    /// regions to avoid repeated comparisons.
 3624    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3625        &'a self,
 3626        selections: impl IntoIterator<Item = Selection<D>>,
 3627        buffer: &'a MultiBufferSnapshot,
 3628    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3629        let mut i = 0;
 3630        let mut regions = self.autoclose_regions.as_slice();
 3631        selections.into_iter().map(move |selection| {
 3632            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3633
 3634            let mut enclosing = None;
 3635            while let Some(pair_state) = regions.get(i) {
 3636                if pair_state.range.end.to_offset(buffer) < range.start {
 3637                    regions = &regions[i + 1..];
 3638                    i = 0;
 3639                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3640                    break;
 3641                } else {
 3642                    if pair_state.selection_id == selection.id {
 3643                        enclosing = Some(pair_state);
 3644                    }
 3645                    i += 1;
 3646                }
 3647            }
 3648
 3649            (selection, enclosing)
 3650        })
 3651    }
 3652
 3653    /// Remove any autoclose regions that no longer contain their selection.
 3654    fn invalidate_autoclose_regions(
 3655        &mut self,
 3656        mut selections: &[Selection<Anchor>],
 3657        buffer: &MultiBufferSnapshot,
 3658    ) {
 3659        self.autoclose_regions.retain(|state| {
 3660            let mut i = 0;
 3661            while let Some(selection) = selections.get(i) {
 3662                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3663                    selections = &selections[1..];
 3664                    continue;
 3665                }
 3666                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3667                    break;
 3668                }
 3669                if selection.id == state.selection_id {
 3670                    return true;
 3671                } else {
 3672                    i += 1;
 3673                }
 3674            }
 3675            false
 3676        });
 3677    }
 3678
 3679    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3680        let offset = position.to_offset(buffer);
 3681        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3682        if offset > word_range.start && kind == Some(CharKind::Word) {
 3683            Some(
 3684                buffer
 3685                    .text_for_range(word_range.start..offset)
 3686                    .collect::<String>(),
 3687            )
 3688        } else {
 3689            None
 3690        }
 3691    }
 3692
 3693    pub fn toggle_inlay_hints(
 3694        &mut self,
 3695        _: &ToggleInlayHints,
 3696        _: &mut Window,
 3697        cx: &mut Context<Self>,
 3698    ) {
 3699        self.refresh_inlay_hints(
 3700            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3701            cx,
 3702        );
 3703    }
 3704
 3705    pub fn inlay_hints_enabled(&self) -> bool {
 3706        self.inlay_hint_cache.enabled
 3707    }
 3708
 3709    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3710        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3711            return;
 3712        }
 3713
 3714        let reason_description = reason.description();
 3715        let ignore_debounce = matches!(
 3716            reason,
 3717            InlayHintRefreshReason::SettingsChange(_)
 3718                | InlayHintRefreshReason::Toggle(_)
 3719                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3720        );
 3721        let (invalidate_cache, required_languages) = match reason {
 3722            InlayHintRefreshReason::Toggle(enabled) => {
 3723                self.inlay_hint_cache.enabled = enabled;
 3724                if enabled {
 3725                    (InvalidationStrategy::RefreshRequested, None)
 3726                } else {
 3727                    self.inlay_hint_cache.clear();
 3728                    self.splice_inlays(
 3729                        &self
 3730                            .visible_inlay_hints(cx)
 3731                            .iter()
 3732                            .map(|inlay| inlay.id)
 3733                            .collect::<Vec<InlayId>>(),
 3734                        Vec::new(),
 3735                        cx,
 3736                    );
 3737                    return;
 3738                }
 3739            }
 3740            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3741                match self.inlay_hint_cache.update_settings(
 3742                    &self.buffer,
 3743                    new_settings,
 3744                    self.visible_inlay_hints(cx),
 3745                    cx,
 3746                ) {
 3747                    ControlFlow::Break(Some(InlaySplice {
 3748                        to_remove,
 3749                        to_insert,
 3750                    })) => {
 3751                        self.splice_inlays(&to_remove, to_insert, cx);
 3752                        return;
 3753                    }
 3754                    ControlFlow::Break(None) => return,
 3755                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3756                }
 3757            }
 3758            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3759                if let Some(InlaySplice {
 3760                    to_remove,
 3761                    to_insert,
 3762                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3763                {
 3764                    self.splice_inlays(&to_remove, to_insert, cx);
 3765                }
 3766                return;
 3767            }
 3768            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3769            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3770                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3771            }
 3772            InlayHintRefreshReason::RefreshRequested => {
 3773                (InvalidationStrategy::RefreshRequested, None)
 3774            }
 3775        };
 3776
 3777        if let Some(InlaySplice {
 3778            to_remove,
 3779            to_insert,
 3780        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3781            reason_description,
 3782            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3783            invalidate_cache,
 3784            ignore_debounce,
 3785            cx,
 3786        ) {
 3787            self.splice_inlays(&to_remove, to_insert, cx);
 3788        }
 3789    }
 3790
 3791    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3792        self.display_map
 3793            .read(cx)
 3794            .current_inlays()
 3795            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3796            .cloned()
 3797            .collect()
 3798    }
 3799
 3800    pub fn excerpts_for_inlay_hints_query(
 3801        &self,
 3802        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3803        cx: &mut Context<Editor>,
 3804    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3805        let Some(project) = self.project.as_ref() else {
 3806            return HashMap::default();
 3807        };
 3808        let project = project.read(cx);
 3809        let multi_buffer = self.buffer().read(cx);
 3810        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3811        let multi_buffer_visible_start = self
 3812            .scroll_manager
 3813            .anchor()
 3814            .anchor
 3815            .to_point(&multi_buffer_snapshot);
 3816        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3817            multi_buffer_visible_start
 3818                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3819            Bias::Left,
 3820        );
 3821        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3822        multi_buffer_snapshot
 3823            .range_to_buffer_ranges(multi_buffer_visible_range)
 3824            .into_iter()
 3825            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3826            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3827                let buffer_file = project::File::from_dyn(buffer.file())?;
 3828                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3829                let worktree_entry = buffer_worktree
 3830                    .read(cx)
 3831                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3832                if worktree_entry.is_ignored {
 3833                    return None;
 3834                }
 3835
 3836                let language = buffer.language()?;
 3837                if let Some(restrict_to_languages) = restrict_to_languages {
 3838                    if !restrict_to_languages.contains(language) {
 3839                        return None;
 3840                    }
 3841                }
 3842                Some((
 3843                    excerpt_id,
 3844                    (
 3845                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3846                        buffer.version().clone(),
 3847                        excerpt_visible_range,
 3848                    ),
 3849                ))
 3850            })
 3851            .collect()
 3852    }
 3853
 3854    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3855        TextLayoutDetails {
 3856            text_system: window.text_system().clone(),
 3857            editor_style: self.style.clone().unwrap(),
 3858            rem_size: window.rem_size(),
 3859            scroll_anchor: self.scroll_manager.anchor(),
 3860            visible_rows: self.visible_line_count(),
 3861            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3862        }
 3863    }
 3864
 3865    pub fn splice_inlays(
 3866        &self,
 3867        to_remove: &[InlayId],
 3868        to_insert: Vec<Inlay>,
 3869        cx: &mut Context<Self>,
 3870    ) {
 3871        self.display_map.update(cx, |display_map, cx| {
 3872            display_map.splice_inlays(to_remove, to_insert, cx)
 3873        });
 3874        cx.notify();
 3875    }
 3876
 3877    fn trigger_on_type_formatting(
 3878        &self,
 3879        input: String,
 3880        window: &mut Window,
 3881        cx: &mut Context<Self>,
 3882    ) -> Option<Task<Result<()>>> {
 3883        if input.len() != 1 {
 3884            return None;
 3885        }
 3886
 3887        let project = self.project.as_ref()?;
 3888        let position = self.selections.newest_anchor().head();
 3889        let (buffer, buffer_position) = self
 3890            .buffer
 3891            .read(cx)
 3892            .text_anchor_for_position(position, cx)?;
 3893
 3894        let settings = language_settings::language_settings(
 3895            buffer
 3896                .read(cx)
 3897                .language_at(buffer_position)
 3898                .map(|l| l.name()),
 3899            buffer.read(cx).file(),
 3900            cx,
 3901        );
 3902        if !settings.use_on_type_format {
 3903            return None;
 3904        }
 3905
 3906        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3907        // hence we do LSP request & edit on host side only — add formats to host's history.
 3908        let push_to_lsp_host_history = true;
 3909        // If this is not the host, append its history with new edits.
 3910        let push_to_client_history = project.read(cx).is_via_collab();
 3911
 3912        let on_type_formatting = project.update(cx, |project, cx| {
 3913            project.on_type_format(
 3914                buffer.clone(),
 3915                buffer_position,
 3916                input,
 3917                push_to_lsp_host_history,
 3918                cx,
 3919            )
 3920        });
 3921        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3922            if let Some(transaction) = on_type_formatting.await? {
 3923                if push_to_client_history {
 3924                    buffer
 3925                        .update(&mut cx, |buffer, _| {
 3926                            buffer.push_transaction(transaction, Instant::now());
 3927                        })
 3928                        .ok();
 3929                }
 3930                editor.update(&mut cx, |editor, cx| {
 3931                    editor.refresh_document_highlights(cx);
 3932                })?;
 3933            }
 3934            Ok(())
 3935        }))
 3936    }
 3937
 3938    pub fn show_completions(
 3939        &mut self,
 3940        options: &ShowCompletions,
 3941        window: &mut Window,
 3942        cx: &mut Context<Self>,
 3943    ) {
 3944        if self.pending_rename.is_some() {
 3945            return;
 3946        }
 3947
 3948        let Some(provider) = self.completion_provider.as_ref() else {
 3949            return;
 3950        };
 3951
 3952        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3953            return;
 3954        }
 3955
 3956        let position = self.selections.newest_anchor().head();
 3957        if position.diff_base_anchor.is_some() {
 3958            return;
 3959        }
 3960        let (buffer, buffer_position) =
 3961            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3962                output
 3963            } else {
 3964                return;
 3965            };
 3966        let show_completion_documentation = buffer
 3967            .read(cx)
 3968            .snapshot()
 3969            .settings_at(buffer_position, cx)
 3970            .show_completion_documentation;
 3971
 3972        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3973
 3974        let trigger_kind = match &options.trigger {
 3975            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3976                CompletionTriggerKind::TRIGGER_CHARACTER
 3977            }
 3978            _ => CompletionTriggerKind::INVOKED,
 3979        };
 3980        let completion_context = CompletionContext {
 3981            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3982                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3983                    Some(String::from(trigger))
 3984                } else {
 3985                    None
 3986                }
 3987            }),
 3988            trigger_kind,
 3989        };
 3990        let completions =
 3991            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3992        let sort_completions = provider.sort_completions();
 3993
 3994        let id = post_inc(&mut self.next_completion_id);
 3995        let task = cx.spawn_in(window, |editor, mut cx| {
 3996            async move {
 3997                editor.update(&mut cx, |this, _| {
 3998                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3999                })?;
 4000                let completions = completions.await.log_err();
 4001                let menu = if let Some(completions) = completions {
 4002                    let mut menu = CompletionsMenu::new(
 4003                        id,
 4004                        sort_completions,
 4005                        show_completion_documentation,
 4006                        position,
 4007                        buffer.clone(),
 4008                        completions.into(),
 4009                    );
 4010
 4011                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4012                        .await;
 4013
 4014                    menu.visible().then_some(menu)
 4015                } else {
 4016                    None
 4017                };
 4018
 4019                editor.update_in(&mut cx, |editor, window, cx| {
 4020                    match editor.context_menu.borrow().as_ref() {
 4021                        None => {}
 4022                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4023                            if prev_menu.id > id {
 4024                                return;
 4025                            }
 4026                        }
 4027                        _ => return,
 4028                    }
 4029
 4030                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4031                        let mut menu = menu.unwrap();
 4032                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4033
 4034                        *editor.context_menu.borrow_mut() =
 4035                            Some(CodeContextMenu::Completions(menu));
 4036
 4037                        if editor.show_edit_predictions_in_menu() {
 4038                            editor.update_visible_inline_completion(window, cx);
 4039                        } else {
 4040                            editor.discard_inline_completion(false, cx);
 4041                        }
 4042
 4043                        cx.notify();
 4044                    } else if editor.completion_tasks.len() <= 1 {
 4045                        // If there are no more completion tasks and the last menu was
 4046                        // empty, we should hide it.
 4047                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4048                        // If it was already hidden and we don't show inline
 4049                        // completions in the menu, we should also show the
 4050                        // inline-completion when available.
 4051                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4052                            editor.update_visible_inline_completion(window, cx);
 4053                        }
 4054                    }
 4055                })?;
 4056
 4057                Ok::<_, anyhow::Error>(())
 4058            }
 4059            .log_err()
 4060        });
 4061
 4062        self.completion_tasks.push((id, task));
 4063    }
 4064
 4065    pub fn confirm_completion(
 4066        &mut self,
 4067        action: &ConfirmCompletion,
 4068        window: &mut Window,
 4069        cx: &mut Context<Self>,
 4070    ) -> Option<Task<Result<()>>> {
 4071        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4072    }
 4073
 4074    pub fn compose_completion(
 4075        &mut self,
 4076        action: &ComposeCompletion,
 4077        window: &mut Window,
 4078        cx: &mut Context<Self>,
 4079    ) -> Option<Task<Result<()>>> {
 4080        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4081    }
 4082
 4083    fn do_completion(
 4084        &mut self,
 4085        item_ix: Option<usize>,
 4086        intent: CompletionIntent,
 4087        window: &mut Window,
 4088        cx: &mut Context<Editor>,
 4089    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4090        use language::ToOffset as _;
 4091
 4092        let completions_menu =
 4093            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4094                menu
 4095            } else {
 4096                return None;
 4097            };
 4098
 4099        let entries = completions_menu.entries.borrow();
 4100        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4101        if self.show_edit_predictions_in_menu() {
 4102            self.discard_inline_completion(true, cx);
 4103        }
 4104        let candidate_id = mat.candidate_id;
 4105        drop(entries);
 4106
 4107        let buffer_handle = completions_menu.buffer;
 4108        let completion = completions_menu
 4109            .completions
 4110            .borrow()
 4111            .get(candidate_id)?
 4112            .clone();
 4113        cx.stop_propagation();
 4114
 4115        let snippet;
 4116        let text;
 4117
 4118        if completion.is_snippet() {
 4119            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4120            text = snippet.as_ref().unwrap().text.clone();
 4121        } else {
 4122            snippet = None;
 4123            text = completion.new_text.clone();
 4124        };
 4125        let selections = self.selections.all::<usize>(cx);
 4126        let buffer = buffer_handle.read(cx);
 4127        let old_range = completion.old_range.to_offset(buffer);
 4128        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4129
 4130        let newest_selection = self.selections.newest_anchor();
 4131        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4132            return None;
 4133        }
 4134
 4135        let lookbehind = newest_selection
 4136            .start
 4137            .text_anchor
 4138            .to_offset(buffer)
 4139            .saturating_sub(old_range.start);
 4140        let lookahead = old_range
 4141            .end
 4142            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4143        let mut common_prefix_len = old_text
 4144            .bytes()
 4145            .zip(text.bytes())
 4146            .take_while(|(a, b)| a == b)
 4147            .count();
 4148
 4149        let snapshot = self.buffer.read(cx).snapshot(cx);
 4150        let mut range_to_replace: Option<Range<isize>> = None;
 4151        let mut ranges = Vec::new();
 4152        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4153        for selection in &selections {
 4154            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4155                let start = selection.start.saturating_sub(lookbehind);
 4156                let end = selection.end + lookahead;
 4157                if selection.id == newest_selection.id {
 4158                    range_to_replace = Some(
 4159                        ((start + common_prefix_len) as isize - selection.start as isize)
 4160                            ..(end as isize - selection.start as isize),
 4161                    );
 4162                }
 4163                ranges.push(start + common_prefix_len..end);
 4164            } else {
 4165                common_prefix_len = 0;
 4166                ranges.clear();
 4167                ranges.extend(selections.iter().map(|s| {
 4168                    if s.id == newest_selection.id {
 4169                        range_to_replace = Some(
 4170                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4171                                - selection.start as isize
 4172                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4173                                    - selection.start as isize,
 4174                        );
 4175                        old_range.clone()
 4176                    } else {
 4177                        s.start..s.end
 4178                    }
 4179                }));
 4180                break;
 4181            }
 4182            if !self.linked_edit_ranges.is_empty() {
 4183                let start_anchor = snapshot.anchor_before(selection.head());
 4184                let end_anchor = snapshot.anchor_after(selection.tail());
 4185                if let Some(ranges) = self
 4186                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4187                {
 4188                    for (buffer, edits) in ranges {
 4189                        linked_edits.entry(buffer.clone()).or_default().extend(
 4190                            edits
 4191                                .into_iter()
 4192                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4193                        );
 4194                    }
 4195                }
 4196            }
 4197        }
 4198        let text = &text[common_prefix_len..];
 4199
 4200        cx.emit(EditorEvent::InputHandled {
 4201            utf16_range_to_replace: range_to_replace,
 4202            text: text.into(),
 4203        });
 4204
 4205        self.transact(window, cx, |this, window, cx| {
 4206            if let Some(mut snippet) = snippet {
 4207                snippet.text = text.to_string();
 4208                for tabstop in snippet
 4209                    .tabstops
 4210                    .iter_mut()
 4211                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4212                {
 4213                    tabstop.start -= common_prefix_len as isize;
 4214                    tabstop.end -= common_prefix_len as isize;
 4215                }
 4216
 4217                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4218            } else {
 4219                this.buffer.update(cx, |buffer, cx| {
 4220                    buffer.edit(
 4221                        ranges.iter().map(|range| (range.clone(), text)),
 4222                        this.autoindent_mode.clone(),
 4223                        cx,
 4224                    );
 4225                });
 4226            }
 4227            for (buffer, edits) in linked_edits {
 4228                buffer.update(cx, |buffer, cx| {
 4229                    let snapshot = buffer.snapshot();
 4230                    let edits = edits
 4231                        .into_iter()
 4232                        .map(|(range, text)| {
 4233                            use text::ToPoint as TP;
 4234                            let end_point = TP::to_point(&range.end, &snapshot);
 4235                            let start_point = TP::to_point(&range.start, &snapshot);
 4236                            (start_point..end_point, text)
 4237                        })
 4238                        .sorted_by_key(|(range, _)| range.start)
 4239                        .collect::<Vec<_>>();
 4240                    buffer.edit(edits, None, cx);
 4241                })
 4242            }
 4243
 4244            this.refresh_inline_completion(true, false, window, cx);
 4245        });
 4246
 4247        let show_new_completions_on_confirm = completion
 4248            .confirm
 4249            .as_ref()
 4250            .map_or(false, |confirm| confirm(intent, window, cx));
 4251        if show_new_completions_on_confirm {
 4252            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4253        }
 4254
 4255        let provider = self.completion_provider.as_ref()?;
 4256        drop(completion);
 4257        let apply_edits = provider.apply_additional_edits_for_completion(
 4258            buffer_handle,
 4259            completions_menu.completions.clone(),
 4260            candidate_id,
 4261            true,
 4262            cx,
 4263        );
 4264
 4265        let editor_settings = EditorSettings::get_global(cx);
 4266        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4267            // After the code completion is finished, users often want to know what signatures are needed.
 4268            // so we should automatically call signature_help
 4269            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4270        }
 4271
 4272        Some(cx.foreground_executor().spawn(async move {
 4273            apply_edits.await?;
 4274            Ok(())
 4275        }))
 4276    }
 4277
 4278    pub fn toggle_code_actions(
 4279        &mut self,
 4280        action: &ToggleCodeActions,
 4281        window: &mut Window,
 4282        cx: &mut Context<Self>,
 4283    ) {
 4284        let mut context_menu = self.context_menu.borrow_mut();
 4285        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4286            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4287                // Toggle if we're selecting the same one
 4288                *context_menu = None;
 4289                cx.notify();
 4290                return;
 4291            } else {
 4292                // Otherwise, clear it and start a new one
 4293                *context_menu = None;
 4294                cx.notify();
 4295            }
 4296        }
 4297        drop(context_menu);
 4298        let snapshot = self.snapshot(window, cx);
 4299        let deployed_from_indicator = action.deployed_from_indicator;
 4300        let mut task = self.code_actions_task.take();
 4301        let action = action.clone();
 4302        cx.spawn_in(window, |editor, mut cx| async move {
 4303            while let Some(prev_task) = task {
 4304                prev_task.await.log_err();
 4305                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4306            }
 4307
 4308            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4309                if editor.focus_handle.is_focused(window) {
 4310                    let multibuffer_point = action
 4311                        .deployed_from_indicator
 4312                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4313                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4314                    let (buffer, buffer_row) = snapshot
 4315                        .buffer_snapshot
 4316                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4317                        .and_then(|(buffer_snapshot, range)| {
 4318                            editor
 4319                                .buffer
 4320                                .read(cx)
 4321                                .buffer(buffer_snapshot.remote_id())
 4322                                .map(|buffer| (buffer, range.start.row))
 4323                        })?;
 4324                    let (_, code_actions) = editor
 4325                        .available_code_actions
 4326                        .clone()
 4327                        .and_then(|(location, code_actions)| {
 4328                            let snapshot = location.buffer.read(cx).snapshot();
 4329                            let point_range = location.range.to_point(&snapshot);
 4330                            let point_range = point_range.start.row..=point_range.end.row;
 4331                            if point_range.contains(&buffer_row) {
 4332                                Some((location, code_actions))
 4333                            } else {
 4334                                None
 4335                            }
 4336                        })
 4337                        .unzip();
 4338                    let buffer_id = buffer.read(cx).remote_id();
 4339                    let tasks = editor
 4340                        .tasks
 4341                        .get(&(buffer_id, buffer_row))
 4342                        .map(|t| Arc::new(t.to_owned()));
 4343                    if tasks.is_none() && code_actions.is_none() {
 4344                        return None;
 4345                    }
 4346
 4347                    editor.completion_tasks.clear();
 4348                    editor.discard_inline_completion(false, cx);
 4349                    let task_context =
 4350                        tasks
 4351                            .as_ref()
 4352                            .zip(editor.project.clone())
 4353                            .map(|(tasks, project)| {
 4354                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4355                            });
 4356
 4357                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4358                        let task_context = match task_context {
 4359                            Some(task_context) => task_context.await,
 4360                            None => None,
 4361                        };
 4362                        let resolved_tasks =
 4363                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4364                                Rc::new(ResolvedTasks {
 4365                                    templates: tasks.resolve(&task_context).collect(),
 4366                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4367                                        multibuffer_point.row,
 4368                                        tasks.column,
 4369                                    )),
 4370                                })
 4371                            });
 4372                        let spawn_straight_away = resolved_tasks
 4373                            .as_ref()
 4374                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4375                            && code_actions
 4376                                .as_ref()
 4377                                .map_or(true, |actions| actions.is_empty());
 4378                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4379                            *editor.context_menu.borrow_mut() =
 4380                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4381                                    buffer,
 4382                                    actions: CodeActionContents {
 4383                                        tasks: resolved_tasks,
 4384                                        actions: code_actions,
 4385                                    },
 4386                                    selected_item: Default::default(),
 4387                                    scroll_handle: UniformListScrollHandle::default(),
 4388                                    deployed_from_indicator,
 4389                                }));
 4390                            if spawn_straight_away {
 4391                                if let Some(task) = editor.confirm_code_action(
 4392                                    &ConfirmCodeAction { item_ix: Some(0) },
 4393                                    window,
 4394                                    cx,
 4395                                ) {
 4396                                    cx.notify();
 4397                                    return task;
 4398                                }
 4399                            }
 4400                            cx.notify();
 4401                            Task::ready(Ok(()))
 4402                        }) {
 4403                            task.await
 4404                        } else {
 4405                            Ok(())
 4406                        }
 4407                    }))
 4408                } else {
 4409                    Some(Task::ready(Ok(())))
 4410                }
 4411            })?;
 4412            if let Some(task) = spawned_test_task {
 4413                task.await?;
 4414            }
 4415
 4416            Ok::<_, anyhow::Error>(())
 4417        })
 4418        .detach_and_log_err(cx);
 4419    }
 4420
 4421    pub fn confirm_code_action(
 4422        &mut self,
 4423        action: &ConfirmCodeAction,
 4424        window: &mut Window,
 4425        cx: &mut Context<Self>,
 4426    ) -> Option<Task<Result<()>>> {
 4427        let actions_menu =
 4428            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4429                menu
 4430            } else {
 4431                return None;
 4432            };
 4433        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4434        let action = actions_menu.actions.get(action_ix)?;
 4435        let title = action.label();
 4436        let buffer = actions_menu.buffer;
 4437        let workspace = self.workspace()?;
 4438
 4439        match action {
 4440            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4441                workspace.update(cx, |workspace, cx| {
 4442                    workspace::tasks::schedule_resolved_task(
 4443                        workspace,
 4444                        task_source_kind,
 4445                        resolved_task,
 4446                        false,
 4447                        cx,
 4448                    );
 4449
 4450                    Some(Task::ready(Ok(())))
 4451                })
 4452            }
 4453            CodeActionsItem::CodeAction {
 4454                excerpt_id,
 4455                action,
 4456                provider,
 4457            } => {
 4458                let apply_code_action =
 4459                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4460                let workspace = workspace.downgrade();
 4461                Some(cx.spawn_in(window, |editor, cx| async move {
 4462                    let project_transaction = apply_code_action.await?;
 4463                    Self::open_project_transaction(
 4464                        &editor,
 4465                        workspace,
 4466                        project_transaction,
 4467                        title,
 4468                        cx,
 4469                    )
 4470                    .await
 4471                }))
 4472            }
 4473        }
 4474    }
 4475
 4476    pub async fn open_project_transaction(
 4477        this: &WeakEntity<Editor>,
 4478        workspace: WeakEntity<Workspace>,
 4479        transaction: ProjectTransaction,
 4480        title: String,
 4481        mut cx: AsyncWindowContext,
 4482    ) -> Result<()> {
 4483        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4484        cx.update(|_, cx| {
 4485            entries.sort_unstable_by_key(|(buffer, _)| {
 4486                buffer.read(cx).file().map(|f| f.path().clone())
 4487            });
 4488        })?;
 4489
 4490        // If the project transaction's edits are all contained within this editor, then
 4491        // avoid opening a new editor to display them.
 4492
 4493        if let Some((buffer, transaction)) = entries.first() {
 4494            if entries.len() == 1 {
 4495                let excerpt = this.update(&mut cx, |editor, cx| {
 4496                    editor
 4497                        .buffer()
 4498                        .read(cx)
 4499                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4500                })?;
 4501                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4502                    if excerpted_buffer == *buffer {
 4503                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4504                            let excerpt_range = excerpt_range.to_offset(buffer);
 4505                            buffer
 4506                                .edited_ranges_for_transaction::<usize>(transaction)
 4507                                .all(|range| {
 4508                                    excerpt_range.start <= range.start
 4509                                        && excerpt_range.end >= range.end
 4510                                })
 4511                        })?;
 4512
 4513                        if all_edits_within_excerpt {
 4514                            return Ok(());
 4515                        }
 4516                    }
 4517                }
 4518            }
 4519        } else {
 4520            return Ok(());
 4521        }
 4522
 4523        let mut ranges_to_highlight = Vec::new();
 4524        let excerpt_buffer = cx.new(|cx| {
 4525            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4526            for (buffer_handle, transaction) in &entries {
 4527                let buffer = buffer_handle.read(cx);
 4528                ranges_to_highlight.extend(
 4529                    multibuffer.push_excerpts_with_context_lines(
 4530                        buffer_handle.clone(),
 4531                        buffer
 4532                            .edited_ranges_for_transaction::<usize>(transaction)
 4533                            .collect(),
 4534                        DEFAULT_MULTIBUFFER_CONTEXT,
 4535                        cx,
 4536                    ),
 4537                );
 4538            }
 4539            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4540            multibuffer
 4541        })?;
 4542
 4543        workspace.update_in(&mut cx, |workspace, window, cx| {
 4544            let project = workspace.project().clone();
 4545            let editor = cx
 4546                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4547            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4548            editor.update(cx, |editor, cx| {
 4549                editor.highlight_background::<Self>(
 4550                    &ranges_to_highlight,
 4551                    |theme| theme.editor_highlighted_line_background,
 4552                    cx,
 4553                );
 4554            });
 4555        })?;
 4556
 4557        Ok(())
 4558    }
 4559
 4560    pub fn clear_code_action_providers(&mut self) {
 4561        self.code_action_providers.clear();
 4562        self.available_code_actions.take();
 4563    }
 4564
 4565    pub fn add_code_action_provider(
 4566        &mut self,
 4567        provider: Rc<dyn CodeActionProvider>,
 4568        window: &mut Window,
 4569        cx: &mut Context<Self>,
 4570    ) {
 4571        if self
 4572            .code_action_providers
 4573            .iter()
 4574            .any(|existing_provider| existing_provider.id() == provider.id())
 4575        {
 4576            return;
 4577        }
 4578
 4579        self.code_action_providers.push(provider);
 4580        self.refresh_code_actions(window, cx);
 4581    }
 4582
 4583    pub fn remove_code_action_provider(
 4584        &mut self,
 4585        id: Arc<str>,
 4586        window: &mut Window,
 4587        cx: &mut Context<Self>,
 4588    ) {
 4589        self.code_action_providers
 4590            .retain(|provider| provider.id() != id);
 4591        self.refresh_code_actions(window, cx);
 4592    }
 4593
 4594    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4595        let buffer = self.buffer.read(cx);
 4596        let newest_selection = self.selections.newest_anchor().clone();
 4597        if newest_selection.head().diff_base_anchor.is_some() {
 4598            return None;
 4599        }
 4600        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4601        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4602        if start_buffer != end_buffer {
 4603            return None;
 4604        }
 4605
 4606        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4607            cx.background_executor()
 4608                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4609                .await;
 4610
 4611            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4612                let providers = this.code_action_providers.clone();
 4613                let tasks = this
 4614                    .code_action_providers
 4615                    .iter()
 4616                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4617                    .collect::<Vec<_>>();
 4618                (providers, tasks)
 4619            })?;
 4620
 4621            let mut actions = Vec::new();
 4622            for (provider, provider_actions) in
 4623                providers.into_iter().zip(future::join_all(tasks).await)
 4624            {
 4625                if let Some(provider_actions) = provider_actions.log_err() {
 4626                    actions.extend(provider_actions.into_iter().map(|action| {
 4627                        AvailableCodeAction {
 4628                            excerpt_id: newest_selection.start.excerpt_id,
 4629                            action,
 4630                            provider: provider.clone(),
 4631                        }
 4632                    }));
 4633                }
 4634            }
 4635
 4636            this.update(&mut cx, |this, cx| {
 4637                this.available_code_actions = if actions.is_empty() {
 4638                    None
 4639                } else {
 4640                    Some((
 4641                        Location {
 4642                            buffer: start_buffer,
 4643                            range: start..end,
 4644                        },
 4645                        actions.into(),
 4646                    ))
 4647                };
 4648                cx.notify();
 4649            })
 4650        }));
 4651        None
 4652    }
 4653
 4654    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4655        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4656            self.show_git_blame_inline = false;
 4657
 4658            self.show_git_blame_inline_delay_task =
 4659                Some(cx.spawn_in(window, |this, mut cx| async move {
 4660                    cx.background_executor().timer(delay).await;
 4661
 4662                    this.update(&mut cx, |this, cx| {
 4663                        this.show_git_blame_inline = true;
 4664                        cx.notify();
 4665                    })
 4666                    .log_err();
 4667                }));
 4668        }
 4669    }
 4670
 4671    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4672        if self.pending_rename.is_some() {
 4673            return None;
 4674        }
 4675
 4676        let provider = self.semantics_provider.clone()?;
 4677        let buffer = self.buffer.read(cx);
 4678        let newest_selection = self.selections.newest_anchor().clone();
 4679        let cursor_position = newest_selection.head();
 4680        let (cursor_buffer, cursor_buffer_position) =
 4681            buffer.text_anchor_for_position(cursor_position, cx)?;
 4682        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4683        if cursor_buffer != tail_buffer {
 4684            return None;
 4685        }
 4686        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4687        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4688            cx.background_executor()
 4689                .timer(Duration::from_millis(debounce))
 4690                .await;
 4691
 4692            let highlights = if let Some(highlights) = cx
 4693                .update(|cx| {
 4694                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4695                })
 4696                .ok()
 4697                .flatten()
 4698            {
 4699                highlights.await.log_err()
 4700            } else {
 4701                None
 4702            };
 4703
 4704            if let Some(highlights) = highlights {
 4705                this.update(&mut cx, |this, cx| {
 4706                    if this.pending_rename.is_some() {
 4707                        return;
 4708                    }
 4709
 4710                    let buffer_id = cursor_position.buffer_id;
 4711                    let buffer = this.buffer.read(cx);
 4712                    if !buffer
 4713                        .text_anchor_for_position(cursor_position, cx)
 4714                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4715                    {
 4716                        return;
 4717                    }
 4718
 4719                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4720                    let mut write_ranges = Vec::new();
 4721                    let mut read_ranges = Vec::new();
 4722                    for highlight in highlights {
 4723                        for (excerpt_id, excerpt_range) in
 4724                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4725                        {
 4726                            let start = highlight
 4727                                .range
 4728                                .start
 4729                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4730                            let end = highlight
 4731                                .range
 4732                                .end
 4733                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4734                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4735                                continue;
 4736                            }
 4737
 4738                            let range = Anchor {
 4739                                buffer_id,
 4740                                excerpt_id,
 4741                                text_anchor: start,
 4742                                diff_base_anchor: None,
 4743                            }..Anchor {
 4744                                buffer_id,
 4745                                excerpt_id,
 4746                                text_anchor: end,
 4747                                diff_base_anchor: None,
 4748                            };
 4749                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4750                                write_ranges.push(range);
 4751                            } else {
 4752                                read_ranges.push(range);
 4753                            }
 4754                        }
 4755                    }
 4756
 4757                    this.highlight_background::<DocumentHighlightRead>(
 4758                        &read_ranges,
 4759                        |theme| theme.editor_document_highlight_read_background,
 4760                        cx,
 4761                    );
 4762                    this.highlight_background::<DocumentHighlightWrite>(
 4763                        &write_ranges,
 4764                        |theme| theme.editor_document_highlight_write_background,
 4765                        cx,
 4766                    );
 4767                    cx.notify();
 4768                })
 4769                .log_err();
 4770            }
 4771        }));
 4772        None
 4773    }
 4774
 4775    pub fn refresh_selected_text_highlights(
 4776        &mut self,
 4777        window: &mut Window,
 4778        cx: &mut Context<Editor>,
 4779    ) {
 4780        self.selection_highlight_task.take();
 4781        if !EditorSettings::get_global(cx).selection_highlight {
 4782            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4783            return;
 4784        }
 4785        if self.selections.count() != 1 || self.selections.line_mode {
 4786            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4787            return;
 4788        }
 4789        let selection = self.selections.newest::<Point>(cx);
 4790        if selection.is_empty() || selection.start.row != selection.end.row {
 4791            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4792            return;
 4793        }
 4794        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4795        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4796            cx.background_executor()
 4797                .timer(Duration::from_millis(debounce))
 4798                .await;
 4799            let Some(matches_task) = editor
 4800                .read_with(&mut cx, |editor, cx| {
 4801                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4802                    cx.background_spawn(async move {
 4803                        let mut ranges = Vec::new();
 4804                        let buffer_ranges =
 4805                            vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())];
 4806                        let query = buffer.text_for_range(selection.range()).collect::<String>();
 4807                        for range in buffer_ranges {
 4808                            for (search_buffer, search_range, excerpt_id) in
 4809                                buffer.range_to_buffer_ranges(range)
 4810                            {
 4811                                ranges.extend(
 4812                                    project::search::SearchQuery::text(
 4813                                        query.clone(),
 4814                                        false,
 4815                                        false,
 4816                                        false,
 4817                                        Default::default(),
 4818                                        Default::default(),
 4819                                        None,
 4820                                    )
 4821                                    .unwrap()
 4822                                    .search(search_buffer, Some(search_range.clone()))
 4823                                    .await
 4824                                    .into_iter()
 4825                                    .map(|match_range| {
 4826                                        let start = search_buffer
 4827                                            .anchor_after(search_range.start + match_range.start);
 4828                                        let end = search_buffer
 4829                                            .anchor_before(search_range.start + match_range.end);
 4830                                        Anchor::range_in_buffer(
 4831                                            excerpt_id,
 4832                                            search_buffer.remote_id(),
 4833                                            start..end,
 4834                                        )
 4835                                    }),
 4836                                );
 4837                            }
 4838                        }
 4839                        ranges
 4840                    })
 4841                })
 4842                .log_err()
 4843            else {
 4844                return;
 4845            };
 4846            let matches = matches_task.await;
 4847            editor
 4848                .update_in(&mut cx, |editor, _, cx| {
 4849                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4850                    if !matches.is_empty() {
 4851                        editor.highlight_background::<SelectedTextHighlight>(
 4852                            &matches,
 4853                            |theme| theme.editor_document_highlight_bracket_background,
 4854                            cx,
 4855                        )
 4856                    }
 4857                })
 4858                .log_err();
 4859        }));
 4860    }
 4861
 4862    pub fn refresh_inline_completion(
 4863        &mut self,
 4864        debounce: bool,
 4865        user_requested: bool,
 4866        window: &mut Window,
 4867        cx: &mut Context<Self>,
 4868    ) -> Option<()> {
 4869        let provider = self.edit_prediction_provider()?;
 4870        let cursor = self.selections.newest_anchor().head();
 4871        let (buffer, cursor_buffer_position) =
 4872            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4873
 4874        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4875            self.discard_inline_completion(false, cx);
 4876            return None;
 4877        }
 4878
 4879        if !user_requested
 4880            && (!self.should_show_edit_predictions()
 4881                || !self.is_focused(window)
 4882                || buffer.read(cx).is_empty())
 4883        {
 4884            self.discard_inline_completion(false, cx);
 4885            return None;
 4886        }
 4887
 4888        self.update_visible_inline_completion(window, cx);
 4889        provider.refresh(
 4890            self.project.clone(),
 4891            buffer,
 4892            cursor_buffer_position,
 4893            debounce,
 4894            cx,
 4895        );
 4896        Some(())
 4897    }
 4898
 4899    fn show_edit_predictions_in_menu(&self) -> bool {
 4900        match self.edit_prediction_settings {
 4901            EditPredictionSettings::Disabled => false,
 4902            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4903        }
 4904    }
 4905
 4906    pub fn edit_predictions_enabled(&self) -> bool {
 4907        match self.edit_prediction_settings {
 4908            EditPredictionSettings::Disabled => false,
 4909            EditPredictionSettings::Enabled { .. } => true,
 4910        }
 4911    }
 4912
 4913    fn edit_prediction_requires_modifier(&self) -> bool {
 4914        match self.edit_prediction_settings {
 4915            EditPredictionSettings::Disabled => false,
 4916            EditPredictionSettings::Enabled {
 4917                preview_requires_modifier,
 4918                ..
 4919            } => preview_requires_modifier,
 4920        }
 4921    }
 4922
 4923    fn edit_prediction_settings_at_position(
 4924        &self,
 4925        buffer: &Entity<Buffer>,
 4926        buffer_position: language::Anchor,
 4927        cx: &App,
 4928    ) -> EditPredictionSettings {
 4929        if self.mode != EditorMode::Full
 4930            || !self.show_inline_completions_override.unwrap_or(true)
 4931            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4932        {
 4933            return EditPredictionSettings::Disabled;
 4934        }
 4935
 4936        let buffer = buffer.read(cx);
 4937
 4938        let file = buffer.file();
 4939
 4940        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4941            return EditPredictionSettings::Disabled;
 4942        };
 4943
 4944        let by_provider = matches!(
 4945            self.menu_inline_completions_policy,
 4946            MenuInlineCompletionsPolicy::ByProvider
 4947        );
 4948
 4949        let show_in_menu = by_provider
 4950            && self
 4951                .edit_prediction_provider
 4952                .as_ref()
 4953                .map_or(false, |provider| {
 4954                    provider.provider.show_completions_in_menu()
 4955                });
 4956
 4957        let preview_requires_modifier =
 4958            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4959
 4960        EditPredictionSettings::Enabled {
 4961            show_in_menu,
 4962            preview_requires_modifier,
 4963        }
 4964    }
 4965
 4966    fn should_show_edit_predictions(&self) -> bool {
 4967        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4968    }
 4969
 4970    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4971        matches!(
 4972            self.edit_prediction_preview,
 4973            EditPredictionPreview::Active { .. }
 4974        )
 4975    }
 4976
 4977    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4978        let cursor = self.selections.newest_anchor().head();
 4979        if let Some((buffer, cursor_position)) =
 4980            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4981        {
 4982            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4983        } else {
 4984            false
 4985        }
 4986    }
 4987
 4988    fn inline_completions_enabled_in_buffer(
 4989        &self,
 4990        buffer: &Entity<Buffer>,
 4991        buffer_position: language::Anchor,
 4992        cx: &App,
 4993    ) -> bool {
 4994        maybe!({
 4995            let provider = self.edit_prediction_provider()?;
 4996            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4997                return Some(false);
 4998            }
 4999            let buffer = buffer.read(cx);
 5000            let Some(file) = buffer.file() else {
 5001                return Some(true);
 5002            };
 5003            let settings = all_language_settings(Some(file), cx);
 5004            Some(settings.inline_completions_enabled_for_path(file.path()))
 5005        })
 5006        .unwrap_or(false)
 5007    }
 5008
 5009    fn cycle_inline_completion(
 5010        &mut self,
 5011        direction: Direction,
 5012        window: &mut Window,
 5013        cx: &mut Context<Self>,
 5014    ) -> Option<()> {
 5015        let provider = self.edit_prediction_provider()?;
 5016        let cursor = self.selections.newest_anchor().head();
 5017        let (buffer, cursor_buffer_position) =
 5018            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5019        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5020            return None;
 5021        }
 5022
 5023        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5024        self.update_visible_inline_completion(window, cx);
 5025
 5026        Some(())
 5027    }
 5028
 5029    pub fn show_inline_completion(
 5030        &mut self,
 5031        _: &ShowEditPrediction,
 5032        window: &mut Window,
 5033        cx: &mut Context<Self>,
 5034    ) {
 5035        if !self.has_active_inline_completion() {
 5036            self.refresh_inline_completion(false, true, window, cx);
 5037            return;
 5038        }
 5039
 5040        self.update_visible_inline_completion(window, cx);
 5041    }
 5042
 5043    pub fn display_cursor_names(
 5044        &mut self,
 5045        _: &DisplayCursorNames,
 5046        window: &mut Window,
 5047        cx: &mut Context<Self>,
 5048    ) {
 5049        self.show_cursor_names(window, cx);
 5050    }
 5051
 5052    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5053        self.show_cursor_names = true;
 5054        cx.notify();
 5055        cx.spawn_in(window, |this, mut cx| async move {
 5056            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5057            this.update(&mut cx, |this, cx| {
 5058                this.show_cursor_names = false;
 5059                cx.notify()
 5060            })
 5061            .ok()
 5062        })
 5063        .detach();
 5064    }
 5065
 5066    pub fn next_edit_prediction(
 5067        &mut self,
 5068        _: &NextEditPrediction,
 5069        window: &mut Window,
 5070        cx: &mut Context<Self>,
 5071    ) {
 5072        if self.has_active_inline_completion() {
 5073            self.cycle_inline_completion(Direction::Next, window, cx);
 5074        } else {
 5075            let is_copilot_disabled = self
 5076                .refresh_inline_completion(false, true, window, cx)
 5077                .is_none();
 5078            if is_copilot_disabled {
 5079                cx.propagate();
 5080            }
 5081        }
 5082    }
 5083
 5084    pub fn previous_edit_prediction(
 5085        &mut self,
 5086        _: &PreviousEditPrediction,
 5087        window: &mut Window,
 5088        cx: &mut Context<Self>,
 5089    ) {
 5090        if self.has_active_inline_completion() {
 5091            self.cycle_inline_completion(Direction::Prev, window, cx);
 5092        } else {
 5093            let is_copilot_disabled = self
 5094                .refresh_inline_completion(false, true, window, cx)
 5095                .is_none();
 5096            if is_copilot_disabled {
 5097                cx.propagate();
 5098            }
 5099        }
 5100    }
 5101
 5102    pub fn accept_edit_prediction(
 5103        &mut self,
 5104        _: &AcceptEditPrediction,
 5105        window: &mut Window,
 5106        cx: &mut Context<Self>,
 5107    ) {
 5108        if self.show_edit_predictions_in_menu() {
 5109            self.hide_context_menu(window, cx);
 5110        }
 5111
 5112        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5113            return;
 5114        };
 5115
 5116        self.report_inline_completion_event(
 5117            active_inline_completion.completion_id.clone(),
 5118            true,
 5119            cx,
 5120        );
 5121
 5122        match &active_inline_completion.completion {
 5123            InlineCompletion::Move { target, .. } => {
 5124                let target = *target;
 5125
 5126                if let Some(position_map) = &self.last_position_map {
 5127                    if position_map
 5128                        .visible_row_range
 5129                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5130                        || !self.edit_prediction_requires_modifier()
 5131                    {
 5132                        self.unfold_ranges(&[target..target], true, false, cx);
 5133                        // Note that this is also done in vim's handler of the Tab action.
 5134                        self.change_selections(
 5135                            Some(Autoscroll::newest()),
 5136                            window,
 5137                            cx,
 5138                            |selections| {
 5139                                selections.select_anchor_ranges([target..target]);
 5140                            },
 5141                        );
 5142                        self.clear_row_highlights::<EditPredictionPreview>();
 5143
 5144                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5145                            previous_scroll_position: None,
 5146                        };
 5147                    } else {
 5148                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5149                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5150                        };
 5151                        self.highlight_rows::<EditPredictionPreview>(
 5152                            target..target,
 5153                            cx.theme().colors().editor_highlighted_line_background,
 5154                            true,
 5155                            cx,
 5156                        );
 5157                        self.request_autoscroll(Autoscroll::fit(), cx);
 5158                    }
 5159                }
 5160            }
 5161            InlineCompletion::Edit { edits, .. } => {
 5162                if let Some(provider) = self.edit_prediction_provider() {
 5163                    provider.accept(cx);
 5164                }
 5165
 5166                let snapshot = self.buffer.read(cx).snapshot(cx);
 5167                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5168
 5169                self.buffer.update(cx, |buffer, cx| {
 5170                    buffer.edit(edits.iter().cloned(), None, cx)
 5171                });
 5172
 5173                self.change_selections(None, window, cx, |s| {
 5174                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5175                });
 5176
 5177                self.update_visible_inline_completion(window, cx);
 5178                if self.active_inline_completion.is_none() {
 5179                    self.refresh_inline_completion(true, true, window, cx);
 5180                }
 5181
 5182                cx.notify();
 5183            }
 5184        }
 5185
 5186        self.edit_prediction_requires_modifier_in_leading_space = false;
 5187    }
 5188
 5189    pub fn accept_partial_inline_completion(
 5190        &mut self,
 5191        _: &AcceptPartialEditPrediction,
 5192        window: &mut Window,
 5193        cx: &mut Context<Self>,
 5194    ) {
 5195        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5196            return;
 5197        };
 5198        if self.selections.count() != 1 {
 5199            return;
 5200        }
 5201
 5202        self.report_inline_completion_event(
 5203            active_inline_completion.completion_id.clone(),
 5204            true,
 5205            cx,
 5206        );
 5207
 5208        match &active_inline_completion.completion {
 5209            InlineCompletion::Move { target, .. } => {
 5210                let target = *target;
 5211                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5212                    selections.select_anchor_ranges([target..target]);
 5213                });
 5214            }
 5215            InlineCompletion::Edit { edits, .. } => {
 5216                // Find an insertion that starts at the cursor position.
 5217                let snapshot = self.buffer.read(cx).snapshot(cx);
 5218                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5219                let insertion = edits.iter().find_map(|(range, text)| {
 5220                    let range = range.to_offset(&snapshot);
 5221                    if range.is_empty() && range.start == cursor_offset {
 5222                        Some(text)
 5223                    } else {
 5224                        None
 5225                    }
 5226                });
 5227
 5228                if let Some(text) = insertion {
 5229                    let mut partial_completion = text
 5230                        .chars()
 5231                        .by_ref()
 5232                        .take_while(|c| c.is_alphabetic())
 5233                        .collect::<String>();
 5234                    if partial_completion.is_empty() {
 5235                        partial_completion = text
 5236                            .chars()
 5237                            .by_ref()
 5238                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5239                            .collect::<String>();
 5240                    }
 5241
 5242                    cx.emit(EditorEvent::InputHandled {
 5243                        utf16_range_to_replace: None,
 5244                        text: partial_completion.clone().into(),
 5245                    });
 5246
 5247                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5248
 5249                    self.refresh_inline_completion(true, true, window, cx);
 5250                    cx.notify();
 5251                } else {
 5252                    self.accept_edit_prediction(&Default::default(), window, cx);
 5253                }
 5254            }
 5255        }
 5256    }
 5257
 5258    fn discard_inline_completion(
 5259        &mut self,
 5260        should_report_inline_completion_event: bool,
 5261        cx: &mut Context<Self>,
 5262    ) -> bool {
 5263        if should_report_inline_completion_event {
 5264            let completion_id = self
 5265                .active_inline_completion
 5266                .as_ref()
 5267                .and_then(|active_completion| active_completion.completion_id.clone());
 5268
 5269            self.report_inline_completion_event(completion_id, false, cx);
 5270        }
 5271
 5272        if let Some(provider) = self.edit_prediction_provider() {
 5273            provider.discard(cx);
 5274        }
 5275
 5276        self.take_active_inline_completion(cx)
 5277    }
 5278
 5279    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5280        let Some(provider) = self.edit_prediction_provider() else {
 5281            return;
 5282        };
 5283
 5284        let Some((_, buffer, _)) = self
 5285            .buffer
 5286            .read(cx)
 5287            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5288        else {
 5289            return;
 5290        };
 5291
 5292        let extension = buffer
 5293            .read(cx)
 5294            .file()
 5295            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5296
 5297        let event_type = match accepted {
 5298            true => "Edit Prediction Accepted",
 5299            false => "Edit Prediction Discarded",
 5300        };
 5301        telemetry::event!(
 5302            event_type,
 5303            provider = provider.name(),
 5304            prediction_id = id,
 5305            suggestion_accepted = accepted,
 5306            file_extension = extension,
 5307        );
 5308    }
 5309
 5310    pub fn has_active_inline_completion(&self) -> bool {
 5311        self.active_inline_completion.is_some()
 5312    }
 5313
 5314    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5315        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5316            return false;
 5317        };
 5318
 5319        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5320        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5321        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5322        true
 5323    }
 5324
 5325    /// Returns true when we're displaying the edit prediction popover below the cursor
 5326    /// like we are not previewing and the LSP autocomplete menu is visible
 5327    /// or we are in `when_holding_modifier` mode.
 5328    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5329        if self.edit_prediction_preview_is_active()
 5330            || !self.show_edit_predictions_in_menu()
 5331            || !self.edit_predictions_enabled()
 5332        {
 5333            return false;
 5334        }
 5335
 5336        if self.has_visible_completions_menu() {
 5337            return true;
 5338        }
 5339
 5340        has_completion && self.edit_prediction_requires_modifier()
 5341    }
 5342
 5343    fn handle_modifiers_changed(
 5344        &mut self,
 5345        modifiers: Modifiers,
 5346        position_map: &PositionMap,
 5347        window: &mut Window,
 5348        cx: &mut Context<Self>,
 5349    ) {
 5350        if self.show_edit_predictions_in_menu() {
 5351            self.update_edit_prediction_preview(&modifiers, window, cx);
 5352        }
 5353
 5354        self.update_selection_mode(&modifiers, position_map, window, cx);
 5355
 5356        let mouse_position = window.mouse_position();
 5357        if !position_map.text_hitbox.is_hovered(window) {
 5358            return;
 5359        }
 5360
 5361        self.update_hovered_link(
 5362            position_map.point_for_position(mouse_position),
 5363            &position_map.snapshot,
 5364            modifiers,
 5365            window,
 5366            cx,
 5367        )
 5368    }
 5369
 5370    fn update_selection_mode(
 5371        &mut self,
 5372        modifiers: &Modifiers,
 5373        position_map: &PositionMap,
 5374        window: &mut Window,
 5375        cx: &mut Context<Self>,
 5376    ) {
 5377        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5378            return;
 5379        }
 5380
 5381        let mouse_position = window.mouse_position();
 5382        let point_for_position = position_map.point_for_position(mouse_position);
 5383        let position = point_for_position.previous_valid;
 5384
 5385        self.select(
 5386            SelectPhase::BeginColumnar {
 5387                position,
 5388                reset: false,
 5389                goal_column: point_for_position.exact_unclipped.column(),
 5390            },
 5391            window,
 5392            cx,
 5393        );
 5394    }
 5395
 5396    fn update_edit_prediction_preview(
 5397        &mut self,
 5398        modifiers: &Modifiers,
 5399        window: &mut Window,
 5400        cx: &mut Context<Self>,
 5401    ) {
 5402        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5403        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5404            return;
 5405        };
 5406
 5407        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5408            if matches!(
 5409                self.edit_prediction_preview,
 5410                EditPredictionPreview::Inactive
 5411            ) {
 5412                self.edit_prediction_preview = EditPredictionPreview::Active {
 5413                    previous_scroll_position: None,
 5414                };
 5415
 5416                self.update_visible_inline_completion(window, cx);
 5417                cx.notify();
 5418            }
 5419        } else if let EditPredictionPreview::Active {
 5420            previous_scroll_position,
 5421        } = self.edit_prediction_preview
 5422        {
 5423            if let (Some(previous_scroll_position), Some(position_map)) =
 5424                (previous_scroll_position, self.last_position_map.as_ref())
 5425            {
 5426                self.set_scroll_position(
 5427                    previous_scroll_position
 5428                        .scroll_position(&position_map.snapshot.display_snapshot),
 5429                    window,
 5430                    cx,
 5431                );
 5432            }
 5433
 5434            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5435            self.clear_row_highlights::<EditPredictionPreview>();
 5436            self.update_visible_inline_completion(window, cx);
 5437            cx.notify();
 5438        }
 5439    }
 5440
 5441    fn update_visible_inline_completion(
 5442        &mut self,
 5443        _window: &mut Window,
 5444        cx: &mut Context<Self>,
 5445    ) -> Option<()> {
 5446        let selection = self.selections.newest_anchor();
 5447        let cursor = selection.head();
 5448        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5449        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5450        let excerpt_id = cursor.excerpt_id;
 5451
 5452        let show_in_menu = self.show_edit_predictions_in_menu();
 5453        let completions_menu_has_precedence = !show_in_menu
 5454            && (self.context_menu.borrow().is_some()
 5455                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5456
 5457        if completions_menu_has_precedence
 5458            || !offset_selection.is_empty()
 5459            || self
 5460                .active_inline_completion
 5461                .as_ref()
 5462                .map_or(false, |completion| {
 5463                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5464                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5465                    !invalidation_range.contains(&offset_selection.head())
 5466                })
 5467        {
 5468            self.discard_inline_completion(false, cx);
 5469            return None;
 5470        }
 5471
 5472        self.take_active_inline_completion(cx);
 5473        let Some(provider) = self.edit_prediction_provider() else {
 5474            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5475            return None;
 5476        };
 5477
 5478        let (buffer, cursor_buffer_position) =
 5479            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5480
 5481        self.edit_prediction_settings =
 5482            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5483
 5484        self.edit_prediction_cursor_on_leading_whitespace =
 5485            multibuffer.is_line_whitespace_upto(cursor);
 5486
 5487        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5488        let edits = inline_completion
 5489            .edits
 5490            .into_iter()
 5491            .flat_map(|(range, new_text)| {
 5492                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5493                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5494                Some((start..end, new_text))
 5495            })
 5496            .collect::<Vec<_>>();
 5497        if edits.is_empty() {
 5498            return None;
 5499        }
 5500
 5501        let first_edit_start = edits.first().unwrap().0.start;
 5502        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5503        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5504
 5505        let last_edit_end = edits.last().unwrap().0.end;
 5506        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5507        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5508
 5509        let cursor_row = cursor.to_point(&multibuffer).row;
 5510
 5511        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5512
 5513        let mut inlay_ids = Vec::new();
 5514        let invalidation_row_range;
 5515        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5516            Some(cursor_row..edit_end_row)
 5517        } else if cursor_row > edit_end_row {
 5518            Some(edit_start_row..cursor_row)
 5519        } else {
 5520            None
 5521        };
 5522        let is_move =
 5523            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5524        let completion = if is_move {
 5525            invalidation_row_range =
 5526                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5527            let target = first_edit_start;
 5528            InlineCompletion::Move { target, snapshot }
 5529        } else {
 5530            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5531                && !self.inline_completions_hidden_for_vim_mode;
 5532
 5533            if show_completions_in_buffer {
 5534                if edits
 5535                    .iter()
 5536                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5537                {
 5538                    let mut inlays = Vec::new();
 5539                    for (range, new_text) in &edits {
 5540                        let inlay = Inlay::inline_completion(
 5541                            post_inc(&mut self.next_inlay_id),
 5542                            range.start,
 5543                            new_text.as_str(),
 5544                        );
 5545                        inlay_ids.push(inlay.id);
 5546                        inlays.push(inlay);
 5547                    }
 5548
 5549                    self.splice_inlays(&[], inlays, cx);
 5550                } else {
 5551                    let background_color = cx.theme().status().deleted_background;
 5552                    self.highlight_text::<InlineCompletionHighlight>(
 5553                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5554                        HighlightStyle {
 5555                            background_color: Some(background_color),
 5556                            ..Default::default()
 5557                        },
 5558                        cx,
 5559                    );
 5560                }
 5561            }
 5562
 5563            invalidation_row_range = edit_start_row..edit_end_row;
 5564
 5565            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5566                if provider.show_tab_accept_marker() {
 5567                    EditDisplayMode::TabAccept
 5568                } else {
 5569                    EditDisplayMode::Inline
 5570                }
 5571            } else {
 5572                EditDisplayMode::DiffPopover
 5573            };
 5574
 5575            InlineCompletion::Edit {
 5576                edits,
 5577                edit_preview: inline_completion.edit_preview,
 5578                display_mode,
 5579                snapshot,
 5580            }
 5581        };
 5582
 5583        let invalidation_range = multibuffer
 5584            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5585            ..multibuffer.anchor_after(Point::new(
 5586                invalidation_row_range.end,
 5587                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5588            ));
 5589
 5590        self.stale_inline_completion_in_menu = None;
 5591        self.active_inline_completion = Some(InlineCompletionState {
 5592            inlay_ids,
 5593            completion,
 5594            completion_id: inline_completion.id,
 5595            invalidation_range,
 5596        });
 5597
 5598        cx.notify();
 5599
 5600        Some(())
 5601    }
 5602
 5603    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5604        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5605    }
 5606
 5607    fn render_code_actions_indicator(
 5608        &self,
 5609        _style: &EditorStyle,
 5610        row: DisplayRow,
 5611        is_active: bool,
 5612        cx: &mut Context<Self>,
 5613    ) -> Option<IconButton> {
 5614        if self.available_code_actions.is_some() {
 5615            Some(
 5616                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5617                    .shape(ui::IconButtonShape::Square)
 5618                    .icon_size(IconSize::XSmall)
 5619                    .icon_color(Color::Muted)
 5620                    .toggle_state(is_active)
 5621                    .tooltip({
 5622                        let focus_handle = self.focus_handle.clone();
 5623                        move |window, cx| {
 5624                            Tooltip::for_action_in(
 5625                                "Toggle Code Actions",
 5626                                &ToggleCodeActions {
 5627                                    deployed_from_indicator: None,
 5628                                },
 5629                                &focus_handle,
 5630                                window,
 5631                                cx,
 5632                            )
 5633                        }
 5634                    })
 5635                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5636                        window.focus(&editor.focus_handle(cx));
 5637                        editor.toggle_code_actions(
 5638                            &ToggleCodeActions {
 5639                                deployed_from_indicator: Some(row),
 5640                            },
 5641                            window,
 5642                            cx,
 5643                        );
 5644                    })),
 5645            )
 5646        } else {
 5647            None
 5648        }
 5649    }
 5650
 5651    fn clear_tasks(&mut self) {
 5652        self.tasks.clear()
 5653    }
 5654
 5655    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5656        if self.tasks.insert(key, value).is_some() {
 5657            // This case should hopefully be rare, but just in case...
 5658            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5659        }
 5660    }
 5661
 5662    fn build_tasks_context(
 5663        project: &Entity<Project>,
 5664        buffer: &Entity<Buffer>,
 5665        buffer_row: u32,
 5666        tasks: &Arc<RunnableTasks>,
 5667        cx: &mut Context<Self>,
 5668    ) -> Task<Option<task::TaskContext>> {
 5669        let position = Point::new(buffer_row, tasks.column);
 5670        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5671        let location = Location {
 5672            buffer: buffer.clone(),
 5673            range: range_start..range_start,
 5674        };
 5675        // Fill in the environmental variables from the tree-sitter captures
 5676        let mut captured_task_variables = TaskVariables::default();
 5677        for (capture_name, value) in tasks.extra_variables.clone() {
 5678            captured_task_variables.insert(
 5679                task::VariableName::Custom(capture_name.into()),
 5680                value.clone(),
 5681            );
 5682        }
 5683        project.update(cx, |project, cx| {
 5684            project.task_store().update(cx, |task_store, cx| {
 5685                task_store.task_context_for_location(captured_task_variables, location, cx)
 5686            })
 5687        })
 5688    }
 5689
 5690    pub fn spawn_nearest_task(
 5691        &mut self,
 5692        action: &SpawnNearestTask,
 5693        window: &mut Window,
 5694        cx: &mut Context<Self>,
 5695    ) {
 5696        let Some((workspace, _)) = self.workspace.clone() else {
 5697            return;
 5698        };
 5699        let Some(project) = self.project.clone() else {
 5700            return;
 5701        };
 5702
 5703        // Try to find a closest, enclosing node using tree-sitter that has a
 5704        // task
 5705        let Some((buffer, buffer_row, tasks)) = self
 5706            .find_enclosing_node_task(cx)
 5707            // Or find the task that's closest in row-distance.
 5708            .or_else(|| self.find_closest_task(cx))
 5709        else {
 5710            return;
 5711        };
 5712
 5713        let reveal_strategy = action.reveal;
 5714        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5715        cx.spawn_in(window, |_, mut cx| async move {
 5716            let context = task_context.await?;
 5717            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5718
 5719            let resolved = resolved_task.resolved.as_mut()?;
 5720            resolved.reveal = reveal_strategy;
 5721
 5722            workspace
 5723                .update(&mut cx, |workspace, cx| {
 5724                    workspace::tasks::schedule_resolved_task(
 5725                        workspace,
 5726                        task_source_kind,
 5727                        resolved_task,
 5728                        false,
 5729                        cx,
 5730                    );
 5731                })
 5732                .ok()
 5733        })
 5734        .detach();
 5735    }
 5736
 5737    fn find_closest_task(
 5738        &mut self,
 5739        cx: &mut Context<Self>,
 5740    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5741        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5742
 5743        let ((buffer_id, row), tasks) = self
 5744            .tasks
 5745            .iter()
 5746            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5747
 5748        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5749        let tasks = Arc::new(tasks.to_owned());
 5750        Some((buffer, *row, tasks))
 5751    }
 5752
 5753    fn find_enclosing_node_task(
 5754        &mut self,
 5755        cx: &mut Context<Self>,
 5756    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5757        let snapshot = self.buffer.read(cx).snapshot(cx);
 5758        let offset = self.selections.newest::<usize>(cx).head();
 5759        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5760        let buffer_id = excerpt.buffer().remote_id();
 5761
 5762        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5763        let mut cursor = layer.node().walk();
 5764
 5765        while cursor.goto_first_child_for_byte(offset).is_some() {
 5766            if cursor.node().end_byte() == offset {
 5767                cursor.goto_next_sibling();
 5768            }
 5769        }
 5770
 5771        // Ascend to the smallest ancestor that contains the range and has a task.
 5772        loop {
 5773            let node = cursor.node();
 5774            let node_range = node.byte_range();
 5775            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5776
 5777            // Check if this node contains our offset
 5778            if node_range.start <= offset && node_range.end >= offset {
 5779                // If it contains offset, check for task
 5780                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5781                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5782                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5783                }
 5784            }
 5785
 5786            if !cursor.goto_parent() {
 5787                break;
 5788            }
 5789        }
 5790        None
 5791    }
 5792
 5793    fn render_run_indicator(
 5794        &self,
 5795        _style: &EditorStyle,
 5796        is_active: bool,
 5797        row: DisplayRow,
 5798        cx: &mut Context<Self>,
 5799    ) -> IconButton {
 5800        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5801            .shape(ui::IconButtonShape::Square)
 5802            .icon_size(IconSize::XSmall)
 5803            .icon_color(Color::Muted)
 5804            .toggle_state(is_active)
 5805            .on_click(cx.listener(move |editor, _e, window, cx| {
 5806                window.focus(&editor.focus_handle(cx));
 5807                editor.toggle_code_actions(
 5808                    &ToggleCodeActions {
 5809                        deployed_from_indicator: Some(row),
 5810                    },
 5811                    window,
 5812                    cx,
 5813                );
 5814            }))
 5815    }
 5816
 5817    pub fn context_menu_visible(&self) -> bool {
 5818        !self.edit_prediction_preview_is_active()
 5819            && self
 5820                .context_menu
 5821                .borrow()
 5822                .as_ref()
 5823                .map_or(false, |menu| menu.visible())
 5824    }
 5825
 5826    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5827        self.context_menu
 5828            .borrow()
 5829            .as_ref()
 5830            .map(|menu| menu.origin())
 5831    }
 5832
 5833    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5834        px(30.)
 5835    }
 5836
 5837    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5838        if self.read_only(cx) {
 5839            cx.theme().players().read_only()
 5840        } else {
 5841            self.style.as_ref().unwrap().local_player
 5842        }
 5843    }
 5844
 5845    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5846        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5847        let accept_keystroke = accept_binding.keystroke()?;
 5848
 5849        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5850
 5851        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5852            Color::Accent
 5853        } else {
 5854            Color::Muted
 5855        };
 5856
 5857        h_flex()
 5858            .px_0p5()
 5859            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5860            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5861            .text_size(TextSize::XSmall.rems(cx))
 5862            .child(h_flex().children(ui::render_modifiers(
 5863                &accept_keystroke.modifiers,
 5864                PlatformStyle::platform(),
 5865                Some(modifiers_color),
 5866                Some(IconSize::XSmall.rems().into()),
 5867                true,
 5868            )))
 5869            .when(is_platform_style_mac, |parent| {
 5870                parent.child(accept_keystroke.key.clone())
 5871            })
 5872            .when(!is_platform_style_mac, |parent| {
 5873                parent.child(
 5874                    Key::new(
 5875                        util::capitalize(&accept_keystroke.key),
 5876                        Some(Color::Default),
 5877                    )
 5878                    .size(Some(IconSize::XSmall.rems().into())),
 5879                )
 5880            })
 5881            .into()
 5882    }
 5883
 5884    fn render_edit_prediction_line_popover(
 5885        &self,
 5886        label: impl Into<SharedString>,
 5887        icon: Option<IconName>,
 5888        window: &mut Window,
 5889        cx: &App,
 5890    ) -> Option<Div> {
 5891        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5892
 5893        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5894
 5895        let result = h_flex()
 5896            .gap_1()
 5897            .border_1()
 5898            .rounded_lg()
 5899            .shadow_sm()
 5900            .bg(bg_color)
 5901            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5902            .py_0p5()
 5903            .pl_1()
 5904            .pr(padding_right)
 5905            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5906            .child(Label::new(label).size(LabelSize::Small))
 5907            .when_some(icon, |element, icon| {
 5908                element.child(
 5909                    div()
 5910                        .mt(px(1.5))
 5911                        .child(Icon::new(icon).size(IconSize::Small)),
 5912                )
 5913            });
 5914
 5915        Some(result)
 5916    }
 5917
 5918    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5919        let accent_color = cx.theme().colors().text_accent;
 5920        let editor_bg_color = cx.theme().colors().editor_background;
 5921        editor_bg_color.blend(accent_color.opacity(0.1))
 5922    }
 5923
 5924    fn render_edit_prediction_cursor_popover(
 5925        &self,
 5926        min_width: Pixels,
 5927        max_width: Pixels,
 5928        cursor_point: Point,
 5929        style: &EditorStyle,
 5930        accept_keystroke: Option<&gpui::Keystroke>,
 5931        _window: &Window,
 5932        cx: &mut Context<Editor>,
 5933    ) -> Option<AnyElement> {
 5934        let provider = self.edit_prediction_provider.as_ref()?;
 5935
 5936        if provider.provider.needs_terms_acceptance(cx) {
 5937            return Some(
 5938                h_flex()
 5939                    .min_w(min_width)
 5940                    .flex_1()
 5941                    .px_2()
 5942                    .py_1()
 5943                    .gap_3()
 5944                    .elevation_2(cx)
 5945                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5946                    .id("accept-terms")
 5947                    .cursor_pointer()
 5948                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5949                    .on_click(cx.listener(|this, _event, window, cx| {
 5950                        cx.stop_propagation();
 5951                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5952                        window.dispatch_action(
 5953                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5954                            cx,
 5955                        );
 5956                    }))
 5957                    .child(
 5958                        h_flex()
 5959                            .flex_1()
 5960                            .gap_2()
 5961                            .child(Icon::new(IconName::ZedPredict))
 5962                            .child(Label::new("Accept Terms of Service"))
 5963                            .child(div().w_full())
 5964                            .child(
 5965                                Icon::new(IconName::ArrowUpRight)
 5966                                    .color(Color::Muted)
 5967                                    .size(IconSize::Small),
 5968                            )
 5969                            .into_any_element(),
 5970                    )
 5971                    .into_any(),
 5972            );
 5973        }
 5974
 5975        let is_refreshing = provider.provider.is_refreshing(cx);
 5976
 5977        fn pending_completion_container() -> Div {
 5978            h_flex()
 5979                .h_full()
 5980                .flex_1()
 5981                .gap_2()
 5982                .child(Icon::new(IconName::ZedPredict))
 5983        }
 5984
 5985        let completion = match &self.active_inline_completion {
 5986            Some(completion) => match &completion.completion {
 5987                InlineCompletion::Move {
 5988                    target, snapshot, ..
 5989                } if !self.has_visible_completions_menu() => {
 5990                    use text::ToPoint as _;
 5991
 5992                    return Some(
 5993                        h_flex()
 5994                            .px_2()
 5995                            .py_1()
 5996                            .elevation_2(cx)
 5997                            .border_color(cx.theme().colors().border)
 5998                            .rounded_tl(px(0.))
 5999                            .gap_2()
 6000                            .child(
 6001                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6002                                    Icon::new(IconName::ZedPredictDown)
 6003                                } else {
 6004                                    Icon::new(IconName::ZedPredictUp)
 6005                                },
 6006                            )
 6007                            .child(Label::new("Hold").size(LabelSize::Small))
 6008                            .child(h_flex().children(ui::render_modifiers(
 6009                                &accept_keystroke?.modifiers,
 6010                                PlatformStyle::platform(),
 6011                                Some(Color::Default),
 6012                                Some(IconSize::Small.rems().into()),
 6013                                false,
 6014                            )))
 6015                            .into_any(),
 6016                    );
 6017                }
 6018                _ => self.render_edit_prediction_cursor_popover_preview(
 6019                    completion,
 6020                    cursor_point,
 6021                    style,
 6022                    cx,
 6023                )?,
 6024            },
 6025
 6026            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6027                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6028                    stale_completion,
 6029                    cursor_point,
 6030                    style,
 6031                    cx,
 6032                )?,
 6033
 6034                None => {
 6035                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6036                }
 6037            },
 6038
 6039            None => pending_completion_container().child(Label::new("No Prediction")),
 6040        };
 6041
 6042        let completion = if is_refreshing {
 6043            completion
 6044                .with_animation(
 6045                    "loading-completion",
 6046                    Animation::new(Duration::from_secs(2))
 6047                        .repeat()
 6048                        .with_easing(pulsating_between(0.4, 0.8)),
 6049                    |label, delta| label.opacity(delta),
 6050                )
 6051                .into_any_element()
 6052        } else {
 6053            completion.into_any_element()
 6054        };
 6055
 6056        let has_completion = self.active_inline_completion.is_some();
 6057
 6058        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6059        Some(
 6060            h_flex()
 6061                .min_w(min_width)
 6062                .max_w(max_width)
 6063                .flex_1()
 6064                .elevation_2(cx)
 6065                .border_color(cx.theme().colors().border)
 6066                .child(
 6067                    div()
 6068                        .flex_1()
 6069                        .py_1()
 6070                        .px_2()
 6071                        .overflow_hidden()
 6072                        .child(completion),
 6073                )
 6074                .when_some(accept_keystroke, |el, accept_keystroke| {
 6075                    if !accept_keystroke.modifiers.modified() {
 6076                        return el;
 6077                    }
 6078
 6079                    el.child(
 6080                        h_flex()
 6081                            .h_full()
 6082                            .border_l_1()
 6083                            .rounded_r_lg()
 6084                            .border_color(cx.theme().colors().border)
 6085                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6086                            .gap_1()
 6087                            .py_1()
 6088                            .px_2()
 6089                            .child(
 6090                                h_flex()
 6091                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6092                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6093                                    .child(h_flex().children(ui::render_modifiers(
 6094                                        &accept_keystroke.modifiers,
 6095                                        PlatformStyle::platform(),
 6096                                        Some(if !has_completion {
 6097                                            Color::Muted
 6098                                        } else {
 6099                                            Color::Default
 6100                                        }),
 6101                                        None,
 6102                                        false,
 6103                                    ))),
 6104                            )
 6105                            .child(Label::new("Preview").into_any_element())
 6106                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6107                    )
 6108                })
 6109                .into_any(),
 6110        )
 6111    }
 6112
 6113    fn render_edit_prediction_cursor_popover_preview(
 6114        &self,
 6115        completion: &InlineCompletionState,
 6116        cursor_point: Point,
 6117        style: &EditorStyle,
 6118        cx: &mut Context<Editor>,
 6119    ) -> Option<Div> {
 6120        use text::ToPoint as _;
 6121
 6122        fn render_relative_row_jump(
 6123            prefix: impl Into<String>,
 6124            current_row: u32,
 6125            target_row: u32,
 6126        ) -> Div {
 6127            let (row_diff, arrow) = if target_row < current_row {
 6128                (current_row - target_row, IconName::ArrowUp)
 6129            } else {
 6130                (target_row - current_row, IconName::ArrowDown)
 6131            };
 6132
 6133            h_flex()
 6134                .child(
 6135                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6136                        .color(Color::Muted)
 6137                        .size(LabelSize::Small),
 6138                )
 6139                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6140        }
 6141
 6142        match &completion.completion {
 6143            InlineCompletion::Move {
 6144                target, snapshot, ..
 6145            } => Some(
 6146                h_flex()
 6147                    .px_2()
 6148                    .gap_2()
 6149                    .flex_1()
 6150                    .child(
 6151                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6152                            Icon::new(IconName::ZedPredictDown)
 6153                        } else {
 6154                            Icon::new(IconName::ZedPredictUp)
 6155                        },
 6156                    )
 6157                    .child(Label::new("Jump to Edit")),
 6158            ),
 6159
 6160            InlineCompletion::Edit {
 6161                edits,
 6162                edit_preview,
 6163                snapshot,
 6164                display_mode: _,
 6165            } => {
 6166                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6167
 6168                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6169                    &snapshot,
 6170                    &edits,
 6171                    edit_preview.as_ref()?,
 6172                    true,
 6173                    cx,
 6174                )
 6175                .first_line_preview();
 6176
 6177                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6178                    .with_highlights(&style.text, highlighted_edits.highlights);
 6179
 6180                let preview = h_flex()
 6181                    .gap_1()
 6182                    .min_w_16()
 6183                    .child(styled_text)
 6184                    .when(has_more_lines, |parent| parent.child(""));
 6185
 6186                let left = if first_edit_row != cursor_point.row {
 6187                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6188                        .into_any_element()
 6189                } else {
 6190                    Icon::new(IconName::ZedPredict).into_any_element()
 6191                };
 6192
 6193                Some(
 6194                    h_flex()
 6195                        .h_full()
 6196                        .flex_1()
 6197                        .gap_2()
 6198                        .pr_1()
 6199                        .overflow_x_hidden()
 6200                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6201                        .child(left)
 6202                        .child(preview),
 6203                )
 6204            }
 6205        }
 6206    }
 6207
 6208    fn render_context_menu(
 6209        &self,
 6210        style: &EditorStyle,
 6211        max_height_in_lines: u32,
 6212        y_flipped: bool,
 6213        window: &mut Window,
 6214        cx: &mut Context<Editor>,
 6215    ) -> Option<AnyElement> {
 6216        let menu = self.context_menu.borrow();
 6217        let menu = menu.as_ref()?;
 6218        if !menu.visible() {
 6219            return None;
 6220        };
 6221        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6222    }
 6223
 6224    fn render_context_menu_aside(
 6225        &mut self,
 6226        max_size: Size<Pixels>,
 6227        window: &mut Window,
 6228        cx: &mut Context<Editor>,
 6229    ) -> Option<AnyElement> {
 6230        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6231            if menu.visible() {
 6232                menu.render_aside(self, max_size, window, cx)
 6233            } else {
 6234                None
 6235            }
 6236        })
 6237    }
 6238
 6239    fn hide_context_menu(
 6240        &mut self,
 6241        window: &mut Window,
 6242        cx: &mut Context<Self>,
 6243    ) -> Option<CodeContextMenu> {
 6244        cx.notify();
 6245        self.completion_tasks.clear();
 6246        let context_menu = self.context_menu.borrow_mut().take();
 6247        self.stale_inline_completion_in_menu.take();
 6248        self.update_visible_inline_completion(window, cx);
 6249        context_menu
 6250    }
 6251
 6252    fn show_snippet_choices(
 6253        &mut self,
 6254        choices: &Vec<String>,
 6255        selection: Range<Anchor>,
 6256        cx: &mut Context<Self>,
 6257    ) {
 6258        if selection.start.buffer_id.is_none() {
 6259            return;
 6260        }
 6261        let buffer_id = selection.start.buffer_id.unwrap();
 6262        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6263        let id = post_inc(&mut self.next_completion_id);
 6264
 6265        if let Some(buffer) = buffer {
 6266            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6267                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6268            ));
 6269        }
 6270    }
 6271
 6272    pub fn insert_snippet(
 6273        &mut self,
 6274        insertion_ranges: &[Range<usize>],
 6275        snippet: Snippet,
 6276        window: &mut Window,
 6277        cx: &mut Context<Self>,
 6278    ) -> Result<()> {
 6279        struct Tabstop<T> {
 6280            is_end_tabstop: bool,
 6281            ranges: Vec<Range<T>>,
 6282            choices: Option<Vec<String>>,
 6283        }
 6284
 6285        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6286            let snippet_text: Arc<str> = snippet.text.clone().into();
 6287            buffer.edit(
 6288                insertion_ranges
 6289                    .iter()
 6290                    .cloned()
 6291                    .map(|range| (range, snippet_text.clone())),
 6292                Some(AutoindentMode::EachLine),
 6293                cx,
 6294            );
 6295
 6296            let snapshot = &*buffer.read(cx);
 6297            let snippet = &snippet;
 6298            snippet
 6299                .tabstops
 6300                .iter()
 6301                .map(|tabstop| {
 6302                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6303                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6304                    });
 6305                    let mut tabstop_ranges = tabstop
 6306                        .ranges
 6307                        .iter()
 6308                        .flat_map(|tabstop_range| {
 6309                            let mut delta = 0_isize;
 6310                            insertion_ranges.iter().map(move |insertion_range| {
 6311                                let insertion_start = insertion_range.start as isize + delta;
 6312                                delta +=
 6313                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6314
 6315                                let start = ((insertion_start + tabstop_range.start) as usize)
 6316                                    .min(snapshot.len());
 6317                                let end = ((insertion_start + tabstop_range.end) as usize)
 6318                                    .min(snapshot.len());
 6319                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6320                            })
 6321                        })
 6322                        .collect::<Vec<_>>();
 6323                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6324
 6325                    Tabstop {
 6326                        is_end_tabstop,
 6327                        ranges: tabstop_ranges,
 6328                        choices: tabstop.choices.clone(),
 6329                    }
 6330                })
 6331                .collect::<Vec<_>>()
 6332        });
 6333        if let Some(tabstop) = tabstops.first() {
 6334            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6335                s.select_ranges(tabstop.ranges.iter().cloned());
 6336            });
 6337
 6338            if let Some(choices) = &tabstop.choices {
 6339                if let Some(selection) = tabstop.ranges.first() {
 6340                    self.show_snippet_choices(choices, selection.clone(), cx)
 6341                }
 6342            }
 6343
 6344            // If we're already at the last tabstop and it's at the end of the snippet,
 6345            // we're done, we don't need to keep the state around.
 6346            if !tabstop.is_end_tabstop {
 6347                let choices = tabstops
 6348                    .iter()
 6349                    .map(|tabstop| tabstop.choices.clone())
 6350                    .collect();
 6351
 6352                let ranges = tabstops
 6353                    .into_iter()
 6354                    .map(|tabstop| tabstop.ranges)
 6355                    .collect::<Vec<_>>();
 6356
 6357                self.snippet_stack.push(SnippetState {
 6358                    active_index: 0,
 6359                    ranges,
 6360                    choices,
 6361                });
 6362            }
 6363
 6364            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6365            if self.autoclose_regions.is_empty() {
 6366                let snapshot = self.buffer.read(cx).snapshot(cx);
 6367                for selection in &mut self.selections.all::<Point>(cx) {
 6368                    let selection_head = selection.head();
 6369                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6370                        continue;
 6371                    };
 6372
 6373                    let mut bracket_pair = None;
 6374                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6375                    let prev_chars = snapshot
 6376                        .reversed_chars_at(selection_head)
 6377                        .collect::<String>();
 6378                    for (pair, enabled) in scope.brackets() {
 6379                        if enabled
 6380                            && pair.close
 6381                            && prev_chars.starts_with(pair.start.as_str())
 6382                            && next_chars.starts_with(pair.end.as_str())
 6383                        {
 6384                            bracket_pair = Some(pair.clone());
 6385                            break;
 6386                        }
 6387                    }
 6388                    if let Some(pair) = bracket_pair {
 6389                        let start = snapshot.anchor_after(selection_head);
 6390                        let end = snapshot.anchor_after(selection_head);
 6391                        self.autoclose_regions.push(AutocloseRegion {
 6392                            selection_id: selection.id,
 6393                            range: start..end,
 6394                            pair,
 6395                        });
 6396                    }
 6397                }
 6398            }
 6399        }
 6400        Ok(())
 6401    }
 6402
 6403    pub fn move_to_next_snippet_tabstop(
 6404        &mut self,
 6405        window: &mut Window,
 6406        cx: &mut Context<Self>,
 6407    ) -> bool {
 6408        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6409    }
 6410
 6411    pub fn move_to_prev_snippet_tabstop(
 6412        &mut self,
 6413        window: &mut Window,
 6414        cx: &mut Context<Self>,
 6415    ) -> bool {
 6416        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6417    }
 6418
 6419    pub fn move_to_snippet_tabstop(
 6420        &mut self,
 6421        bias: Bias,
 6422        window: &mut Window,
 6423        cx: &mut Context<Self>,
 6424    ) -> bool {
 6425        if let Some(mut snippet) = self.snippet_stack.pop() {
 6426            match bias {
 6427                Bias::Left => {
 6428                    if snippet.active_index > 0 {
 6429                        snippet.active_index -= 1;
 6430                    } else {
 6431                        self.snippet_stack.push(snippet);
 6432                        return false;
 6433                    }
 6434                }
 6435                Bias::Right => {
 6436                    if snippet.active_index + 1 < snippet.ranges.len() {
 6437                        snippet.active_index += 1;
 6438                    } else {
 6439                        self.snippet_stack.push(snippet);
 6440                        return false;
 6441                    }
 6442                }
 6443            }
 6444            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6445                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6446                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6447                });
 6448
 6449                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6450                    if let Some(selection) = current_ranges.first() {
 6451                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6452                    }
 6453                }
 6454
 6455                // If snippet state is not at the last tabstop, push it back on the stack
 6456                if snippet.active_index + 1 < snippet.ranges.len() {
 6457                    self.snippet_stack.push(snippet);
 6458                }
 6459                return true;
 6460            }
 6461        }
 6462
 6463        false
 6464    }
 6465
 6466    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6467        self.transact(window, cx, |this, window, cx| {
 6468            this.select_all(&SelectAll, window, cx);
 6469            this.insert("", window, cx);
 6470        });
 6471    }
 6472
 6473    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6474        self.transact(window, cx, |this, window, cx| {
 6475            this.select_autoclose_pair(window, cx);
 6476            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6477            if !this.linked_edit_ranges.is_empty() {
 6478                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6479                let snapshot = this.buffer.read(cx).snapshot(cx);
 6480
 6481                for selection in selections.iter() {
 6482                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6483                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6484                    if selection_start.buffer_id != selection_end.buffer_id {
 6485                        continue;
 6486                    }
 6487                    if let Some(ranges) =
 6488                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6489                    {
 6490                        for (buffer, entries) in ranges {
 6491                            linked_ranges.entry(buffer).or_default().extend(entries);
 6492                        }
 6493                    }
 6494                }
 6495            }
 6496
 6497            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6498            if !this.selections.line_mode {
 6499                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6500                for selection in &mut selections {
 6501                    if selection.is_empty() {
 6502                        let old_head = selection.head();
 6503                        let mut new_head =
 6504                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6505                                .to_point(&display_map);
 6506                        if let Some((buffer, line_buffer_range)) = display_map
 6507                            .buffer_snapshot
 6508                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6509                        {
 6510                            let indent_size =
 6511                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6512                            let indent_len = match indent_size.kind {
 6513                                IndentKind::Space => {
 6514                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6515                                }
 6516                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6517                            };
 6518                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6519                                let indent_len = indent_len.get();
 6520                                new_head = cmp::min(
 6521                                    new_head,
 6522                                    MultiBufferPoint::new(
 6523                                        old_head.row,
 6524                                        ((old_head.column - 1) / indent_len) * indent_len,
 6525                                    ),
 6526                                );
 6527                            }
 6528                        }
 6529
 6530                        selection.set_head(new_head, SelectionGoal::None);
 6531                    }
 6532                }
 6533            }
 6534
 6535            this.signature_help_state.set_backspace_pressed(true);
 6536            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6537                s.select(selections)
 6538            });
 6539            this.insert("", window, cx);
 6540            let empty_str: Arc<str> = Arc::from("");
 6541            for (buffer, edits) in linked_ranges {
 6542                let snapshot = buffer.read(cx).snapshot();
 6543                use text::ToPoint as TP;
 6544
 6545                let edits = edits
 6546                    .into_iter()
 6547                    .map(|range| {
 6548                        let end_point = TP::to_point(&range.end, &snapshot);
 6549                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6550
 6551                        if end_point == start_point {
 6552                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6553                                .saturating_sub(1);
 6554                            start_point =
 6555                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6556                        };
 6557
 6558                        (start_point..end_point, empty_str.clone())
 6559                    })
 6560                    .sorted_by_key(|(range, _)| range.start)
 6561                    .collect::<Vec<_>>();
 6562                buffer.update(cx, |this, cx| {
 6563                    this.edit(edits, None, cx);
 6564                })
 6565            }
 6566            this.refresh_inline_completion(true, false, window, cx);
 6567            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6568        });
 6569    }
 6570
 6571    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6572        self.transact(window, cx, |this, window, cx| {
 6573            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6574                let line_mode = s.line_mode;
 6575                s.move_with(|map, selection| {
 6576                    if selection.is_empty() && !line_mode {
 6577                        let cursor = movement::right(map, selection.head());
 6578                        selection.end = cursor;
 6579                        selection.reversed = true;
 6580                        selection.goal = SelectionGoal::None;
 6581                    }
 6582                })
 6583            });
 6584            this.insert("", window, cx);
 6585            this.refresh_inline_completion(true, false, window, cx);
 6586        });
 6587    }
 6588
 6589    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6590        if self.move_to_prev_snippet_tabstop(window, cx) {
 6591            return;
 6592        }
 6593
 6594        self.outdent(&Outdent, window, cx);
 6595    }
 6596
 6597    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6598        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6599            return;
 6600        }
 6601
 6602        let mut selections = self.selections.all_adjusted(cx);
 6603        let buffer = self.buffer.read(cx);
 6604        let snapshot = buffer.snapshot(cx);
 6605        let rows_iter = selections.iter().map(|s| s.head().row);
 6606        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6607
 6608        let mut edits = Vec::new();
 6609        let mut prev_edited_row = 0;
 6610        let mut row_delta = 0;
 6611        for selection in &mut selections {
 6612            if selection.start.row != prev_edited_row {
 6613                row_delta = 0;
 6614            }
 6615            prev_edited_row = selection.end.row;
 6616
 6617            // If the selection is non-empty, then increase the indentation of the selected lines.
 6618            if !selection.is_empty() {
 6619                row_delta =
 6620                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6621                continue;
 6622            }
 6623
 6624            // If the selection is empty and the cursor is in the leading whitespace before the
 6625            // suggested indentation, then auto-indent the line.
 6626            let cursor = selection.head();
 6627            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6628            if let Some(suggested_indent) =
 6629                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6630            {
 6631                if cursor.column < suggested_indent.len
 6632                    && cursor.column <= current_indent.len
 6633                    && current_indent.len <= suggested_indent.len
 6634                {
 6635                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6636                    selection.end = selection.start;
 6637                    if row_delta == 0 {
 6638                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6639                            cursor.row,
 6640                            current_indent,
 6641                            suggested_indent,
 6642                        ));
 6643                        row_delta = suggested_indent.len - current_indent.len;
 6644                    }
 6645                    continue;
 6646                }
 6647            }
 6648
 6649            // Otherwise, insert a hard or soft tab.
 6650            let settings = buffer.settings_at(cursor, cx);
 6651            let tab_size = if settings.hard_tabs {
 6652                IndentSize::tab()
 6653            } else {
 6654                let tab_size = settings.tab_size.get();
 6655                let char_column = snapshot
 6656                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6657                    .flat_map(str::chars)
 6658                    .count()
 6659                    + row_delta as usize;
 6660                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6661                IndentSize::spaces(chars_to_next_tab_stop)
 6662            };
 6663            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6664            selection.end = selection.start;
 6665            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6666            row_delta += tab_size.len;
 6667        }
 6668
 6669        self.transact(window, cx, |this, window, cx| {
 6670            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6671            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6672                s.select(selections)
 6673            });
 6674            this.refresh_inline_completion(true, false, window, cx);
 6675        });
 6676    }
 6677
 6678    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6679        if self.read_only(cx) {
 6680            return;
 6681        }
 6682        let mut selections = self.selections.all::<Point>(cx);
 6683        let mut prev_edited_row = 0;
 6684        let mut row_delta = 0;
 6685        let mut edits = Vec::new();
 6686        let buffer = self.buffer.read(cx);
 6687        let snapshot = buffer.snapshot(cx);
 6688        for selection in &mut selections {
 6689            if selection.start.row != prev_edited_row {
 6690                row_delta = 0;
 6691            }
 6692            prev_edited_row = selection.end.row;
 6693
 6694            row_delta =
 6695                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6696        }
 6697
 6698        self.transact(window, cx, |this, window, cx| {
 6699            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6700            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6701                s.select(selections)
 6702            });
 6703        });
 6704    }
 6705
 6706    fn indent_selection(
 6707        buffer: &MultiBuffer,
 6708        snapshot: &MultiBufferSnapshot,
 6709        selection: &mut Selection<Point>,
 6710        edits: &mut Vec<(Range<Point>, String)>,
 6711        delta_for_start_row: u32,
 6712        cx: &App,
 6713    ) -> u32 {
 6714        let settings = buffer.settings_at(selection.start, cx);
 6715        let tab_size = settings.tab_size.get();
 6716        let indent_kind = if settings.hard_tabs {
 6717            IndentKind::Tab
 6718        } else {
 6719            IndentKind::Space
 6720        };
 6721        let mut start_row = selection.start.row;
 6722        let mut end_row = selection.end.row + 1;
 6723
 6724        // If a selection ends at the beginning of a line, don't indent
 6725        // that last line.
 6726        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6727            end_row -= 1;
 6728        }
 6729
 6730        // Avoid re-indenting a row that has already been indented by a
 6731        // previous selection, but still update this selection's column
 6732        // to reflect that indentation.
 6733        if delta_for_start_row > 0 {
 6734            start_row += 1;
 6735            selection.start.column += delta_for_start_row;
 6736            if selection.end.row == selection.start.row {
 6737                selection.end.column += delta_for_start_row;
 6738            }
 6739        }
 6740
 6741        let mut delta_for_end_row = 0;
 6742        let has_multiple_rows = start_row + 1 != end_row;
 6743        for row in start_row..end_row {
 6744            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6745            let indent_delta = match (current_indent.kind, indent_kind) {
 6746                (IndentKind::Space, IndentKind::Space) => {
 6747                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6748                    IndentSize::spaces(columns_to_next_tab_stop)
 6749                }
 6750                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6751                (_, IndentKind::Tab) => IndentSize::tab(),
 6752            };
 6753
 6754            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6755                0
 6756            } else {
 6757                selection.start.column
 6758            };
 6759            let row_start = Point::new(row, start);
 6760            edits.push((
 6761                row_start..row_start,
 6762                indent_delta.chars().collect::<String>(),
 6763            ));
 6764
 6765            // Update this selection's endpoints to reflect the indentation.
 6766            if row == selection.start.row {
 6767                selection.start.column += indent_delta.len;
 6768            }
 6769            if row == selection.end.row {
 6770                selection.end.column += indent_delta.len;
 6771                delta_for_end_row = indent_delta.len;
 6772            }
 6773        }
 6774
 6775        if selection.start.row == selection.end.row {
 6776            delta_for_start_row + delta_for_end_row
 6777        } else {
 6778            delta_for_end_row
 6779        }
 6780    }
 6781
 6782    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6783        if self.read_only(cx) {
 6784            return;
 6785        }
 6786        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6787        let selections = self.selections.all::<Point>(cx);
 6788        let mut deletion_ranges = Vec::new();
 6789        let mut last_outdent = None;
 6790        {
 6791            let buffer = self.buffer.read(cx);
 6792            let snapshot = buffer.snapshot(cx);
 6793            for selection in &selections {
 6794                let settings = buffer.settings_at(selection.start, cx);
 6795                let tab_size = settings.tab_size.get();
 6796                let mut rows = selection.spanned_rows(false, &display_map);
 6797
 6798                // Avoid re-outdenting a row that has already been outdented by a
 6799                // previous selection.
 6800                if let Some(last_row) = last_outdent {
 6801                    if last_row == rows.start {
 6802                        rows.start = rows.start.next_row();
 6803                    }
 6804                }
 6805                let has_multiple_rows = rows.len() > 1;
 6806                for row in rows.iter_rows() {
 6807                    let indent_size = snapshot.indent_size_for_line(row);
 6808                    if indent_size.len > 0 {
 6809                        let deletion_len = match indent_size.kind {
 6810                            IndentKind::Space => {
 6811                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6812                                if columns_to_prev_tab_stop == 0 {
 6813                                    tab_size
 6814                                } else {
 6815                                    columns_to_prev_tab_stop
 6816                                }
 6817                            }
 6818                            IndentKind::Tab => 1,
 6819                        };
 6820                        let start = if has_multiple_rows
 6821                            || deletion_len > selection.start.column
 6822                            || indent_size.len < selection.start.column
 6823                        {
 6824                            0
 6825                        } else {
 6826                            selection.start.column - deletion_len
 6827                        };
 6828                        deletion_ranges.push(
 6829                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6830                        );
 6831                        last_outdent = Some(row);
 6832                    }
 6833                }
 6834            }
 6835        }
 6836
 6837        self.transact(window, cx, |this, window, cx| {
 6838            this.buffer.update(cx, |buffer, cx| {
 6839                let empty_str: Arc<str> = Arc::default();
 6840                buffer.edit(
 6841                    deletion_ranges
 6842                        .into_iter()
 6843                        .map(|range| (range, empty_str.clone())),
 6844                    None,
 6845                    cx,
 6846                );
 6847            });
 6848            let selections = this.selections.all::<usize>(cx);
 6849            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6850                s.select(selections)
 6851            });
 6852        });
 6853    }
 6854
 6855    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6856        if self.read_only(cx) {
 6857            return;
 6858        }
 6859        let selections = self
 6860            .selections
 6861            .all::<usize>(cx)
 6862            .into_iter()
 6863            .map(|s| s.range());
 6864
 6865        self.transact(window, cx, |this, window, cx| {
 6866            this.buffer.update(cx, |buffer, cx| {
 6867                buffer.autoindent_ranges(selections, cx);
 6868            });
 6869            let selections = this.selections.all::<usize>(cx);
 6870            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6871                s.select(selections)
 6872            });
 6873        });
 6874    }
 6875
 6876    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6877        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6878        let selections = self.selections.all::<Point>(cx);
 6879
 6880        let mut new_cursors = Vec::new();
 6881        let mut edit_ranges = Vec::new();
 6882        let mut selections = selections.iter().peekable();
 6883        while let Some(selection) = selections.next() {
 6884            let mut rows = selection.spanned_rows(false, &display_map);
 6885            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6886
 6887            // Accumulate contiguous regions of rows that we want to delete.
 6888            while let Some(next_selection) = selections.peek() {
 6889                let next_rows = next_selection.spanned_rows(false, &display_map);
 6890                if next_rows.start <= rows.end {
 6891                    rows.end = next_rows.end;
 6892                    selections.next().unwrap();
 6893                } else {
 6894                    break;
 6895                }
 6896            }
 6897
 6898            let buffer = &display_map.buffer_snapshot;
 6899            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6900            let edit_end;
 6901            let cursor_buffer_row;
 6902            if buffer.max_point().row >= rows.end.0 {
 6903                // If there's a line after the range, delete the \n from the end of the row range
 6904                // and position the cursor on the next line.
 6905                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6906                cursor_buffer_row = rows.end;
 6907            } else {
 6908                // If there isn't a line after the range, delete the \n from the line before the
 6909                // start of the row range and position the cursor there.
 6910                edit_start = edit_start.saturating_sub(1);
 6911                edit_end = buffer.len();
 6912                cursor_buffer_row = rows.start.previous_row();
 6913            }
 6914
 6915            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6916            *cursor.column_mut() =
 6917                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6918
 6919            new_cursors.push((
 6920                selection.id,
 6921                buffer.anchor_after(cursor.to_point(&display_map)),
 6922            ));
 6923            edit_ranges.push(edit_start..edit_end);
 6924        }
 6925
 6926        self.transact(window, cx, |this, window, cx| {
 6927            let buffer = this.buffer.update(cx, |buffer, cx| {
 6928                let empty_str: Arc<str> = Arc::default();
 6929                buffer.edit(
 6930                    edit_ranges
 6931                        .into_iter()
 6932                        .map(|range| (range, empty_str.clone())),
 6933                    None,
 6934                    cx,
 6935                );
 6936                buffer.snapshot(cx)
 6937            });
 6938            let new_selections = new_cursors
 6939                .into_iter()
 6940                .map(|(id, cursor)| {
 6941                    let cursor = cursor.to_point(&buffer);
 6942                    Selection {
 6943                        id,
 6944                        start: cursor,
 6945                        end: cursor,
 6946                        reversed: false,
 6947                        goal: SelectionGoal::None,
 6948                    }
 6949                })
 6950                .collect();
 6951
 6952            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6953                s.select(new_selections);
 6954            });
 6955        });
 6956    }
 6957
 6958    pub fn join_lines_impl(
 6959        &mut self,
 6960        insert_whitespace: bool,
 6961        window: &mut Window,
 6962        cx: &mut Context<Self>,
 6963    ) {
 6964        if self.read_only(cx) {
 6965            return;
 6966        }
 6967        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6968        for selection in self.selections.all::<Point>(cx) {
 6969            let start = MultiBufferRow(selection.start.row);
 6970            // Treat single line selections as if they include the next line. Otherwise this action
 6971            // would do nothing for single line selections individual cursors.
 6972            let end = if selection.start.row == selection.end.row {
 6973                MultiBufferRow(selection.start.row + 1)
 6974            } else {
 6975                MultiBufferRow(selection.end.row)
 6976            };
 6977
 6978            if let Some(last_row_range) = row_ranges.last_mut() {
 6979                if start <= last_row_range.end {
 6980                    last_row_range.end = end;
 6981                    continue;
 6982                }
 6983            }
 6984            row_ranges.push(start..end);
 6985        }
 6986
 6987        let snapshot = self.buffer.read(cx).snapshot(cx);
 6988        let mut cursor_positions = Vec::new();
 6989        for row_range in &row_ranges {
 6990            let anchor = snapshot.anchor_before(Point::new(
 6991                row_range.end.previous_row().0,
 6992                snapshot.line_len(row_range.end.previous_row()),
 6993            ));
 6994            cursor_positions.push(anchor..anchor);
 6995        }
 6996
 6997        self.transact(window, cx, |this, window, cx| {
 6998            for row_range in row_ranges.into_iter().rev() {
 6999                for row in row_range.iter_rows().rev() {
 7000                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7001                    let next_line_row = row.next_row();
 7002                    let indent = snapshot.indent_size_for_line(next_line_row);
 7003                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7004
 7005                    let replace =
 7006                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7007                            " "
 7008                        } else {
 7009                            ""
 7010                        };
 7011
 7012                    this.buffer.update(cx, |buffer, cx| {
 7013                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7014                    });
 7015                }
 7016            }
 7017
 7018            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7019                s.select_anchor_ranges(cursor_positions)
 7020            });
 7021        });
 7022    }
 7023
 7024    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7025        self.join_lines_impl(true, window, cx);
 7026    }
 7027
 7028    pub fn sort_lines_case_sensitive(
 7029        &mut self,
 7030        _: &SortLinesCaseSensitive,
 7031        window: &mut Window,
 7032        cx: &mut Context<Self>,
 7033    ) {
 7034        self.manipulate_lines(window, cx, |lines| lines.sort())
 7035    }
 7036
 7037    pub fn sort_lines_case_insensitive(
 7038        &mut self,
 7039        _: &SortLinesCaseInsensitive,
 7040        window: &mut Window,
 7041        cx: &mut Context<Self>,
 7042    ) {
 7043        self.manipulate_lines(window, cx, |lines| {
 7044            lines.sort_by_key(|line| line.to_lowercase())
 7045        })
 7046    }
 7047
 7048    pub fn unique_lines_case_insensitive(
 7049        &mut self,
 7050        _: &UniqueLinesCaseInsensitive,
 7051        window: &mut Window,
 7052        cx: &mut Context<Self>,
 7053    ) {
 7054        self.manipulate_lines(window, cx, |lines| {
 7055            let mut seen = HashSet::default();
 7056            lines.retain(|line| seen.insert(line.to_lowercase()));
 7057        })
 7058    }
 7059
 7060    pub fn unique_lines_case_sensitive(
 7061        &mut self,
 7062        _: &UniqueLinesCaseSensitive,
 7063        window: &mut Window,
 7064        cx: &mut Context<Self>,
 7065    ) {
 7066        self.manipulate_lines(window, cx, |lines| {
 7067            let mut seen = HashSet::default();
 7068            lines.retain(|line| seen.insert(*line));
 7069        })
 7070    }
 7071
 7072    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 7073        let mut revert_changes = HashMap::default();
 7074        let snapshot = self.snapshot(window, cx);
 7075        for hunk in snapshot
 7076            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 7077        {
 7078            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7079        }
 7080        if !revert_changes.is_empty() {
 7081            self.transact(window, cx, |editor, window, cx| {
 7082                editor.revert(revert_changes, window, cx);
 7083            });
 7084        }
 7085    }
 7086
 7087    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7088        let Some(project) = self.project.clone() else {
 7089            return;
 7090        };
 7091        self.reload(project, window, cx)
 7092            .detach_and_notify_err(window, cx);
 7093    }
 7094
 7095    pub fn revert_selected_hunks(
 7096        &mut self,
 7097        _: &RevertSelectedHunks,
 7098        window: &mut Window,
 7099        cx: &mut Context<Self>,
 7100    ) {
 7101        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 7102        self.discard_hunks_in_ranges(selections, window, cx);
 7103    }
 7104
 7105    fn discard_hunks_in_ranges(
 7106        &mut self,
 7107        ranges: impl Iterator<Item = Range<Point>>,
 7108        window: &mut Window,
 7109        cx: &mut Context<Editor>,
 7110    ) {
 7111        let mut revert_changes = HashMap::default();
 7112        let snapshot = self.snapshot(window, cx);
 7113        for hunk in &snapshot.hunks_for_ranges(ranges) {
 7114            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7115        }
 7116        if !revert_changes.is_empty() {
 7117            self.transact(window, cx, |editor, window, cx| {
 7118                editor.revert(revert_changes, window, cx);
 7119            });
 7120        }
 7121    }
 7122
 7123    pub fn open_active_item_in_terminal(
 7124        &mut self,
 7125        _: &OpenInTerminal,
 7126        window: &mut Window,
 7127        cx: &mut Context<Self>,
 7128    ) {
 7129        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7130            let project_path = buffer.read(cx).project_path(cx)?;
 7131            let project = self.project.as_ref()?.read(cx);
 7132            let entry = project.entry_for_path(&project_path, cx)?;
 7133            let parent = match &entry.canonical_path {
 7134                Some(canonical_path) => canonical_path.to_path_buf(),
 7135                None => project.absolute_path(&project_path, cx)?,
 7136            }
 7137            .parent()?
 7138            .to_path_buf();
 7139            Some(parent)
 7140        }) {
 7141            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7142        }
 7143    }
 7144
 7145    pub fn prepare_revert_change(
 7146        &self,
 7147        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7148        hunk: &MultiBufferDiffHunk,
 7149        cx: &mut App,
 7150    ) -> Option<()> {
 7151        let buffer = self.buffer.read(cx);
 7152        let diff = buffer.diff_for(hunk.buffer_id)?;
 7153        let buffer = buffer.buffer(hunk.buffer_id)?;
 7154        let buffer = buffer.read(cx);
 7155        let original_text = diff
 7156            .read(cx)
 7157            .base_text()
 7158            .as_ref()?
 7159            .as_rope()
 7160            .slice(hunk.diff_base_byte_range.clone());
 7161        let buffer_snapshot = buffer.snapshot();
 7162        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7163        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7164            probe
 7165                .0
 7166                .start
 7167                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7168                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7169        }) {
 7170            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7171            Some(())
 7172        } else {
 7173            None
 7174        }
 7175    }
 7176
 7177    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7178        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7179    }
 7180
 7181    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7182        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7183    }
 7184
 7185    fn manipulate_lines<Fn>(
 7186        &mut self,
 7187        window: &mut Window,
 7188        cx: &mut Context<Self>,
 7189        mut callback: Fn,
 7190    ) where
 7191        Fn: FnMut(&mut Vec<&str>),
 7192    {
 7193        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7194        let buffer = self.buffer.read(cx).snapshot(cx);
 7195
 7196        let mut edits = Vec::new();
 7197
 7198        let selections = self.selections.all::<Point>(cx);
 7199        let mut selections = selections.iter().peekable();
 7200        let mut contiguous_row_selections = Vec::new();
 7201        let mut new_selections = Vec::new();
 7202        let mut added_lines = 0;
 7203        let mut removed_lines = 0;
 7204
 7205        while let Some(selection) = selections.next() {
 7206            let (start_row, end_row) = consume_contiguous_rows(
 7207                &mut contiguous_row_selections,
 7208                selection,
 7209                &display_map,
 7210                &mut selections,
 7211            );
 7212
 7213            let start_point = Point::new(start_row.0, 0);
 7214            let end_point = Point::new(
 7215                end_row.previous_row().0,
 7216                buffer.line_len(end_row.previous_row()),
 7217            );
 7218            let text = buffer
 7219                .text_for_range(start_point..end_point)
 7220                .collect::<String>();
 7221
 7222            let mut lines = text.split('\n').collect_vec();
 7223
 7224            let lines_before = lines.len();
 7225            callback(&mut lines);
 7226            let lines_after = lines.len();
 7227
 7228            edits.push((start_point..end_point, lines.join("\n")));
 7229
 7230            // Selections must change based on added and removed line count
 7231            let start_row =
 7232                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7233            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7234            new_selections.push(Selection {
 7235                id: selection.id,
 7236                start: start_row,
 7237                end: end_row,
 7238                goal: SelectionGoal::None,
 7239                reversed: selection.reversed,
 7240            });
 7241
 7242            if lines_after > lines_before {
 7243                added_lines += lines_after - lines_before;
 7244            } else if lines_before > lines_after {
 7245                removed_lines += lines_before - lines_after;
 7246            }
 7247        }
 7248
 7249        self.transact(window, cx, |this, window, cx| {
 7250            let buffer = this.buffer.update(cx, |buffer, cx| {
 7251                buffer.edit(edits, None, cx);
 7252                buffer.snapshot(cx)
 7253            });
 7254
 7255            // Recalculate offsets on newly edited buffer
 7256            let new_selections = new_selections
 7257                .iter()
 7258                .map(|s| {
 7259                    let start_point = Point::new(s.start.0, 0);
 7260                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7261                    Selection {
 7262                        id: s.id,
 7263                        start: buffer.point_to_offset(start_point),
 7264                        end: buffer.point_to_offset(end_point),
 7265                        goal: s.goal,
 7266                        reversed: s.reversed,
 7267                    }
 7268                })
 7269                .collect();
 7270
 7271            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7272                s.select(new_selections);
 7273            });
 7274
 7275            this.request_autoscroll(Autoscroll::fit(), cx);
 7276        });
 7277    }
 7278
 7279    pub fn convert_to_upper_case(
 7280        &mut self,
 7281        _: &ConvertToUpperCase,
 7282        window: &mut Window,
 7283        cx: &mut Context<Self>,
 7284    ) {
 7285        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7286    }
 7287
 7288    pub fn convert_to_lower_case(
 7289        &mut self,
 7290        _: &ConvertToLowerCase,
 7291        window: &mut Window,
 7292        cx: &mut Context<Self>,
 7293    ) {
 7294        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7295    }
 7296
 7297    pub fn convert_to_title_case(
 7298        &mut self,
 7299        _: &ConvertToTitleCase,
 7300        window: &mut Window,
 7301        cx: &mut Context<Self>,
 7302    ) {
 7303        self.manipulate_text(window, cx, |text| {
 7304            text.split('\n')
 7305                .map(|line| line.to_case(Case::Title))
 7306                .join("\n")
 7307        })
 7308    }
 7309
 7310    pub fn convert_to_snake_case(
 7311        &mut self,
 7312        _: &ConvertToSnakeCase,
 7313        window: &mut Window,
 7314        cx: &mut Context<Self>,
 7315    ) {
 7316        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7317    }
 7318
 7319    pub fn convert_to_kebab_case(
 7320        &mut self,
 7321        _: &ConvertToKebabCase,
 7322        window: &mut Window,
 7323        cx: &mut Context<Self>,
 7324    ) {
 7325        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7326    }
 7327
 7328    pub fn convert_to_upper_camel_case(
 7329        &mut self,
 7330        _: &ConvertToUpperCamelCase,
 7331        window: &mut Window,
 7332        cx: &mut Context<Self>,
 7333    ) {
 7334        self.manipulate_text(window, cx, |text| {
 7335            text.split('\n')
 7336                .map(|line| line.to_case(Case::UpperCamel))
 7337                .join("\n")
 7338        })
 7339    }
 7340
 7341    pub fn convert_to_lower_camel_case(
 7342        &mut self,
 7343        _: &ConvertToLowerCamelCase,
 7344        window: &mut Window,
 7345        cx: &mut Context<Self>,
 7346    ) {
 7347        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7348    }
 7349
 7350    pub fn convert_to_opposite_case(
 7351        &mut self,
 7352        _: &ConvertToOppositeCase,
 7353        window: &mut Window,
 7354        cx: &mut Context<Self>,
 7355    ) {
 7356        self.manipulate_text(window, cx, |text| {
 7357            text.chars()
 7358                .fold(String::with_capacity(text.len()), |mut t, c| {
 7359                    if c.is_uppercase() {
 7360                        t.extend(c.to_lowercase());
 7361                    } else {
 7362                        t.extend(c.to_uppercase());
 7363                    }
 7364                    t
 7365                })
 7366        })
 7367    }
 7368
 7369    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7370    where
 7371        Fn: FnMut(&str) -> String,
 7372    {
 7373        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7374        let buffer = self.buffer.read(cx).snapshot(cx);
 7375
 7376        let mut new_selections = Vec::new();
 7377        let mut edits = Vec::new();
 7378        let mut selection_adjustment = 0i32;
 7379
 7380        for selection in self.selections.all::<usize>(cx) {
 7381            let selection_is_empty = selection.is_empty();
 7382
 7383            let (start, end) = if selection_is_empty {
 7384                let word_range = movement::surrounding_word(
 7385                    &display_map,
 7386                    selection.start.to_display_point(&display_map),
 7387                );
 7388                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7389                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7390                (start, end)
 7391            } else {
 7392                (selection.start, selection.end)
 7393            };
 7394
 7395            let text = buffer.text_for_range(start..end).collect::<String>();
 7396            let old_length = text.len() as i32;
 7397            let text = callback(&text);
 7398
 7399            new_selections.push(Selection {
 7400                start: (start as i32 - selection_adjustment) as usize,
 7401                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7402                goal: SelectionGoal::None,
 7403                ..selection
 7404            });
 7405
 7406            selection_adjustment += old_length - text.len() as i32;
 7407
 7408            edits.push((start..end, text));
 7409        }
 7410
 7411        self.transact(window, cx, |this, window, cx| {
 7412            this.buffer.update(cx, |buffer, cx| {
 7413                buffer.edit(edits, None, cx);
 7414            });
 7415
 7416            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7417                s.select(new_selections);
 7418            });
 7419
 7420            this.request_autoscroll(Autoscroll::fit(), cx);
 7421        });
 7422    }
 7423
 7424    pub fn duplicate(
 7425        &mut self,
 7426        upwards: bool,
 7427        whole_lines: bool,
 7428        window: &mut Window,
 7429        cx: &mut Context<Self>,
 7430    ) {
 7431        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7432        let buffer = &display_map.buffer_snapshot;
 7433        let selections = self.selections.all::<Point>(cx);
 7434
 7435        let mut edits = Vec::new();
 7436        let mut selections_iter = selections.iter().peekable();
 7437        while let Some(selection) = selections_iter.next() {
 7438            let mut rows = selection.spanned_rows(false, &display_map);
 7439            // duplicate line-wise
 7440            if whole_lines || selection.start == selection.end {
 7441                // Avoid duplicating the same lines twice.
 7442                while let Some(next_selection) = selections_iter.peek() {
 7443                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7444                    if next_rows.start < rows.end {
 7445                        rows.end = next_rows.end;
 7446                        selections_iter.next().unwrap();
 7447                    } else {
 7448                        break;
 7449                    }
 7450                }
 7451
 7452                // Copy the text from the selected row region and splice it either at the start
 7453                // or end of the region.
 7454                let start = Point::new(rows.start.0, 0);
 7455                let end = Point::new(
 7456                    rows.end.previous_row().0,
 7457                    buffer.line_len(rows.end.previous_row()),
 7458                );
 7459                let text = buffer
 7460                    .text_for_range(start..end)
 7461                    .chain(Some("\n"))
 7462                    .collect::<String>();
 7463                let insert_location = if upwards {
 7464                    Point::new(rows.end.0, 0)
 7465                } else {
 7466                    start
 7467                };
 7468                edits.push((insert_location..insert_location, text));
 7469            } else {
 7470                // duplicate character-wise
 7471                let start = selection.start;
 7472                let end = selection.end;
 7473                let text = buffer.text_for_range(start..end).collect::<String>();
 7474                edits.push((selection.end..selection.end, text));
 7475            }
 7476        }
 7477
 7478        self.transact(window, cx, |this, _, cx| {
 7479            this.buffer.update(cx, |buffer, cx| {
 7480                buffer.edit(edits, None, cx);
 7481            });
 7482
 7483            this.request_autoscroll(Autoscroll::fit(), cx);
 7484        });
 7485    }
 7486
 7487    pub fn duplicate_line_up(
 7488        &mut self,
 7489        _: &DuplicateLineUp,
 7490        window: &mut Window,
 7491        cx: &mut Context<Self>,
 7492    ) {
 7493        self.duplicate(true, true, window, cx);
 7494    }
 7495
 7496    pub fn duplicate_line_down(
 7497        &mut self,
 7498        _: &DuplicateLineDown,
 7499        window: &mut Window,
 7500        cx: &mut Context<Self>,
 7501    ) {
 7502        self.duplicate(false, true, window, cx);
 7503    }
 7504
 7505    pub fn duplicate_selection(
 7506        &mut self,
 7507        _: &DuplicateSelection,
 7508        window: &mut Window,
 7509        cx: &mut Context<Self>,
 7510    ) {
 7511        self.duplicate(false, false, window, cx);
 7512    }
 7513
 7514    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7515        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7516        let buffer = self.buffer.read(cx).snapshot(cx);
 7517
 7518        let mut edits = Vec::new();
 7519        let mut unfold_ranges = Vec::new();
 7520        let mut refold_creases = Vec::new();
 7521
 7522        let selections = self.selections.all::<Point>(cx);
 7523        let mut selections = selections.iter().peekable();
 7524        let mut contiguous_row_selections = Vec::new();
 7525        let mut new_selections = Vec::new();
 7526
 7527        while let Some(selection) = selections.next() {
 7528            // Find all the selections that span a contiguous row range
 7529            let (start_row, end_row) = consume_contiguous_rows(
 7530                &mut contiguous_row_selections,
 7531                selection,
 7532                &display_map,
 7533                &mut selections,
 7534            );
 7535
 7536            // Move the text spanned by the row range to be before the line preceding the row range
 7537            if start_row.0 > 0 {
 7538                let range_to_move = Point::new(
 7539                    start_row.previous_row().0,
 7540                    buffer.line_len(start_row.previous_row()),
 7541                )
 7542                    ..Point::new(
 7543                        end_row.previous_row().0,
 7544                        buffer.line_len(end_row.previous_row()),
 7545                    );
 7546                let insertion_point = display_map
 7547                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7548                    .0;
 7549
 7550                // Don't move lines across excerpts
 7551                if buffer
 7552                    .excerpt_containing(insertion_point..range_to_move.end)
 7553                    .is_some()
 7554                {
 7555                    let text = buffer
 7556                        .text_for_range(range_to_move.clone())
 7557                        .flat_map(|s| s.chars())
 7558                        .skip(1)
 7559                        .chain(['\n'])
 7560                        .collect::<String>();
 7561
 7562                    edits.push((
 7563                        buffer.anchor_after(range_to_move.start)
 7564                            ..buffer.anchor_before(range_to_move.end),
 7565                        String::new(),
 7566                    ));
 7567                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7568                    edits.push((insertion_anchor..insertion_anchor, text));
 7569
 7570                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7571
 7572                    // Move selections up
 7573                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7574                        |mut selection| {
 7575                            selection.start.row -= row_delta;
 7576                            selection.end.row -= row_delta;
 7577                            selection
 7578                        },
 7579                    ));
 7580
 7581                    // Move folds up
 7582                    unfold_ranges.push(range_to_move.clone());
 7583                    for fold in display_map.folds_in_range(
 7584                        buffer.anchor_before(range_to_move.start)
 7585                            ..buffer.anchor_after(range_to_move.end),
 7586                    ) {
 7587                        let mut start = fold.range.start.to_point(&buffer);
 7588                        let mut end = fold.range.end.to_point(&buffer);
 7589                        start.row -= row_delta;
 7590                        end.row -= row_delta;
 7591                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7592                    }
 7593                }
 7594            }
 7595
 7596            // If we didn't move line(s), preserve the existing selections
 7597            new_selections.append(&mut contiguous_row_selections);
 7598        }
 7599
 7600        self.transact(window, cx, |this, window, cx| {
 7601            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7602            this.buffer.update(cx, |buffer, cx| {
 7603                for (range, text) in edits {
 7604                    buffer.edit([(range, text)], None, cx);
 7605                }
 7606            });
 7607            this.fold_creases(refold_creases, true, window, cx);
 7608            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7609                s.select(new_selections);
 7610            })
 7611        });
 7612    }
 7613
 7614    pub fn move_line_down(
 7615        &mut self,
 7616        _: &MoveLineDown,
 7617        window: &mut Window,
 7618        cx: &mut Context<Self>,
 7619    ) {
 7620        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7621        let buffer = self.buffer.read(cx).snapshot(cx);
 7622
 7623        let mut edits = Vec::new();
 7624        let mut unfold_ranges = Vec::new();
 7625        let mut refold_creases = Vec::new();
 7626
 7627        let selections = self.selections.all::<Point>(cx);
 7628        let mut selections = selections.iter().peekable();
 7629        let mut contiguous_row_selections = Vec::new();
 7630        let mut new_selections = Vec::new();
 7631
 7632        while let Some(selection) = selections.next() {
 7633            // Find all the selections that span a contiguous row range
 7634            let (start_row, end_row) = consume_contiguous_rows(
 7635                &mut contiguous_row_selections,
 7636                selection,
 7637                &display_map,
 7638                &mut selections,
 7639            );
 7640
 7641            // Move the text spanned by the row range to be after the last line of the row range
 7642            if end_row.0 <= buffer.max_point().row {
 7643                let range_to_move =
 7644                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7645                let insertion_point = display_map
 7646                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7647                    .0;
 7648
 7649                // Don't move lines across excerpt boundaries
 7650                if buffer
 7651                    .excerpt_containing(range_to_move.start..insertion_point)
 7652                    .is_some()
 7653                {
 7654                    let mut text = String::from("\n");
 7655                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7656                    text.pop(); // Drop trailing newline
 7657                    edits.push((
 7658                        buffer.anchor_after(range_to_move.start)
 7659                            ..buffer.anchor_before(range_to_move.end),
 7660                        String::new(),
 7661                    ));
 7662                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7663                    edits.push((insertion_anchor..insertion_anchor, text));
 7664
 7665                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7666
 7667                    // Move selections down
 7668                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7669                        |mut selection| {
 7670                            selection.start.row += row_delta;
 7671                            selection.end.row += row_delta;
 7672                            selection
 7673                        },
 7674                    ));
 7675
 7676                    // Move folds down
 7677                    unfold_ranges.push(range_to_move.clone());
 7678                    for fold in display_map.folds_in_range(
 7679                        buffer.anchor_before(range_to_move.start)
 7680                            ..buffer.anchor_after(range_to_move.end),
 7681                    ) {
 7682                        let mut start = fold.range.start.to_point(&buffer);
 7683                        let mut end = fold.range.end.to_point(&buffer);
 7684                        start.row += row_delta;
 7685                        end.row += row_delta;
 7686                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7687                    }
 7688                }
 7689            }
 7690
 7691            // If we didn't move line(s), preserve the existing selections
 7692            new_selections.append(&mut contiguous_row_selections);
 7693        }
 7694
 7695        self.transact(window, cx, |this, window, cx| {
 7696            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7697            this.buffer.update(cx, |buffer, cx| {
 7698                for (range, text) in edits {
 7699                    buffer.edit([(range, text)], None, cx);
 7700                }
 7701            });
 7702            this.fold_creases(refold_creases, true, window, cx);
 7703            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7704                s.select(new_selections)
 7705            });
 7706        });
 7707    }
 7708
 7709    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7710        let text_layout_details = &self.text_layout_details(window);
 7711        self.transact(window, cx, |this, window, cx| {
 7712            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7713                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7714                let line_mode = s.line_mode;
 7715                s.move_with(|display_map, selection| {
 7716                    if !selection.is_empty() || line_mode {
 7717                        return;
 7718                    }
 7719
 7720                    let mut head = selection.head();
 7721                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7722                    if head.column() == display_map.line_len(head.row()) {
 7723                        transpose_offset = display_map
 7724                            .buffer_snapshot
 7725                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7726                    }
 7727
 7728                    if transpose_offset == 0 {
 7729                        return;
 7730                    }
 7731
 7732                    *head.column_mut() += 1;
 7733                    head = display_map.clip_point(head, Bias::Right);
 7734                    let goal = SelectionGoal::HorizontalPosition(
 7735                        display_map
 7736                            .x_for_display_point(head, text_layout_details)
 7737                            .into(),
 7738                    );
 7739                    selection.collapse_to(head, goal);
 7740
 7741                    let transpose_start = display_map
 7742                        .buffer_snapshot
 7743                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7744                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7745                        let transpose_end = display_map
 7746                            .buffer_snapshot
 7747                            .clip_offset(transpose_offset + 1, Bias::Right);
 7748                        if let Some(ch) =
 7749                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7750                        {
 7751                            edits.push((transpose_start..transpose_offset, String::new()));
 7752                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7753                        }
 7754                    }
 7755                });
 7756                edits
 7757            });
 7758            this.buffer
 7759                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7760            let selections = this.selections.all::<usize>(cx);
 7761            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7762                s.select(selections);
 7763            });
 7764        });
 7765    }
 7766
 7767    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7768        self.rewrap_impl(IsVimMode::No, cx)
 7769    }
 7770
 7771    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7772        let buffer = self.buffer.read(cx).snapshot(cx);
 7773        let selections = self.selections.all::<Point>(cx);
 7774        let mut selections = selections.iter().peekable();
 7775
 7776        let mut edits = Vec::new();
 7777        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7778
 7779        while let Some(selection) = selections.next() {
 7780            let mut start_row = selection.start.row;
 7781            let mut end_row = selection.end.row;
 7782
 7783            // Skip selections that overlap with a range that has already been rewrapped.
 7784            let selection_range = start_row..end_row;
 7785            if rewrapped_row_ranges
 7786                .iter()
 7787                .any(|range| range.overlaps(&selection_range))
 7788            {
 7789                continue;
 7790            }
 7791
 7792            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7793
 7794            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7795                match language_scope.language_name().as_ref() {
 7796                    "Markdown" | "Plain Text" => {
 7797                        should_rewrap = true;
 7798                    }
 7799                    _ => {}
 7800                }
 7801            }
 7802
 7803            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7804
 7805            // Since not all lines in the selection may be at the same indent
 7806            // level, choose the indent size that is the most common between all
 7807            // of the lines.
 7808            //
 7809            // If there is a tie, we use the deepest indent.
 7810            let (indent_size, indent_end) = {
 7811                let mut indent_size_occurrences = HashMap::default();
 7812                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7813
 7814                for row in start_row..=end_row {
 7815                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7816                    rows_by_indent_size.entry(indent).or_default().push(row);
 7817                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7818                }
 7819
 7820                let indent_size = indent_size_occurrences
 7821                    .into_iter()
 7822                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7823                    .map(|(indent, _)| indent)
 7824                    .unwrap_or_default();
 7825                let row = rows_by_indent_size[&indent_size][0];
 7826                let indent_end = Point::new(row, indent_size.len);
 7827
 7828                (indent_size, indent_end)
 7829            };
 7830
 7831            let mut line_prefix = indent_size.chars().collect::<String>();
 7832
 7833            if let Some(comment_prefix) =
 7834                buffer
 7835                    .language_scope_at(selection.head())
 7836                    .and_then(|language| {
 7837                        language
 7838                            .line_comment_prefixes()
 7839                            .iter()
 7840                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7841                            .cloned()
 7842                    })
 7843            {
 7844                line_prefix.push_str(&comment_prefix);
 7845                should_rewrap = true;
 7846            }
 7847
 7848            if !should_rewrap {
 7849                continue;
 7850            }
 7851
 7852            if selection.is_empty() {
 7853                'expand_upwards: while start_row > 0 {
 7854                    let prev_row = start_row - 1;
 7855                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7856                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7857                    {
 7858                        start_row = prev_row;
 7859                    } else {
 7860                        break 'expand_upwards;
 7861                    }
 7862                }
 7863
 7864                'expand_downwards: while end_row < buffer.max_point().row {
 7865                    let next_row = end_row + 1;
 7866                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7867                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7868                    {
 7869                        end_row = next_row;
 7870                    } else {
 7871                        break 'expand_downwards;
 7872                    }
 7873                }
 7874            }
 7875
 7876            let start = Point::new(start_row, 0);
 7877            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7878            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7879            let Some(lines_without_prefixes) = selection_text
 7880                .lines()
 7881                .map(|line| {
 7882                    line.strip_prefix(&line_prefix)
 7883                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7884                        .ok_or_else(|| {
 7885                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7886                        })
 7887                })
 7888                .collect::<Result<Vec<_>, _>>()
 7889                .log_err()
 7890            else {
 7891                continue;
 7892            };
 7893
 7894            let wrap_column = buffer
 7895                .settings_at(Point::new(start_row, 0), cx)
 7896                .preferred_line_length as usize;
 7897            let wrapped_text = wrap_with_prefix(
 7898                line_prefix,
 7899                lines_without_prefixes.join(" "),
 7900                wrap_column,
 7901                tab_size,
 7902            );
 7903
 7904            // TODO: should always use char-based diff while still supporting cursor behavior that
 7905            // matches vim.
 7906            let diff = match is_vim_mode {
 7907                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7908                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7909            };
 7910            let mut offset = start.to_offset(&buffer);
 7911            let mut moved_since_edit = true;
 7912
 7913            for change in diff.iter_all_changes() {
 7914                let value = change.value();
 7915                match change.tag() {
 7916                    ChangeTag::Equal => {
 7917                        offset += value.len();
 7918                        moved_since_edit = true;
 7919                    }
 7920                    ChangeTag::Delete => {
 7921                        let start = buffer.anchor_after(offset);
 7922                        let end = buffer.anchor_before(offset + value.len());
 7923
 7924                        if moved_since_edit {
 7925                            edits.push((start..end, String::new()));
 7926                        } else {
 7927                            edits.last_mut().unwrap().0.end = end;
 7928                        }
 7929
 7930                        offset += value.len();
 7931                        moved_since_edit = false;
 7932                    }
 7933                    ChangeTag::Insert => {
 7934                        if moved_since_edit {
 7935                            let anchor = buffer.anchor_after(offset);
 7936                            edits.push((anchor..anchor, value.to_string()));
 7937                        } else {
 7938                            edits.last_mut().unwrap().1.push_str(value);
 7939                        }
 7940
 7941                        moved_since_edit = false;
 7942                    }
 7943                }
 7944            }
 7945
 7946            rewrapped_row_ranges.push(start_row..=end_row);
 7947        }
 7948
 7949        self.buffer
 7950            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7951    }
 7952
 7953    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7954        let mut text = String::new();
 7955        let buffer = self.buffer.read(cx).snapshot(cx);
 7956        let mut selections = self.selections.all::<Point>(cx);
 7957        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7958        {
 7959            let max_point = buffer.max_point();
 7960            let mut is_first = true;
 7961            for selection in &mut selections {
 7962                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7963                if is_entire_line {
 7964                    selection.start = Point::new(selection.start.row, 0);
 7965                    if !selection.is_empty() && selection.end.column == 0 {
 7966                        selection.end = cmp::min(max_point, selection.end);
 7967                    } else {
 7968                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7969                    }
 7970                    selection.goal = SelectionGoal::None;
 7971                }
 7972                if is_first {
 7973                    is_first = false;
 7974                } else {
 7975                    text += "\n";
 7976                }
 7977                let mut len = 0;
 7978                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7979                    text.push_str(chunk);
 7980                    len += chunk.len();
 7981                }
 7982                clipboard_selections.push(ClipboardSelection {
 7983                    len,
 7984                    is_entire_line,
 7985                    first_line_indent: buffer
 7986                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7987                        .len,
 7988                });
 7989            }
 7990        }
 7991
 7992        self.transact(window, cx, |this, window, cx| {
 7993            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7994                s.select(selections);
 7995            });
 7996            this.insert("", window, cx);
 7997        });
 7998        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7999    }
 8000
 8001    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8002        let item = self.cut_common(window, cx);
 8003        cx.write_to_clipboard(item);
 8004    }
 8005
 8006    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8007        self.change_selections(None, window, cx, |s| {
 8008            s.move_with(|snapshot, sel| {
 8009                if sel.is_empty() {
 8010                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8011                }
 8012            });
 8013        });
 8014        let item = self.cut_common(window, cx);
 8015        cx.set_global(KillRing(item))
 8016    }
 8017
 8018    pub fn kill_ring_yank(
 8019        &mut self,
 8020        _: &KillRingYank,
 8021        window: &mut Window,
 8022        cx: &mut Context<Self>,
 8023    ) {
 8024        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8025            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8026                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8027            } else {
 8028                return;
 8029            }
 8030        } else {
 8031            return;
 8032        };
 8033        self.do_paste(&text, metadata, false, window, cx);
 8034    }
 8035
 8036    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8037        let selections = self.selections.all::<Point>(cx);
 8038        let buffer = self.buffer.read(cx).read(cx);
 8039        let mut text = String::new();
 8040
 8041        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8042        {
 8043            let max_point = buffer.max_point();
 8044            let mut is_first = true;
 8045            for selection in selections.iter() {
 8046                let mut start = selection.start;
 8047                let mut end = selection.end;
 8048                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8049                if is_entire_line {
 8050                    start = Point::new(start.row, 0);
 8051                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8052                }
 8053                if is_first {
 8054                    is_first = false;
 8055                } else {
 8056                    text += "\n";
 8057                }
 8058                let mut len = 0;
 8059                for chunk in buffer.text_for_range(start..end) {
 8060                    text.push_str(chunk);
 8061                    len += chunk.len();
 8062                }
 8063                clipboard_selections.push(ClipboardSelection {
 8064                    len,
 8065                    is_entire_line,
 8066                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8067                });
 8068            }
 8069        }
 8070
 8071        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8072            text,
 8073            clipboard_selections,
 8074        ));
 8075    }
 8076
 8077    pub fn do_paste(
 8078        &mut self,
 8079        text: &String,
 8080        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8081        handle_entire_lines: bool,
 8082        window: &mut Window,
 8083        cx: &mut Context<Self>,
 8084    ) {
 8085        if self.read_only(cx) {
 8086            return;
 8087        }
 8088
 8089        let clipboard_text = Cow::Borrowed(text);
 8090
 8091        self.transact(window, cx, |this, window, cx| {
 8092            if let Some(mut clipboard_selections) = clipboard_selections {
 8093                let old_selections = this.selections.all::<usize>(cx);
 8094                let all_selections_were_entire_line =
 8095                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8096                let first_selection_indent_column =
 8097                    clipboard_selections.first().map(|s| s.first_line_indent);
 8098                if clipboard_selections.len() != old_selections.len() {
 8099                    clipboard_selections.drain(..);
 8100                }
 8101                let cursor_offset = this.selections.last::<usize>(cx).head();
 8102                let mut auto_indent_on_paste = true;
 8103
 8104                this.buffer.update(cx, |buffer, cx| {
 8105                    let snapshot = buffer.read(cx);
 8106                    auto_indent_on_paste =
 8107                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8108
 8109                    let mut start_offset = 0;
 8110                    let mut edits = Vec::new();
 8111                    let mut original_indent_columns = Vec::new();
 8112                    for (ix, selection) in old_selections.iter().enumerate() {
 8113                        let to_insert;
 8114                        let entire_line;
 8115                        let original_indent_column;
 8116                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8117                            let end_offset = start_offset + clipboard_selection.len;
 8118                            to_insert = &clipboard_text[start_offset..end_offset];
 8119                            entire_line = clipboard_selection.is_entire_line;
 8120                            start_offset = end_offset + 1;
 8121                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8122                        } else {
 8123                            to_insert = clipboard_text.as_str();
 8124                            entire_line = all_selections_were_entire_line;
 8125                            original_indent_column = first_selection_indent_column
 8126                        }
 8127
 8128                        // If the corresponding selection was empty when this slice of the
 8129                        // clipboard text was written, then the entire line containing the
 8130                        // selection was copied. If this selection is also currently empty,
 8131                        // then paste the line before the current line of the buffer.
 8132                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8133                            let column = selection.start.to_point(&snapshot).column as usize;
 8134                            let line_start = selection.start - column;
 8135                            line_start..line_start
 8136                        } else {
 8137                            selection.range()
 8138                        };
 8139
 8140                        edits.push((range, to_insert));
 8141                        original_indent_columns.extend(original_indent_column);
 8142                    }
 8143                    drop(snapshot);
 8144
 8145                    buffer.edit(
 8146                        edits,
 8147                        if auto_indent_on_paste {
 8148                            Some(AutoindentMode::Block {
 8149                                original_indent_columns,
 8150                            })
 8151                        } else {
 8152                            None
 8153                        },
 8154                        cx,
 8155                    );
 8156                });
 8157
 8158                let selections = this.selections.all::<usize>(cx);
 8159                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8160                    s.select(selections)
 8161                });
 8162            } else {
 8163                this.insert(&clipboard_text, window, cx);
 8164            }
 8165        });
 8166    }
 8167
 8168    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8169        if let Some(item) = cx.read_from_clipboard() {
 8170            let entries = item.entries();
 8171
 8172            match entries.first() {
 8173                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8174                // of all the pasted entries.
 8175                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8176                    .do_paste(
 8177                        clipboard_string.text(),
 8178                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8179                        true,
 8180                        window,
 8181                        cx,
 8182                    ),
 8183                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8184            }
 8185        }
 8186    }
 8187
 8188    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8189        if self.read_only(cx) {
 8190            return;
 8191        }
 8192
 8193        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8194            if let Some((selections, _)) =
 8195                self.selection_history.transaction(transaction_id).cloned()
 8196            {
 8197                self.change_selections(None, window, cx, |s| {
 8198                    s.select_anchors(selections.to_vec());
 8199                });
 8200            }
 8201            self.request_autoscroll(Autoscroll::fit(), cx);
 8202            self.unmark_text(window, cx);
 8203            self.refresh_inline_completion(true, false, window, cx);
 8204            cx.emit(EditorEvent::Edited { transaction_id });
 8205            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8206        }
 8207    }
 8208
 8209    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8210        if self.read_only(cx) {
 8211            return;
 8212        }
 8213
 8214        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8215            if let Some((_, Some(selections))) =
 8216                self.selection_history.transaction(transaction_id).cloned()
 8217            {
 8218                self.change_selections(None, window, cx, |s| {
 8219                    s.select_anchors(selections.to_vec());
 8220                });
 8221            }
 8222            self.request_autoscroll(Autoscroll::fit(), cx);
 8223            self.unmark_text(window, cx);
 8224            self.refresh_inline_completion(true, false, window, cx);
 8225            cx.emit(EditorEvent::Edited { transaction_id });
 8226        }
 8227    }
 8228
 8229    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8230        self.buffer
 8231            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8232    }
 8233
 8234    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8235        self.buffer
 8236            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8237    }
 8238
 8239    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8240        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8241            let line_mode = s.line_mode;
 8242            s.move_with(|map, selection| {
 8243                let cursor = if selection.is_empty() && !line_mode {
 8244                    movement::left(map, selection.start)
 8245                } else {
 8246                    selection.start
 8247                };
 8248                selection.collapse_to(cursor, SelectionGoal::None);
 8249            });
 8250        })
 8251    }
 8252
 8253    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8254        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8255            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8256        })
 8257    }
 8258
 8259    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8260        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8261            let line_mode = s.line_mode;
 8262            s.move_with(|map, selection| {
 8263                let cursor = if selection.is_empty() && !line_mode {
 8264                    movement::right(map, selection.end)
 8265                } else {
 8266                    selection.end
 8267                };
 8268                selection.collapse_to(cursor, SelectionGoal::None)
 8269            });
 8270        })
 8271    }
 8272
 8273    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8274        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8275            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8276        })
 8277    }
 8278
 8279    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8280        if self.take_rename(true, window, cx).is_some() {
 8281            return;
 8282        }
 8283
 8284        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8285            cx.propagate();
 8286            return;
 8287        }
 8288
 8289        let text_layout_details = &self.text_layout_details(window);
 8290        let selection_count = self.selections.count();
 8291        let first_selection = self.selections.first_anchor();
 8292
 8293        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8294            let line_mode = s.line_mode;
 8295            s.move_with(|map, selection| {
 8296                if !selection.is_empty() && !line_mode {
 8297                    selection.goal = SelectionGoal::None;
 8298                }
 8299                let (cursor, goal) = movement::up(
 8300                    map,
 8301                    selection.start,
 8302                    selection.goal,
 8303                    false,
 8304                    text_layout_details,
 8305                );
 8306                selection.collapse_to(cursor, goal);
 8307            });
 8308        });
 8309
 8310        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8311        {
 8312            cx.propagate();
 8313        }
 8314    }
 8315
 8316    pub fn move_up_by_lines(
 8317        &mut self,
 8318        action: &MoveUpByLines,
 8319        window: &mut Window,
 8320        cx: &mut Context<Self>,
 8321    ) {
 8322        if self.take_rename(true, window, cx).is_some() {
 8323            return;
 8324        }
 8325
 8326        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8327            cx.propagate();
 8328            return;
 8329        }
 8330
 8331        let text_layout_details = &self.text_layout_details(window);
 8332
 8333        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8334            let line_mode = s.line_mode;
 8335            s.move_with(|map, selection| {
 8336                if !selection.is_empty() && !line_mode {
 8337                    selection.goal = SelectionGoal::None;
 8338                }
 8339                let (cursor, goal) = movement::up_by_rows(
 8340                    map,
 8341                    selection.start,
 8342                    action.lines,
 8343                    selection.goal,
 8344                    false,
 8345                    text_layout_details,
 8346                );
 8347                selection.collapse_to(cursor, goal);
 8348            });
 8349        })
 8350    }
 8351
 8352    pub fn move_down_by_lines(
 8353        &mut self,
 8354        action: &MoveDownByLines,
 8355        window: &mut Window,
 8356        cx: &mut Context<Self>,
 8357    ) {
 8358        if self.take_rename(true, window, cx).is_some() {
 8359            return;
 8360        }
 8361
 8362        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8363            cx.propagate();
 8364            return;
 8365        }
 8366
 8367        let text_layout_details = &self.text_layout_details(window);
 8368
 8369        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8370            let line_mode = s.line_mode;
 8371            s.move_with(|map, selection| {
 8372                if !selection.is_empty() && !line_mode {
 8373                    selection.goal = SelectionGoal::None;
 8374                }
 8375                let (cursor, goal) = movement::down_by_rows(
 8376                    map,
 8377                    selection.start,
 8378                    action.lines,
 8379                    selection.goal,
 8380                    false,
 8381                    text_layout_details,
 8382                );
 8383                selection.collapse_to(cursor, goal);
 8384            });
 8385        })
 8386    }
 8387
 8388    pub fn select_down_by_lines(
 8389        &mut self,
 8390        action: &SelectDownByLines,
 8391        window: &mut Window,
 8392        cx: &mut Context<Self>,
 8393    ) {
 8394        let text_layout_details = &self.text_layout_details(window);
 8395        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8396            s.move_heads_with(|map, head, goal| {
 8397                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8398            })
 8399        })
 8400    }
 8401
 8402    pub fn select_up_by_lines(
 8403        &mut self,
 8404        action: &SelectUpByLines,
 8405        window: &mut Window,
 8406        cx: &mut Context<Self>,
 8407    ) {
 8408        let text_layout_details = &self.text_layout_details(window);
 8409        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8410            s.move_heads_with(|map, head, goal| {
 8411                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8412            })
 8413        })
 8414    }
 8415
 8416    pub fn select_page_up(
 8417        &mut self,
 8418        _: &SelectPageUp,
 8419        window: &mut Window,
 8420        cx: &mut Context<Self>,
 8421    ) {
 8422        let Some(row_count) = self.visible_row_count() else {
 8423            return;
 8424        };
 8425
 8426        let text_layout_details = &self.text_layout_details(window);
 8427
 8428        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8429            s.move_heads_with(|map, head, goal| {
 8430                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8431            })
 8432        })
 8433    }
 8434
 8435    pub fn move_page_up(
 8436        &mut self,
 8437        action: &MovePageUp,
 8438        window: &mut Window,
 8439        cx: &mut Context<Self>,
 8440    ) {
 8441        if self.take_rename(true, window, cx).is_some() {
 8442            return;
 8443        }
 8444
 8445        if self
 8446            .context_menu
 8447            .borrow_mut()
 8448            .as_mut()
 8449            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8450            .unwrap_or(false)
 8451        {
 8452            return;
 8453        }
 8454
 8455        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8456            cx.propagate();
 8457            return;
 8458        }
 8459
 8460        let Some(row_count) = self.visible_row_count() else {
 8461            return;
 8462        };
 8463
 8464        let autoscroll = if action.center_cursor {
 8465            Autoscroll::center()
 8466        } else {
 8467            Autoscroll::fit()
 8468        };
 8469
 8470        let text_layout_details = &self.text_layout_details(window);
 8471
 8472        self.change_selections(Some(autoscroll), window, cx, |s| {
 8473            let line_mode = s.line_mode;
 8474            s.move_with(|map, selection| {
 8475                if !selection.is_empty() && !line_mode {
 8476                    selection.goal = SelectionGoal::None;
 8477                }
 8478                let (cursor, goal) = movement::up_by_rows(
 8479                    map,
 8480                    selection.end,
 8481                    row_count,
 8482                    selection.goal,
 8483                    false,
 8484                    text_layout_details,
 8485                );
 8486                selection.collapse_to(cursor, goal);
 8487            });
 8488        });
 8489    }
 8490
 8491    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8492        let text_layout_details = &self.text_layout_details(window);
 8493        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8494            s.move_heads_with(|map, head, goal| {
 8495                movement::up(map, head, goal, false, text_layout_details)
 8496            })
 8497        })
 8498    }
 8499
 8500    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8501        self.take_rename(true, window, cx);
 8502
 8503        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8504            cx.propagate();
 8505            return;
 8506        }
 8507
 8508        let text_layout_details = &self.text_layout_details(window);
 8509        let selection_count = self.selections.count();
 8510        let first_selection = self.selections.first_anchor();
 8511
 8512        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8513            let line_mode = s.line_mode;
 8514            s.move_with(|map, selection| {
 8515                if !selection.is_empty() && !line_mode {
 8516                    selection.goal = SelectionGoal::None;
 8517                }
 8518                let (cursor, goal) = movement::down(
 8519                    map,
 8520                    selection.end,
 8521                    selection.goal,
 8522                    false,
 8523                    text_layout_details,
 8524                );
 8525                selection.collapse_to(cursor, goal);
 8526            });
 8527        });
 8528
 8529        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8530        {
 8531            cx.propagate();
 8532        }
 8533    }
 8534
 8535    pub fn select_page_down(
 8536        &mut self,
 8537        _: &SelectPageDown,
 8538        window: &mut Window,
 8539        cx: &mut Context<Self>,
 8540    ) {
 8541        let Some(row_count) = self.visible_row_count() else {
 8542            return;
 8543        };
 8544
 8545        let text_layout_details = &self.text_layout_details(window);
 8546
 8547        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8548            s.move_heads_with(|map, head, goal| {
 8549                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8550            })
 8551        })
 8552    }
 8553
 8554    pub fn move_page_down(
 8555        &mut self,
 8556        action: &MovePageDown,
 8557        window: &mut Window,
 8558        cx: &mut Context<Self>,
 8559    ) {
 8560        if self.take_rename(true, window, cx).is_some() {
 8561            return;
 8562        }
 8563
 8564        if self
 8565            .context_menu
 8566            .borrow_mut()
 8567            .as_mut()
 8568            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8569            .unwrap_or(false)
 8570        {
 8571            return;
 8572        }
 8573
 8574        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8575            cx.propagate();
 8576            return;
 8577        }
 8578
 8579        let Some(row_count) = self.visible_row_count() else {
 8580            return;
 8581        };
 8582
 8583        let autoscroll = if action.center_cursor {
 8584            Autoscroll::center()
 8585        } else {
 8586            Autoscroll::fit()
 8587        };
 8588
 8589        let text_layout_details = &self.text_layout_details(window);
 8590        self.change_selections(Some(autoscroll), window, cx, |s| {
 8591            let line_mode = s.line_mode;
 8592            s.move_with(|map, selection| {
 8593                if !selection.is_empty() && !line_mode {
 8594                    selection.goal = SelectionGoal::None;
 8595                }
 8596                let (cursor, goal) = movement::down_by_rows(
 8597                    map,
 8598                    selection.end,
 8599                    row_count,
 8600                    selection.goal,
 8601                    false,
 8602                    text_layout_details,
 8603                );
 8604                selection.collapse_to(cursor, goal);
 8605            });
 8606        });
 8607    }
 8608
 8609    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8610        let text_layout_details = &self.text_layout_details(window);
 8611        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8612            s.move_heads_with(|map, head, goal| {
 8613                movement::down(map, head, goal, false, text_layout_details)
 8614            })
 8615        });
 8616    }
 8617
 8618    pub fn context_menu_first(
 8619        &mut self,
 8620        _: &ContextMenuFirst,
 8621        _window: &mut Window,
 8622        cx: &mut Context<Self>,
 8623    ) {
 8624        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8625            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8626        }
 8627    }
 8628
 8629    pub fn context_menu_prev(
 8630        &mut self,
 8631        _: &ContextMenuPrev,
 8632        _window: &mut Window,
 8633        cx: &mut Context<Self>,
 8634    ) {
 8635        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8636            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8637        }
 8638    }
 8639
 8640    pub fn context_menu_next(
 8641        &mut self,
 8642        _: &ContextMenuNext,
 8643        _window: &mut Window,
 8644        cx: &mut Context<Self>,
 8645    ) {
 8646        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8647            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8648        }
 8649    }
 8650
 8651    pub fn context_menu_last(
 8652        &mut self,
 8653        _: &ContextMenuLast,
 8654        _window: &mut Window,
 8655        cx: &mut Context<Self>,
 8656    ) {
 8657        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8658            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8659        }
 8660    }
 8661
 8662    pub fn move_to_previous_word_start(
 8663        &mut self,
 8664        _: &MoveToPreviousWordStart,
 8665        window: &mut Window,
 8666        cx: &mut Context<Self>,
 8667    ) {
 8668        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8669            s.move_cursors_with(|map, head, _| {
 8670                (
 8671                    movement::previous_word_start(map, head),
 8672                    SelectionGoal::None,
 8673                )
 8674            });
 8675        })
 8676    }
 8677
 8678    pub fn move_to_previous_subword_start(
 8679        &mut self,
 8680        _: &MoveToPreviousSubwordStart,
 8681        window: &mut Window,
 8682        cx: &mut Context<Self>,
 8683    ) {
 8684        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8685            s.move_cursors_with(|map, head, _| {
 8686                (
 8687                    movement::previous_subword_start(map, head),
 8688                    SelectionGoal::None,
 8689                )
 8690            });
 8691        })
 8692    }
 8693
 8694    pub fn select_to_previous_word_start(
 8695        &mut self,
 8696        _: &SelectToPreviousWordStart,
 8697        window: &mut Window,
 8698        cx: &mut Context<Self>,
 8699    ) {
 8700        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8701            s.move_heads_with(|map, head, _| {
 8702                (
 8703                    movement::previous_word_start(map, head),
 8704                    SelectionGoal::None,
 8705                )
 8706            });
 8707        })
 8708    }
 8709
 8710    pub fn select_to_previous_subword_start(
 8711        &mut self,
 8712        _: &SelectToPreviousSubwordStart,
 8713        window: &mut Window,
 8714        cx: &mut Context<Self>,
 8715    ) {
 8716        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8717            s.move_heads_with(|map, head, _| {
 8718                (
 8719                    movement::previous_subword_start(map, head),
 8720                    SelectionGoal::None,
 8721                )
 8722            });
 8723        })
 8724    }
 8725
 8726    pub fn delete_to_previous_word_start(
 8727        &mut self,
 8728        action: &DeleteToPreviousWordStart,
 8729        window: &mut Window,
 8730        cx: &mut Context<Self>,
 8731    ) {
 8732        self.transact(window, cx, |this, window, cx| {
 8733            this.select_autoclose_pair(window, cx);
 8734            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8735                let line_mode = s.line_mode;
 8736                s.move_with(|map, selection| {
 8737                    if selection.is_empty() && !line_mode {
 8738                        let cursor = if action.ignore_newlines {
 8739                            movement::previous_word_start(map, selection.head())
 8740                        } else {
 8741                            movement::previous_word_start_or_newline(map, selection.head())
 8742                        };
 8743                        selection.set_head(cursor, SelectionGoal::None);
 8744                    }
 8745                });
 8746            });
 8747            this.insert("", window, cx);
 8748        });
 8749    }
 8750
 8751    pub fn delete_to_previous_subword_start(
 8752        &mut self,
 8753        _: &DeleteToPreviousSubwordStart,
 8754        window: &mut Window,
 8755        cx: &mut Context<Self>,
 8756    ) {
 8757        self.transact(window, cx, |this, window, cx| {
 8758            this.select_autoclose_pair(window, cx);
 8759            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8760                let line_mode = s.line_mode;
 8761                s.move_with(|map, selection| {
 8762                    if selection.is_empty() && !line_mode {
 8763                        let cursor = movement::previous_subword_start(map, selection.head());
 8764                        selection.set_head(cursor, SelectionGoal::None);
 8765                    }
 8766                });
 8767            });
 8768            this.insert("", window, cx);
 8769        });
 8770    }
 8771
 8772    pub fn move_to_next_word_end(
 8773        &mut self,
 8774        _: &MoveToNextWordEnd,
 8775        window: &mut Window,
 8776        cx: &mut Context<Self>,
 8777    ) {
 8778        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8779            s.move_cursors_with(|map, head, _| {
 8780                (movement::next_word_end(map, head), SelectionGoal::None)
 8781            });
 8782        })
 8783    }
 8784
 8785    pub fn move_to_next_subword_end(
 8786        &mut self,
 8787        _: &MoveToNextSubwordEnd,
 8788        window: &mut Window,
 8789        cx: &mut Context<Self>,
 8790    ) {
 8791        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8792            s.move_cursors_with(|map, head, _| {
 8793                (movement::next_subword_end(map, head), SelectionGoal::None)
 8794            });
 8795        })
 8796    }
 8797
 8798    pub fn select_to_next_word_end(
 8799        &mut self,
 8800        _: &SelectToNextWordEnd,
 8801        window: &mut Window,
 8802        cx: &mut Context<Self>,
 8803    ) {
 8804        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8805            s.move_heads_with(|map, head, _| {
 8806                (movement::next_word_end(map, head), SelectionGoal::None)
 8807            });
 8808        })
 8809    }
 8810
 8811    pub fn select_to_next_subword_end(
 8812        &mut self,
 8813        _: &SelectToNextSubwordEnd,
 8814        window: &mut Window,
 8815        cx: &mut Context<Self>,
 8816    ) {
 8817        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8818            s.move_heads_with(|map, head, _| {
 8819                (movement::next_subword_end(map, head), SelectionGoal::None)
 8820            });
 8821        })
 8822    }
 8823
 8824    pub fn delete_to_next_word_end(
 8825        &mut self,
 8826        action: &DeleteToNextWordEnd,
 8827        window: &mut Window,
 8828        cx: &mut Context<Self>,
 8829    ) {
 8830        self.transact(window, cx, |this, window, cx| {
 8831            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8832                let line_mode = s.line_mode;
 8833                s.move_with(|map, selection| {
 8834                    if selection.is_empty() && !line_mode {
 8835                        let cursor = if action.ignore_newlines {
 8836                            movement::next_word_end(map, selection.head())
 8837                        } else {
 8838                            movement::next_word_end_or_newline(map, selection.head())
 8839                        };
 8840                        selection.set_head(cursor, SelectionGoal::None);
 8841                    }
 8842                });
 8843            });
 8844            this.insert("", window, cx);
 8845        });
 8846    }
 8847
 8848    pub fn delete_to_next_subword_end(
 8849        &mut self,
 8850        _: &DeleteToNextSubwordEnd,
 8851        window: &mut Window,
 8852        cx: &mut Context<Self>,
 8853    ) {
 8854        self.transact(window, cx, |this, window, cx| {
 8855            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8856                s.move_with(|map, selection| {
 8857                    if selection.is_empty() {
 8858                        let cursor = movement::next_subword_end(map, selection.head());
 8859                        selection.set_head(cursor, SelectionGoal::None);
 8860                    }
 8861                });
 8862            });
 8863            this.insert("", window, cx);
 8864        });
 8865    }
 8866
 8867    pub fn move_to_beginning_of_line(
 8868        &mut self,
 8869        action: &MoveToBeginningOfLine,
 8870        window: &mut Window,
 8871        cx: &mut Context<Self>,
 8872    ) {
 8873        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8874            s.move_cursors_with(|map, head, _| {
 8875                (
 8876                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8877                    SelectionGoal::None,
 8878                )
 8879            });
 8880        })
 8881    }
 8882
 8883    pub fn select_to_beginning_of_line(
 8884        &mut self,
 8885        action: &SelectToBeginningOfLine,
 8886        window: &mut Window,
 8887        cx: &mut Context<Self>,
 8888    ) {
 8889        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8890            s.move_heads_with(|map, head, _| {
 8891                (
 8892                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8893                    SelectionGoal::None,
 8894                )
 8895            });
 8896        });
 8897    }
 8898
 8899    pub fn delete_to_beginning_of_line(
 8900        &mut self,
 8901        _: &DeleteToBeginningOfLine,
 8902        window: &mut Window,
 8903        cx: &mut Context<Self>,
 8904    ) {
 8905        self.transact(window, cx, |this, window, cx| {
 8906            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8907                s.move_with(|_, selection| {
 8908                    selection.reversed = true;
 8909                });
 8910            });
 8911
 8912            this.select_to_beginning_of_line(
 8913                &SelectToBeginningOfLine {
 8914                    stop_at_soft_wraps: false,
 8915                },
 8916                window,
 8917                cx,
 8918            );
 8919            this.backspace(&Backspace, window, cx);
 8920        });
 8921    }
 8922
 8923    pub fn move_to_end_of_line(
 8924        &mut self,
 8925        action: &MoveToEndOfLine,
 8926        window: &mut Window,
 8927        cx: &mut Context<Self>,
 8928    ) {
 8929        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8930            s.move_cursors_with(|map, head, _| {
 8931                (
 8932                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8933                    SelectionGoal::None,
 8934                )
 8935            });
 8936        })
 8937    }
 8938
 8939    pub fn select_to_end_of_line(
 8940        &mut self,
 8941        action: &SelectToEndOfLine,
 8942        window: &mut Window,
 8943        cx: &mut Context<Self>,
 8944    ) {
 8945        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8946            s.move_heads_with(|map, head, _| {
 8947                (
 8948                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8949                    SelectionGoal::None,
 8950                )
 8951            });
 8952        })
 8953    }
 8954
 8955    pub fn delete_to_end_of_line(
 8956        &mut self,
 8957        _: &DeleteToEndOfLine,
 8958        window: &mut Window,
 8959        cx: &mut Context<Self>,
 8960    ) {
 8961        self.transact(window, cx, |this, window, cx| {
 8962            this.select_to_end_of_line(
 8963                &SelectToEndOfLine {
 8964                    stop_at_soft_wraps: false,
 8965                },
 8966                window,
 8967                cx,
 8968            );
 8969            this.delete(&Delete, window, cx);
 8970        });
 8971    }
 8972
 8973    pub fn cut_to_end_of_line(
 8974        &mut self,
 8975        _: &CutToEndOfLine,
 8976        window: &mut Window,
 8977        cx: &mut Context<Self>,
 8978    ) {
 8979        self.transact(window, cx, |this, window, cx| {
 8980            this.select_to_end_of_line(
 8981                &SelectToEndOfLine {
 8982                    stop_at_soft_wraps: false,
 8983                },
 8984                window,
 8985                cx,
 8986            );
 8987            this.cut(&Cut, window, cx);
 8988        });
 8989    }
 8990
 8991    pub fn move_to_start_of_paragraph(
 8992        &mut self,
 8993        _: &MoveToStartOfParagraph,
 8994        window: &mut Window,
 8995        cx: &mut Context<Self>,
 8996    ) {
 8997        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8998            cx.propagate();
 8999            return;
 9000        }
 9001
 9002        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9003            s.move_with(|map, selection| {
 9004                selection.collapse_to(
 9005                    movement::start_of_paragraph(map, selection.head(), 1),
 9006                    SelectionGoal::None,
 9007                )
 9008            });
 9009        })
 9010    }
 9011
 9012    pub fn move_to_end_of_paragraph(
 9013        &mut self,
 9014        _: &MoveToEndOfParagraph,
 9015        window: &mut Window,
 9016        cx: &mut Context<Self>,
 9017    ) {
 9018        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9019            cx.propagate();
 9020            return;
 9021        }
 9022
 9023        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9024            s.move_with(|map, selection| {
 9025                selection.collapse_to(
 9026                    movement::end_of_paragraph(map, selection.head(), 1),
 9027                    SelectionGoal::None,
 9028                )
 9029            });
 9030        })
 9031    }
 9032
 9033    pub fn select_to_start_of_paragraph(
 9034        &mut self,
 9035        _: &SelectToStartOfParagraph,
 9036        window: &mut Window,
 9037        cx: &mut Context<Self>,
 9038    ) {
 9039        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9040            cx.propagate();
 9041            return;
 9042        }
 9043
 9044        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9045            s.move_heads_with(|map, head, _| {
 9046                (
 9047                    movement::start_of_paragraph(map, head, 1),
 9048                    SelectionGoal::None,
 9049                )
 9050            });
 9051        })
 9052    }
 9053
 9054    pub fn select_to_end_of_paragraph(
 9055        &mut self,
 9056        _: &SelectToEndOfParagraph,
 9057        window: &mut Window,
 9058        cx: &mut Context<Self>,
 9059    ) {
 9060        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9061            cx.propagate();
 9062            return;
 9063        }
 9064
 9065        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9066            s.move_heads_with(|map, head, _| {
 9067                (
 9068                    movement::end_of_paragraph(map, head, 1),
 9069                    SelectionGoal::None,
 9070                )
 9071            });
 9072        })
 9073    }
 9074
 9075    pub fn move_to_beginning(
 9076        &mut self,
 9077        _: &MoveToBeginning,
 9078        window: &mut Window,
 9079        cx: &mut Context<Self>,
 9080    ) {
 9081        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9082            cx.propagate();
 9083            return;
 9084        }
 9085
 9086        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9087            s.select_ranges(vec![0..0]);
 9088        });
 9089    }
 9090
 9091    pub fn select_to_beginning(
 9092        &mut self,
 9093        _: &SelectToBeginning,
 9094        window: &mut Window,
 9095        cx: &mut Context<Self>,
 9096    ) {
 9097        let mut selection = self.selections.last::<Point>(cx);
 9098        selection.set_head(Point::zero(), SelectionGoal::None);
 9099
 9100        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9101            s.select(vec![selection]);
 9102        });
 9103    }
 9104
 9105    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9106        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9107            cx.propagate();
 9108            return;
 9109        }
 9110
 9111        let cursor = self.buffer.read(cx).read(cx).len();
 9112        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9113            s.select_ranges(vec![cursor..cursor])
 9114        });
 9115    }
 9116
 9117    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9118        self.nav_history = nav_history;
 9119    }
 9120
 9121    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9122        self.nav_history.as_ref()
 9123    }
 9124
 9125    fn push_to_nav_history(
 9126        &mut self,
 9127        cursor_anchor: Anchor,
 9128        new_position: Option<Point>,
 9129        cx: &mut Context<Self>,
 9130    ) {
 9131        if let Some(nav_history) = self.nav_history.as_mut() {
 9132            let buffer = self.buffer.read(cx).read(cx);
 9133            let cursor_position = cursor_anchor.to_point(&buffer);
 9134            let scroll_state = self.scroll_manager.anchor();
 9135            let scroll_top_row = scroll_state.top_row(&buffer);
 9136            drop(buffer);
 9137
 9138            if let Some(new_position) = new_position {
 9139                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9140                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9141                    return;
 9142                }
 9143            }
 9144
 9145            nav_history.push(
 9146                Some(NavigationData {
 9147                    cursor_anchor,
 9148                    cursor_position,
 9149                    scroll_anchor: scroll_state,
 9150                    scroll_top_row,
 9151                }),
 9152                cx,
 9153            );
 9154        }
 9155    }
 9156
 9157    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9158        let buffer = self.buffer.read(cx).snapshot(cx);
 9159        let mut selection = self.selections.first::<usize>(cx);
 9160        selection.set_head(buffer.len(), SelectionGoal::None);
 9161        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9162            s.select(vec![selection]);
 9163        });
 9164    }
 9165
 9166    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9167        let end = self.buffer.read(cx).read(cx).len();
 9168        self.change_selections(None, window, cx, |s| {
 9169            s.select_ranges(vec![0..end]);
 9170        });
 9171    }
 9172
 9173    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9174        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9175        let mut selections = self.selections.all::<Point>(cx);
 9176        let max_point = display_map.buffer_snapshot.max_point();
 9177        for selection in &mut selections {
 9178            let rows = selection.spanned_rows(true, &display_map);
 9179            selection.start = Point::new(rows.start.0, 0);
 9180            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9181            selection.reversed = false;
 9182        }
 9183        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9184            s.select(selections);
 9185        });
 9186    }
 9187
 9188    pub fn split_selection_into_lines(
 9189        &mut self,
 9190        _: &SplitSelectionIntoLines,
 9191        window: &mut Window,
 9192        cx: &mut Context<Self>,
 9193    ) {
 9194        let selections = self
 9195            .selections
 9196            .all::<Point>(cx)
 9197            .into_iter()
 9198            .map(|selection| selection.start..selection.end)
 9199            .collect::<Vec<_>>();
 9200        self.unfold_ranges(&selections, true, true, cx);
 9201
 9202        let mut new_selection_ranges = Vec::new();
 9203        {
 9204            let buffer = self.buffer.read(cx).read(cx);
 9205            for selection in selections {
 9206                for row in selection.start.row..selection.end.row {
 9207                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9208                    new_selection_ranges.push(cursor..cursor);
 9209                }
 9210
 9211                let is_multiline_selection = selection.start.row != selection.end.row;
 9212                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9213                // so this action feels more ergonomic when paired with other selection operations
 9214                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9215                if !should_skip_last {
 9216                    new_selection_ranges.push(selection.end..selection.end);
 9217                }
 9218            }
 9219        }
 9220        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9221            s.select_ranges(new_selection_ranges);
 9222        });
 9223    }
 9224
 9225    pub fn add_selection_above(
 9226        &mut self,
 9227        _: &AddSelectionAbove,
 9228        window: &mut Window,
 9229        cx: &mut Context<Self>,
 9230    ) {
 9231        self.add_selection(true, window, cx);
 9232    }
 9233
 9234    pub fn add_selection_below(
 9235        &mut self,
 9236        _: &AddSelectionBelow,
 9237        window: &mut Window,
 9238        cx: &mut Context<Self>,
 9239    ) {
 9240        self.add_selection(false, window, cx);
 9241    }
 9242
 9243    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9244        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9245        let mut selections = self.selections.all::<Point>(cx);
 9246        let text_layout_details = self.text_layout_details(window);
 9247        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9248            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9249            let range = oldest_selection.display_range(&display_map).sorted();
 9250
 9251            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9252            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9253            let positions = start_x.min(end_x)..start_x.max(end_x);
 9254
 9255            selections.clear();
 9256            let mut stack = Vec::new();
 9257            for row in range.start.row().0..=range.end.row().0 {
 9258                if let Some(selection) = self.selections.build_columnar_selection(
 9259                    &display_map,
 9260                    DisplayRow(row),
 9261                    &positions,
 9262                    oldest_selection.reversed,
 9263                    &text_layout_details,
 9264                ) {
 9265                    stack.push(selection.id);
 9266                    selections.push(selection);
 9267                }
 9268            }
 9269
 9270            if above {
 9271                stack.reverse();
 9272            }
 9273
 9274            AddSelectionsState { above, stack }
 9275        });
 9276
 9277        let last_added_selection = *state.stack.last().unwrap();
 9278        let mut new_selections = Vec::new();
 9279        if above == state.above {
 9280            let end_row = if above {
 9281                DisplayRow(0)
 9282            } else {
 9283                display_map.max_point().row()
 9284            };
 9285
 9286            'outer: for selection in selections {
 9287                if selection.id == last_added_selection {
 9288                    let range = selection.display_range(&display_map).sorted();
 9289                    debug_assert_eq!(range.start.row(), range.end.row());
 9290                    let mut row = range.start.row();
 9291                    let positions =
 9292                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9293                            px(start)..px(end)
 9294                        } else {
 9295                            let start_x =
 9296                                display_map.x_for_display_point(range.start, &text_layout_details);
 9297                            let end_x =
 9298                                display_map.x_for_display_point(range.end, &text_layout_details);
 9299                            start_x.min(end_x)..start_x.max(end_x)
 9300                        };
 9301
 9302                    while row != end_row {
 9303                        if above {
 9304                            row.0 -= 1;
 9305                        } else {
 9306                            row.0 += 1;
 9307                        }
 9308
 9309                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9310                            &display_map,
 9311                            row,
 9312                            &positions,
 9313                            selection.reversed,
 9314                            &text_layout_details,
 9315                        ) {
 9316                            state.stack.push(new_selection.id);
 9317                            if above {
 9318                                new_selections.push(new_selection);
 9319                                new_selections.push(selection);
 9320                            } else {
 9321                                new_selections.push(selection);
 9322                                new_selections.push(new_selection);
 9323                            }
 9324
 9325                            continue 'outer;
 9326                        }
 9327                    }
 9328                }
 9329
 9330                new_selections.push(selection);
 9331            }
 9332        } else {
 9333            new_selections = selections;
 9334            new_selections.retain(|s| s.id != last_added_selection);
 9335            state.stack.pop();
 9336        }
 9337
 9338        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9339            s.select(new_selections);
 9340        });
 9341        if state.stack.len() > 1 {
 9342            self.add_selections_state = Some(state);
 9343        }
 9344    }
 9345
 9346    pub fn select_next_match_internal(
 9347        &mut self,
 9348        display_map: &DisplaySnapshot,
 9349        replace_newest: bool,
 9350        autoscroll: Option<Autoscroll>,
 9351        window: &mut Window,
 9352        cx: &mut Context<Self>,
 9353    ) -> Result<()> {
 9354        fn select_next_match_ranges(
 9355            this: &mut Editor,
 9356            range: Range<usize>,
 9357            replace_newest: bool,
 9358            auto_scroll: Option<Autoscroll>,
 9359            window: &mut Window,
 9360            cx: &mut Context<Editor>,
 9361        ) {
 9362            this.unfold_ranges(&[range.clone()], false, true, cx);
 9363            this.change_selections(auto_scroll, window, cx, |s| {
 9364                if replace_newest {
 9365                    s.delete(s.newest_anchor().id);
 9366                }
 9367                s.insert_range(range.clone());
 9368            });
 9369        }
 9370
 9371        let buffer = &display_map.buffer_snapshot;
 9372        let mut selections = self.selections.all::<usize>(cx);
 9373        if let Some(mut select_next_state) = self.select_next_state.take() {
 9374            let query = &select_next_state.query;
 9375            if !select_next_state.done {
 9376                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9377                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9378                let mut next_selected_range = None;
 9379
 9380                let bytes_after_last_selection =
 9381                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9382                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9383                let query_matches = query
 9384                    .stream_find_iter(bytes_after_last_selection)
 9385                    .map(|result| (last_selection.end, result))
 9386                    .chain(
 9387                        query
 9388                            .stream_find_iter(bytes_before_first_selection)
 9389                            .map(|result| (0, result)),
 9390                    );
 9391
 9392                for (start_offset, query_match) in query_matches {
 9393                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9394                    let offset_range =
 9395                        start_offset + query_match.start()..start_offset + query_match.end();
 9396                    let display_range = offset_range.start.to_display_point(display_map)
 9397                        ..offset_range.end.to_display_point(display_map);
 9398
 9399                    if !select_next_state.wordwise
 9400                        || (!movement::is_inside_word(display_map, display_range.start)
 9401                            && !movement::is_inside_word(display_map, display_range.end))
 9402                    {
 9403                        // TODO: This is n^2, because we might check all the selections
 9404                        if !selections
 9405                            .iter()
 9406                            .any(|selection| selection.range().overlaps(&offset_range))
 9407                        {
 9408                            next_selected_range = Some(offset_range);
 9409                            break;
 9410                        }
 9411                    }
 9412                }
 9413
 9414                if let Some(next_selected_range) = next_selected_range {
 9415                    select_next_match_ranges(
 9416                        self,
 9417                        next_selected_range,
 9418                        replace_newest,
 9419                        autoscroll,
 9420                        window,
 9421                        cx,
 9422                    );
 9423                } else {
 9424                    select_next_state.done = true;
 9425                }
 9426            }
 9427
 9428            self.select_next_state = Some(select_next_state);
 9429        } else {
 9430            let mut only_carets = true;
 9431            let mut same_text_selected = true;
 9432            let mut selected_text = None;
 9433
 9434            let mut selections_iter = selections.iter().peekable();
 9435            while let Some(selection) = selections_iter.next() {
 9436                if selection.start != selection.end {
 9437                    only_carets = false;
 9438                }
 9439
 9440                if same_text_selected {
 9441                    if selected_text.is_none() {
 9442                        selected_text =
 9443                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9444                    }
 9445
 9446                    if let Some(next_selection) = selections_iter.peek() {
 9447                        if next_selection.range().len() == selection.range().len() {
 9448                            let next_selected_text = buffer
 9449                                .text_for_range(next_selection.range())
 9450                                .collect::<String>();
 9451                            if Some(next_selected_text) != selected_text {
 9452                                same_text_selected = false;
 9453                                selected_text = None;
 9454                            }
 9455                        } else {
 9456                            same_text_selected = false;
 9457                            selected_text = None;
 9458                        }
 9459                    }
 9460                }
 9461            }
 9462
 9463            if only_carets {
 9464                for selection in &mut selections {
 9465                    let word_range = movement::surrounding_word(
 9466                        display_map,
 9467                        selection.start.to_display_point(display_map),
 9468                    );
 9469                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9470                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9471                    selection.goal = SelectionGoal::None;
 9472                    selection.reversed = false;
 9473                    select_next_match_ranges(
 9474                        self,
 9475                        selection.start..selection.end,
 9476                        replace_newest,
 9477                        autoscroll,
 9478                        window,
 9479                        cx,
 9480                    );
 9481                }
 9482
 9483                if selections.len() == 1 {
 9484                    let selection = selections
 9485                        .last()
 9486                        .expect("ensured that there's only one selection");
 9487                    let query = buffer
 9488                        .text_for_range(selection.start..selection.end)
 9489                        .collect::<String>();
 9490                    let is_empty = query.is_empty();
 9491                    let select_state = SelectNextState {
 9492                        query: AhoCorasick::new(&[query])?,
 9493                        wordwise: true,
 9494                        done: is_empty,
 9495                    };
 9496                    self.select_next_state = Some(select_state);
 9497                } else {
 9498                    self.select_next_state = None;
 9499                }
 9500            } else if let Some(selected_text) = selected_text {
 9501                self.select_next_state = Some(SelectNextState {
 9502                    query: AhoCorasick::new(&[selected_text])?,
 9503                    wordwise: false,
 9504                    done: false,
 9505                });
 9506                self.select_next_match_internal(
 9507                    display_map,
 9508                    replace_newest,
 9509                    autoscroll,
 9510                    window,
 9511                    cx,
 9512                )?;
 9513            }
 9514        }
 9515        Ok(())
 9516    }
 9517
 9518    pub fn select_all_matches(
 9519        &mut self,
 9520        _action: &SelectAllMatches,
 9521        window: &mut Window,
 9522        cx: &mut Context<Self>,
 9523    ) -> Result<()> {
 9524        self.push_to_selection_history();
 9525        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9526
 9527        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9528        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9529            return Ok(());
 9530        };
 9531        if select_next_state.done {
 9532            return Ok(());
 9533        }
 9534
 9535        let mut new_selections = self.selections.all::<usize>(cx);
 9536
 9537        let buffer = &display_map.buffer_snapshot;
 9538        let query_matches = select_next_state
 9539            .query
 9540            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9541
 9542        for query_match in query_matches {
 9543            let query_match = query_match.unwrap(); // can only fail due to I/O
 9544            let offset_range = query_match.start()..query_match.end();
 9545            let display_range = offset_range.start.to_display_point(&display_map)
 9546                ..offset_range.end.to_display_point(&display_map);
 9547
 9548            if !select_next_state.wordwise
 9549                || (!movement::is_inside_word(&display_map, display_range.start)
 9550                    && !movement::is_inside_word(&display_map, display_range.end))
 9551            {
 9552                self.selections.change_with(cx, |selections| {
 9553                    new_selections.push(Selection {
 9554                        id: selections.new_selection_id(),
 9555                        start: offset_range.start,
 9556                        end: offset_range.end,
 9557                        reversed: false,
 9558                        goal: SelectionGoal::None,
 9559                    });
 9560                });
 9561            }
 9562        }
 9563
 9564        new_selections.sort_by_key(|selection| selection.start);
 9565        let mut ix = 0;
 9566        while ix + 1 < new_selections.len() {
 9567            let current_selection = &new_selections[ix];
 9568            let next_selection = &new_selections[ix + 1];
 9569            if current_selection.range().overlaps(&next_selection.range()) {
 9570                if current_selection.id < next_selection.id {
 9571                    new_selections.remove(ix + 1);
 9572                } else {
 9573                    new_selections.remove(ix);
 9574                }
 9575            } else {
 9576                ix += 1;
 9577            }
 9578        }
 9579
 9580        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9581
 9582        for selection in new_selections.iter_mut() {
 9583            selection.reversed = reversed;
 9584        }
 9585
 9586        select_next_state.done = true;
 9587        self.unfold_ranges(
 9588            &new_selections
 9589                .iter()
 9590                .map(|selection| selection.range())
 9591                .collect::<Vec<_>>(),
 9592            false,
 9593            false,
 9594            cx,
 9595        );
 9596        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9597            selections.select(new_selections)
 9598        });
 9599
 9600        Ok(())
 9601    }
 9602
 9603    pub fn select_next(
 9604        &mut self,
 9605        action: &SelectNext,
 9606        window: &mut Window,
 9607        cx: &mut Context<Self>,
 9608    ) -> Result<()> {
 9609        self.push_to_selection_history();
 9610        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9611        self.select_next_match_internal(
 9612            &display_map,
 9613            action.replace_newest,
 9614            Some(Autoscroll::newest()),
 9615            window,
 9616            cx,
 9617        )?;
 9618        Ok(())
 9619    }
 9620
 9621    pub fn select_previous(
 9622        &mut self,
 9623        action: &SelectPrevious,
 9624        window: &mut Window,
 9625        cx: &mut Context<Self>,
 9626    ) -> Result<()> {
 9627        self.push_to_selection_history();
 9628        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9629        let buffer = &display_map.buffer_snapshot;
 9630        let mut selections = self.selections.all::<usize>(cx);
 9631        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9632            let query = &select_prev_state.query;
 9633            if !select_prev_state.done {
 9634                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9635                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9636                let mut next_selected_range = None;
 9637                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9638                let bytes_before_last_selection =
 9639                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9640                let bytes_after_first_selection =
 9641                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9642                let query_matches = query
 9643                    .stream_find_iter(bytes_before_last_selection)
 9644                    .map(|result| (last_selection.start, result))
 9645                    .chain(
 9646                        query
 9647                            .stream_find_iter(bytes_after_first_selection)
 9648                            .map(|result| (buffer.len(), result)),
 9649                    );
 9650                for (end_offset, query_match) in query_matches {
 9651                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9652                    let offset_range =
 9653                        end_offset - query_match.end()..end_offset - query_match.start();
 9654                    let display_range = offset_range.start.to_display_point(&display_map)
 9655                        ..offset_range.end.to_display_point(&display_map);
 9656
 9657                    if !select_prev_state.wordwise
 9658                        || (!movement::is_inside_word(&display_map, display_range.start)
 9659                            && !movement::is_inside_word(&display_map, display_range.end))
 9660                    {
 9661                        next_selected_range = Some(offset_range);
 9662                        break;
 9663                    }
 9664                }
 9665
 9666                if let Some(next_selected_range) = next_selected_range {
 9667                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9668                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9669                        if action.replace_newest {
 9670                            s.delete(s.newest_anchor().id);
 9671                        }
 9672                        s.insert_range(next_selected_range);
 9673                    });
 9674                } else {
 9675                    select_prev_state.done = true;
 9676                }
 9677            }
 9678
 9679            self.select_prev_state = Some(select_prev_state);
 9680        } else {
 9681            let mut only_carets = true;
 9682            let mut same_text_selected = true;
 9683            let mut selected_text = None;
 9684
 9685            let mut selections_iter = selections.iter().peekable();
 9686            while let Some(selection) = selections_iter.next() {
 9687                if selection.start != selection.end {
 9688                    only_carets = false;
 9689                }
 9690
 9691                if same_text_selected {
 9692                    if selected_text.is_none() {
 9693                        selected_text =
 9694                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9695                    }
 9696
 9697                    if let Some(next_selection) = selections_iter.peek() {
 9698                        if next_selection.range().len() == selection.range().len() {
 9699                            let next_selected_text = buffer
 9700                                .text_for_range(next_selection.range())
 9701                                .collect::<String>();
 9702                            if Some(next_selected_text) != selected_text {
 9703                                same_text_selected = false;
 9704                                selected_text = None;
 9705                            }
 9706                        } else {
 9707                            same_text_selected = false;
 9708                            selected_text = None;
 9709                        }
 9710                    }
 9711                }
 9712            }
 9713
 9714            if only_carets {
 9715                for selection in &mut selections {
 9716                    let word_range = movement::surrounding_word(
 9717                        &display_map,
 9718                        selection.start.to_display_point(&display_map),
 9719                    );
 9720                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9721                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9722                    selection.goal = SelectionGoal::None;
 9723                    selection.reversed = false;
 9724                }
 9725                if selections.len() == 1 {
 9726                    let selection = selections
 9727                        .last()
 9728                        .expect("ensured that there's only one selection");
 9729                    let query = buffer
 9730                        .text_for_range(selection.start..selection.end)
 9731                        .collect::<String>();
 9732                    let is_empty = query.is_empty();
 9733                    let select_state = SelectNextState {
 9734                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9735                        wordwise: true,
 9736                        done: is_empty,
 9737                    };
 9738                    self.select_prev_state = Some(select_state);
 9739                } else {
 9740                    self.select_prev_state = None;
 9741                }
 9742
 9743                self.unfold_ranges(
 9744                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9745                    false,
 9746                    true,
 9747                    cx,
 9748                );
 9749                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9750                    s.select(selections);
 9751                });
 9752            } else if let Some(selected_text) = selected_text {
 9753                self.select_prev_state = Some(SelectNextState {
 9754                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9755                    wordwise: false,
 9756                    done: false,
 9757                });
 9758                self.select_previous(action, window, cx)?;
 9759            }
 9760        }
 9761        Ok(())
 9762    }
 9763
 9764    pub fn toggle_comments(
 9765        &mut self,
 9766        action: &ToggleComments,
 9767        window: &mut Window,
 9768        cx: &mut Context<Self>,
 9769    ) {
 9770        if self.read_only(cx) {
 9771            return;
 9772        }
 9773        let text_layout_details = &self.text_layout_details(window);
 9774        self.transact(window, cx, |this, window, cx| {
 9775            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9776            let mut edits = Vec::new();
 9777            let mut selection_edit_ranges = Vec::new();
 9778            let mut last_toggled_row = None;
 9779            let snapshot = this.buffer.read(cx).read(cx);
 9780            let empty_str: Arc<str> = Arc::default();
 9781            let mut suffixes_inserted = Vec::new();
 9782            let ignore_indent = action.ignore_indent;
 9783
 9784            fn comment_prefix_range(
 9785                snapshot: &MultiBufferSnapshot,
 9786                row: MultiBufferRow,
 9787                comment_prefix: &str,
 9788                comment_prefix_whitespace: &str,
 9789                ignore_indent: bool,
 9790            ) -> Range<Point> {
 9791                let indent_size = if ignore_indent {
 9792                    0
 9793                } else {
 9794                    snapshot.indent_size_for_line(row).len
 9795                };
 9796
 9797                let start = Point::new(row.0, indent_size);
 9798
 9799                let mut line_bytes = snapshot
 9800                    .bytes_in_range(start..snapshot.max_point())
 9801                    .flatten()
 9802                    .copied();
 9803
 9804                // If this line currently begins with the line comment prefix, then record
 9805                // the range containing the prefix.
 9806                if line_bytes
 9807                    .by_ref()
 9808                    .take(comment_prefix.len())
 9809                    .eq(comment_prefix.bytes())
 9810                {
 9811                    // Include any whitespace that matches the comment prefix.
 9812                    let matching_whitespace_len = line_bytes
 9813                        .zip(comment_prefix_whitespace.bytes())
 9814                        .take_while(|(a, b)| a == b)
 9815                        .count() as u32;
 9816                    let end = Point::new(
 9817                        start.row,
 9818                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9819                    );
 9820                    start..end
 9821                } else {
 9822                    start..start
 9823                }
 9824            }
 9825
 9826            fn comment_suffix_range(
 9827                snapshot: &MultiBufferSnapshot,
 9828                row: MultiBufferRow,
 9829                comment_suffix: &str,
 9830                comment_suffix_has_leading_space: bool,
 9831            ) -> Range<Point> {
 9832                let end = Point::new(row.0, snapshot.line_len(row));
 9833                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9834
 9835                let mut line_end_bytes = snapshot
 9836                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9837                    .flatten()
 9838                    .copied();
 9839
 9840                let leading_space_len = if suffix_start_column > 0
 9841                    && line_end_bytes.next() == Some(b' ')
 9842                    && comment_suffix_has_leading_space
 9843                {
 9844                    1
 9845                } else {
 9846                    0
 9847                };
 9848
 9849                // If this line currently begins with the line comment prefix, then record
 9850                // the range containing the prefix.
 9851                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9852                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9853                    start..end
 9854                } else {
 9855                    end..end
 9856                }
 9857            }
 9858
 9859            // TODO: Handle selections that cross excerpts
 9860            for selection in &mut selections {
 9861                let start_column = snapshot
 9862                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9863                    .len;
 9864                let language = if let Some(language) =
 9865                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9866                {
 9867                    language
 9868                } else {
 9869                    continue;
 9870                };
 9871
 9872                selection_edit_ranges.clear();
 9873
 9874                // If multiple selections contain a given row, avoid processing that
 9875                // row more than once.
 9876                let mut start_row = MultiBufferRow(selection.start.row);
 9877                if last_toggled_row == Some(start_row) {
 9878                    start_row = start_row.next_row();
 9879                }
 9880                let end_row =
 9881                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9882                        MultiBufferRow(selection.end.row - 1)
 9883                    } else {
 9884                        MultiBufferRow(selection.end.row)
 9885                    };
 9886                last_toggled_row = Some(end_row);
 9887
 9888                if start_row > end_row {
 9889                    continue;
 9890                }
 9891
 9892                // If the language has line comments, toggle those.
 9893                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9894
 9895                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9896                if ignore_indent {
 9897                    full_comment_prefixes = full_comment_prefixes
 9898                        .into_iter()
 9899                        .map(|s| Arc::from(s.trim_end()))
 9900                        .collect();
 9901                }
 9902
 9903                if !full_comment_prefixes.is_empty() {
 9904                    let first_prefix = full_comment_prefixes
 9905                        .first()
 9906                        .expect("prefixes is non-empty");
 9907                    let prefix_trimmed_lengths = full_comment_prefixes
 9908                        .iter()
 9909                        .map(|p| p.trim_end_matches(' ').len())
 9910                        .collect::<SmallVec<[usize; 4]>>();
 9911
 9912                    let mut all_selection_lines_are_comments = true;
 9913
 9914                    for row in start_row.0..=end_row.0 {
 9915                        let row = MultiBufferRow(row);
 9916                        if start_row < end_row && snapshot.is_line_blank(row) {
 9917                            continue;
 9918                        }
 9919
 9920                        let prefix_range = full_comment_prefixes
 9921                            .iter()
 9922                            .zip(prefix_trimmed_lengths.iter().copied())
 9923                            .map(|(prefix, trimmed_prefix_len)| {
 9924                                comment_prefix_range(
 9925                                    snapshot.deref(),
 9926                                    row,
 9927                                    &prefix[..trimmed_prefix_len],
 9928                                    &prefix[trimmed_prefix_len..],
 9929                                    ignore_indent,
 9930                                )
 9931                            })
 9932                            .max_by_key(|range| range.end.column - range.start.column)
 9933                            .expect("prefixes is non-empty");
 9934
 9935                        if prefix_range.is_empty() {
 9936                            all_selection_lines_are_comments = false;
 9937                        }
 9938
 9939                        selection_edit_ranges.push(prefix_range);
 9940                    }
 9941
 9942                    if all_selection_lines_are_comments {
 9943                        edits.extend(
 9944                            selection_edit_ranges
 9945                                .iter()
 9946                                .cloned()
 9947                                .map(|range| (range, empty_str.clone())),
 9948                        );
 9949                    } else {
 9950                        let min_column = selection_edit_ranges
 9951                            .iter()
 9952                            .map(|range| range.start.column)
 9953                            .min()
 9954                            .unwrap_or(0);
 9955                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9956                            let position = Point::new(range.start.row, min_column);
 9957                            (position..position, first_prefix.clone())
 9958                        }));
 9959                    }
 9960                } else if let Some((full_comment_prefix, comment_suffix)) =
 9961                    language.block_comment_delimiters()
 9962                {
 9963                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9964                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9965                    let prefix_range = comment_prefix_range(
 9966                        snapshot.deref(),
 9967                        start_row,
 9968                        comment_prefix,
 9969                        comment_prefix_whitespace,
 9970                        ignore_indent,
 9971                    );
 9972                    let suffix_range = comment_suffix_range(
 9973                        snapshot.deref(),
 9974                        end_row,
 9975                        comment_suffix.trim_start_matches(' '),
 9976                        comment_suffix.starts_with(' '),
 9977                    );
 9978
 9979                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9980                        edits.push((
 9981                            prefix_range.start..prefix_range.start,
 9982                            full_comment_prefix.clone(),
 9983                        ));
 9984                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9985                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9986                    } else {
 9987                        edits.push((prefix_range, empty_str.clone()));
 9988                        edits.push((suffix_range, empty_str.clone()));
 9989                    }
 9990                } else {
 9991                    continue;
 9992                }
 9993            }
 9994
 9995            drop(snapshot);
 9996            this.buffer.update(cx, |buffer, cx| {
 9997                buffer.edit(edits, None, cx);
 9998            });
 9999
10000            // Adjust selections so that they end before any comment suffixes that
10001            // were inserted.
10002            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10003            let mut selections = this.selections.all::<Point>(cx);
10004            let snapshot = this.buffer.read(cx).read(cx);
10005            for selection in &mut selections {
10006                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10007                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10008                        Ordering::Less => {
10009                            suffixes_inserted.next();
10010                            continue;
10011                        }
10012                        Ordering::Greater => break,
10013                        Ordering::Equal => {
10014                            if selection.end.column == snapshot.line_len(row) {
10015                                if selection.is_empty() {
10016                                    selection.start.column -= suffix_len as u32;
10017                                }
10018                                selection.end.column -= suffix_len as u32;
10019                            }
10020                            break;
10021                        }
10022                    }
10023                }
10024            }
10025
10026            drop(snapshot);
10027            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10028                s.select(selections)
10029            });
10030
10031            let selections = this.selections.all::<Point>(cx);
10032            let selections_on_single_row = selections.windows(2).all(|selections| {
10033                selections[0].start.row == selections[1].start.row
10034                    && selections[0].end.row == selections[1].end.row
10035                    && selections[0].start.row == selections[0].end.row
10036            });
10037            let selections_selecting = selections
10038                .iter()
10039                .any(|selection| selection.start != selection.end);
10040            let advance_downwards = action.advance_downwards
10041                && selections_on_single_row
10042                && !selections_selecting
10043                && !matches!(this.mode, EditorMode::SingleLine { .. });
10044
10045            if advance_downwards {
10046                let snapshot = this.buffer.read(cx).snapshot(cx);
10047
10048                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10049                    s.move_cursors_with(|display_snapshot, display_point, _| {
10050                        let mut point = display_point.to_point(display_snapshot);
10051                        point.row += 1;
10052                        point = snapshot.clip_point(point, Bias::Left);
10053                        let display_point = point.to_display_point(display_snapshot);
10054                        let goal = SelectionGoal::HorizontalPosition(
10055                            display_snapshot
10056                                .x_for_display_point(display_point, text_layout_details)
10057                                .into(),
10058                        );
10059                        (display_point, goal)
10060                    })
10061                });
10062            }
10063        });
10064    }
10065
10066    pub fn select_enclosing_symbol(
10067        &mut self,
10068        _: &SelectEnclosingSymbol,
10069        window: &mut Window,
10070        cx: &mut Context<Self>,
10071    ) {
10072        let buffer = self.buffer.read(cx).snapshot(cx);
10073        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10074
10075        fn update_selection(
10076            selection: &Selection<usize>,
10077            buffer_snap: &MultiBufferSnapshot,
10078        ) -> Option<Selection<usize>> {
10079            let cursor = selection.head();
10080            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10081            for symbol in symbols.iter().rev() {
10082                let start = symbol.range.start.to_offset(buffer_snap);
10083                let end = symbol.range.end.to_offset(buffer_snap);
10084                let new_range = start..end;
10085                if start < selection.start || end > selection.end {
10086                    return Some(Selection {
10087                        id: selection.id,
10088                        start: new_range.start,
10089                        end: new_range.end,
10090                        goal: SelectionGoal::None,
10091                        reversed: selection.reversed,
10092                    });
10093                }
10094            }
10095            None
10096        }
10097
10098        let mut selected_larger_symbol = false;
10099        let new_selections = old_selections
10100            .iter()
10101            .map(|selection| match update_selection(selection, &buffer) {
10102                Some(new_selection) => {
10103                    if new_selection.range() != selection.range() {
10104                        selected_larger_symbol = true;
10105                    }
10106                    new_selection
10107                }
10108                None => selection.clone(),
10109            })
10110            .collect::<Vec<_>>();
10111
10112        if selected_larger_symbol {
10113            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10114                s.select(new_selections);
10115            });
10116        }
10117    }
10118
10119    pub fn select_larger_syntax_node(
10120        &mut self,
10121        _: &SelectLargerSyntaxNode,
10122        window: &mut Window,
10123        cx: &mut Context<Self>,
10124    ) {
10125        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10126        let buffer = self.buffer.read(cx).snapshot(cx);
10127        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10128
10129        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10130        let mut selected_larger_node = false;
10131        let new_selections = old_selections
10132            .iter()
10133            .map(|selection| {
10134                let old_range = selection.start..selection.end;
10135                let mut new_range = old_range.clone();
10136                let mut new_node = None;
10137                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10138                {
10139                    new_node = Some(node);
10140                    new_range = containing_range;
10141                    if !display_map.intersects_fold(new_range.start)
10142                        && !display_map.intersects_fold(new_range.end)
10143                    {
10144                        break;
10145                    }
10146                }
10147
10148                if let Some(node) = new_node {
10149                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10150                    // nodes. Parent and grandparent are also logged because this operation will not
10151                    // visit nodes that have the same range as their parent.
10152                    log::info!("Node: {node:?}");
10153                    let parent = node.parent();
10154                    log::info!("Parent: {parent:?}");
10155                    let grandparent = parent.and_then(|x| x.parent());
10156                    log::info!("Grandparent: {grandparent:?}");
10157                }
10158
10159                selected_larger_node |= new_range != old_range;
10160                Selection {
10161                    id: selection.id,
10162                    start: new_range.start,
10163                    end: new_range.end,
10164                    goal: SelectionGoal::None,
10165                    reversed: selection.reversed,
10166                }
10167            })
10168            .collect::<Vec<_>>();
10169
10170        if selected_larger_node {
10171            stack.push(old_selections);
10172            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10173                s.select(new_selections);
10174            });
10175        }
10176        self.select_larger_syntax_node_stack = stack;
10177    }
10178
10179    pub fn select_smaller_syntax_node(
10180        &mut self,
10181        _: &SelectSmallerSyntaxNode,
10182        window: &mut Window,
10183        cx: &mut Context<Self>,
10184    ) {
10185        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10186        if let Some(selections) = stack.pop() {
10187            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10188                s.select(selections.to_vec());
10189            });
10190        }
10191        self.select_larger_syntax_node_stack = stack;
10192    }
10193
10194    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10195        if !EditorSettings::get_global(cx).gutter.runnables {
10196            self.clear_tasks();
10197            return Task::ready(());
10198        }
10199        let project = self.project.as_ref().map(Entity::downgrade);
10200        cx.spawn_in(window, |this, mut cx| async move {
10201            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10202            let Some(project) = project.and_then(|p| p.upgrade()) else {
10203                return;
10204            };
10205            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10206                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10207            }) else {
10208                return;
10209            };
10210
10211            let hide_runnables = project
10212                .update(&mut cx, |project, cx| {
10213                    // Do not display any test indicators in non-dev server remote projects.
10214                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10215                })
10216                .unwrap_or(true);
10217            if hide_runnables {
10218                return;
10219            }
10220            let new_rows =
10221                cx.background_spawn({
10222                    let snapshot = display_snapshot.clone();
10223                    async move {
10224                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10225                    }
10226                })
10227                    .await;
10228
10229            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10230            this.update(&mut cx, |this, _| {
10231                this.clear_tasks();
10232                for (key, value) in rows {
10233                    this.insert_tasks(key, value);
10234                }
10235            })
10236            .ok();
10237        })
10238    }
10239    fn fetch_runnable_ranges(
10240        snapshot: &DisplaySnapshot,
10241        range: Range<Anchor>,
10242    ) -> Vec<language::RunnableRange> {
10243        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10244    }
10245
10246    fn runnable_rows(
10247        project: Entity<Project>,
10248        snapshot: DisplaySnapshot,
10249        runnable_ranges: Vec<RunnableRange>,
10250        mut cx: AsyncWindowContext,
10251    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10252        runnable_ranges
10253            .into_iter()
10254            .filter_map(|mut runnable| {
10255                let tasks = cx
10256                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10257                    .ok()?;
10258                if tasks.is_empty() {
10259                    return None;
10260                }
10261
10262                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10263
10264                let row = snapshot
10265                    .buffer_snapshot
10266                    .buffer_line_for_row(MultiBufferRow(point.row))?
10267                    .1
10268                    .start
10269                    .row;
10270
10271                let context_range =
10272                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10273                Some((
10274                    (runnable.buffer_id, row),
10275                    RunnableTasks {
10276                        templates: tasks,
10277                        offset: MultiBufferOffset(runnable.run_range.start),
10278                        context_range,
10279                        column: point.column,
10280                        extra_variables: runnable.extra_captures,
10281                    },
10282                ))
10283            })
10284            .collect()
10285    }
10286
10287    fn templates_with_tags(
10288        project: &Entity<Project>,
10289        runnable: &mut Runnable,
10290        cx: &mut App,
10291    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10292        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10293            let (worktree_id, file) = project
10294                .buffer_for_id(runnable.buffer, cx)
10295                .and_then(|buffer| buffer.read(cx).file())
10296                .map(|file| (file.worktree_id(cx), file.clone()))
10297                .unzip();
10298
10299            (
10300                project.task_store().read(cx).task_inventory().cloned(),
10301                worktree_id,
10302                file,
10303            )
10304        });
10305
10306        let tags = mem::take(&mut runnable.tags);
10307        let mut tags: Vec<_> = tags
10308            .into_iter()
10309            .flat_map(|tag| {
10310                let tag = tag.0.clone();
10311                inventory
10312                    .as_ref()
10313                    .into_iter()
10314                    .flat_map(|inventory| {
10315                        inventory.read(cx).list_tasks(
10316                            file.clone(),
10317                            Some(runnable.language.clone()),
10318                            worktree_id,
10319                            cx,
10320                        )
10321                    })
10322                    .filter(move |(_, template)| {
10323                        template.tags.iter().any(|source_tag| source_tag == &tag)
10324                    })
10325            })
10326            .sorted_by_key(|(kind, _)| kind.to_owned())
10327            .collect();
10328        if let Some((leading_tag_source, _)) = tags.first() {
10329            // Strongest source wins; if we have worktree tag binding, prefer that to
10330            // global and language bindings;
10331            // if we have a global binding, prefer that to language binding.
10332            let first_mismatch = tags
10333                .iter()
10334                .position(|(tag_source, _)| tag_source != leading_tag_source);
10335            if let Some(index) = first_mismatch {
10336                tags.truncate(index);
10337            }
10338        }
10339
10340        tags
10341    }
10342
10343    pub fn move_to_enclosing_bracket(
10344        &mut self,
10345        _: &MoveToEnclosingBracket,
10346        window: &mut Window,
10347        cx: &mut Context<Self>,
10348    ) {
10349        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10350            s.move_offsets_with(|snapshot, selection| {
10351                let Some(enclosing_bracket_ranges) =
10352                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10353                else {
10354                    return;
10355                };
10356
10357                let mut best_length = usize::MAX;
10358                let mut best_inside = false;
10359                let mut best_in_bracket_range = false;
10360                let mut best_destination = None;
10361                for (open, close) in enclosing_bracket_ranges {
10362                    let close = close.to_inclusive();
10363                    let length = close.end() - open.start;
10364                    let inside = selection.start >= open.end && selection.end <= *close.start();
10365                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10366                        || close.contains(&selection.head());
10367
10368                    // If best is next to a bracket and current isn't, skip
10369                    if !in_bracket_range && best_in_bracket_range {
10370                        continue;
10371                    }
10372
10373                    // Prefer smaller lengths unless best is inside and current isn't
10374                    if length > best_length && (best_inside || !inside) {
10375                        continue;
10376                    }
10377
10378                    best_length = length;
10379                    best_inside = inside;
10380                    best_in_bracket_range = in_bracket_range;
10381                    best_destination = Some(
10382                        if close.contains(&selection.start) && close.contains(&selection.end) {
10383                            if inside {
10384                                open.end
10385                            } else {
10386                                open.start
10387                            }
10388                        } else if inside {
10389                            *close.start()
10390                        } else {
10391                            *close.end()
10392                        },
10393                    );
10394                }
10395
10396                if let Some(destination) = best_destination {
10397                    selection.collapse_to(destination, SelectionGoal::None);
10398                }
10399            })
10400        });
10401    }
10402
10403    pub fn undo_selection(
10404        &mut self,
10405        _: &UndoSelection,
10406        window: &mut Window,
10407        cx: &mut Context<Self>,
10408    ) {
10409        self.end_selection(window, cx);
10410        self.selection_history.mode = SelectionHistoryMode::Undoing;
10411        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10412            self.change_selections(None, window, cx, |s| {
10413                s.select_anchors(entry.selections.to_vec())
10414            });
10415            self.select_next_state = entry.select_next_state;
10416            self.select_prev_state = entry.select_prev_state;
10417            self.add_selections_state = entry.add_selections_state;
10418            self.request_autoscroll(Autoscroll::newest(), cx);
10419        }
10420        self.selection_history.mode = SelectionHistoryMode::Normal;
10421    }
10422
10423    pub fn redo_selection(
10424        &mut self,
10425        _: &RedoSelection,
10426        window: &mut Window,
10427        cx: &mut Context<Self>,
10428    ) {
10429        self.end_selection(window, cx);
10430        self.selection_history.mode = SelectionHistoryMode::Redoing;
10431        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10432            self.change_selections(None, window, cx, |s| {
10433                s.select_anchors(entry.selections.to_vec())
10434            });
10435            self.select_next_state = entry.select_next_state;
10436            self.select_prev_state = entry.select_prev_state;
10437            self.add_selections_state = entry.add_selections_state;
10438            self.request_autoscroll(Autoscroll::newest(), cx);
10439        }
10440        self.selection_history.mode = SelectionHistoryMode::Normal;
10441    }
10442
10443    pub fn expand_excerpts(
10444        &mut self,
10445        action: &ExpandExcerpts,
10446        _: &mut Window,
10447        cx: &mut Context<Self>,
10448    ) {
10449        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10450    }
10451
10452    pub fn expand_excerpts_down(
10453        &mut self,
10454        action: &ExpandExcerptsDown,
10455        _: &mut Window,
10456        cx: &mut Context<Self>,
10457    ) {
10458        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10459    }
10460
10461    pub fn expand_excerpts_up(
10462        &mut self,
10463        action: &ExpandExcerptsUp,
10464        _: &mut Window,
10465        cx: &mut Context<Self>,
10466    ) {
10467        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10468    }
10469
10470    pub fn expand_excerpts_for_direction(
10471        &mut self,
10472        lines: u32,
10473        direction: ExpandExcerptDirection,
10474
10475        cx: &mut Context<Self>,
10476    ) {
10477        let selections = self.selections.disjoint_anchors();
10478
10479        let lines = if lines == 0 {
10480            EditorSettings::get_global(cx).expand_excerpt_lines
10481        } else {
10482            lines
10483        };
10484
10485        self.buffer.update(cx, |buffer, cx| {
10486            let snapshot = buffer.snapshot(cx);
10487            let mut excerpt_ids = selections
10488                .iter()
10489                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10490                .collect::<Vec<_>>();
10491            excerpt_ids.sort();
10492            excerpt_ids.dedup();
10493            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10494        })
10495    }
10496
10497    pub fn expand_excerpt(
10498        &mut self,
10499        excerpt: ExcerptId,
10500        direction: ExpandExcerptDirection,
10501        cx: &mut Context<Self>,
10502    ) {
10503        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10504        self.buffer.update(cx, |buffer, cx| {
10505            buffer.expand_excerpts([excerpt], lines, direction, cx)
10506        })
10507    }
10508
10509    pub fn go_to_singleton_buffer_point(
10510        &mut self,
10511        point: Point,
10512        window: &mut Window,
10513        cx: &mut Context<Self>,
10514    ) {
10515        self.go_to_singleton_buffer_range(point..point, window, cx);
10516    }
10517
10518    pub fn go_to_singleton_buffer_range(
10519        &mut self,
10520        range: Range<Point>,
10521        window: &mut Window,
10522        cx: &mut Context<Self>,
10523    ) {
10524        let multibuffer = self.buffer().read(cx);
10525        let Some(buffer) = multibuffer.as_singleton() else {
10526            return;
10527        };
10528        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10529            return;
10530        };
10531        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10532            return;
10533        };
10534        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10535            s.select_anchor_ranges([start..end])
10536        });
10537    }
10538
10539    fn go_to_diagnostic(
10540        &mut self,
10541        _: &GoToDiagnostic,
10542        window: &mut Window,
10543        cx: &mut Context<Self>,
10544    ) {
10545        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10546    }
10547
10548    fn go_to_prev_diagnostic(
10549        &mut self,
10550        _: &GoToPrevDiagnostic,
10551        window: &mut Window,
10552        cx: &mut Context<Self>,
10553    ) {
10554        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10555    }
10556
10557    pub fn go_to_diagnostic_impl(
10558        &mut self,
10559        direction: Direction,
10560        window: &mut Window,
10561        cx: &mut Context<Self>,
10562    ) {
10563        let buffer = self.buffer.read(cx).snapshot(cx);
10564        let selection = self.selections.newest::<usize>(cx);
10565
10566        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10567        if direction == Direction::Next {
10568            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10569                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10570                    return;
10571                };
10572                self.activate_diagnostics(
10573                    buffer_id,
10574                    popover.local_diagnostic.diagnostic.group_id,
10575                    window,
10576                    cx,
10577                );
10578                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10579                    let primary_range_start = active_diagnostics.primary_range.start;
10580                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10581                        let mut new_selection = s.newest_anchor().clone();
10582                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10583                        s.select_anchors(vec![new_selection.clone()]);
10584                    });
10585                    self.refresh_inline_completion(false, true, window, cx);
10586                }
10587                return;
10588            }
10589        }
10590
10591        let active_group_id = self
10592            .active_diagnostics
10593            .as_ref()
10594            .map(|active_group| active_group.group_id);
10595        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10596            active_diagnostics
10597                .primary_range
10598                .to_offset(&buffer)
10599                .to_inclusive()
10600        });
10601        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10602            if active_primary_range.contains(&selection.head()) {
10603                *active_primary_range.start()
10604            } else {
10605                selection.head()
10606            }
10607        } else {
10608            selection.head()
10609        };
10610
10611        let snapshot = self.snapshot(window, cx);
10612        let primary_diagnostics_before = buffer
10613            .diagnostics_in_range::<usize>(0..search_start)
10614            .filter(|entry| entry.diagnostic.is_primary)
10615            .filter(|entry| entry.range.start != entry.range.end)
10616            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10617            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10618            .collect::<Vec<_>>();
10619        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10620            primary_diagnostics_before
10621                .iter()
10622                .position(|entry| entry.diagnostic.group_id == active_group_id)
10623        });
10624
10625        let primary_diagnostics_after = buffer
10626            .diagnostics_in_range::<usize>(search_start..buffer.len())
10627            .filter(|entry| entry.diagnostic.is_primary)
10628            .filter(|entry| entry.range.start != entry.range.end)
10629            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10630            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10631            .collect::<Vec<_>>();
10632        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10633            primary_diagnostics_after
10634                .iter()
10635                .enumerate()
10636                .rev()
10637                .find_map(|(i, entry)| {
10638                    if entry.diagnostic.group_id == active_group_id {
10639                        Some(i)
10640                    } else {
10641                        None
10642                    }
10643                })
10644        });
10645
10646        let next_primary_diagnostic = match direction {
10647            Direction::Prev => primary_diagnostics_before
10648                .iter()
10649                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10650                .rev()
10651                .next(),
10652            Direction::Next => primary_diagnostics_after
10653                .iter()
10654                .skip(
10655                    last_same_group_diagnostic_after
10656                        .map(|index| index + 1)
10657                        .unwrap_or(0),
10658                )
10659                .next(),
10660        };
10661
10662        // Cycle around to the start of the buffer, potentially moving back to the start of
10663        // the currently active diagnostic.
10664        let cycle_around = || match direction {
10665            Direction::Prev => primary_diagnostics_after
10666                .iter()
10667                .rev()
10668                .chain(primary_diagnostics_before.iter().rev())
10669                .next(),
10670            Direction::Next => primary_diagnostics_before
10671                .iter()
10672                .chain(primary_diagnostics_after.iter())
10673                .next(),
10674        };
10675
10676        if let Some((primary_range, group_id)) = next_primary_diagnostic
10677            .or_else(cycle_around)
10678            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10679        {
10680            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10681                return;
10682            };
10683            self.activate_diagnostics(buffer_id, group_id, window, cx);
10684            if self.active_diagnostics.is_some() {
10685                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10686                    s.select(vec![Selection {
10687                        id: selection.id,
10688                        start: primary_range.start,
10689                        end: primary_range.start,
10690                        reversed: false,
10691                        goal: SelectionGoal::None,
10692                    }]);
10693                });
10694                self.refresh_inline_completion(false, true, window, cx);
10695            }
10696        }
10697    }
10698
10699    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10700        let snapshot = self.snapshot(window, cx);
10701        let selection = self.selections.newest::<Point>(cx);
10702        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10703    }
10704
10705    fn go_to_hunk_after_position(
10706        &mut self,
10707        snapshot: &EditorSnapshot,
10708        position: Point,
10709        window: &mut Window,
10710        cx: &mut Context<Editor>,
10711    ) -> Option<MultiBufferDiffHunk> {
10712        let mut hunk = snapshot
10713            .buffer_snapshot
10714            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10715            .find(|hunk| hunk.row_range.start.0 > position.row);
10716        if hunk.is_none() {
10717            hunk = snapshot
10718                .buffer_snapshot
10719                .diff_hunks_in_range(Point::zero()..position)
10720                .find(|hunk| hunk.row_range.end.0 < position.row)
10721        }
10722        if let Some(hunk) = &hunk {
10723            let destination = Point::new(hunk.row_range.start.0, 0);
10724            self.unfold_ranges(&[destination..destination], false, false, cx);
10725            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10726                s.select_ranges(vec![destination..destination]);
10727            });
10728        }
10729
10730        hunk
10731    }
10732
10733    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10734        let snapshot = self.snapshot(window, cx);
10735        let selection = self.selections.newest::<Point>(cx);
10736        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10737    }
10738
10739    fn go_to_hunk_before_position(
10740        &mut self,
10741        snapshot: &EditorSnapshot,
10742        position: Point,
10743        window: &mut Window,
10744        cx: &mut Context<Editor>,
10745    ) -> Option<MultiBufferDiffHunk> {
10746        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10747        if hunk.is_none() {
10748            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10749        }
10750        if let Some(hunk) = &hunk {
10751            let destination = Point::new(hunk.row_range.start.0, 0);
10752            self.unfold_ranges(&[destination..destination], false, false, cx);
10753            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10754                s.select_ranges(vec![destination..destination]);
10755            });
10756        }
10757
10758        hunk
10759    }
10760
10761    pub fn go_to_definition(
10762        &mut self,
10763        _: &GoToDefinition,
10764        window: &mut Window,
10765        cx: &mut Context<Self>,
10766    ) -> Task<Result<Navigated>> {
10767        let definition =
10768            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10769        cx.spawn_in(window, |editor, mut cx| async move {
10770            if definition.await? == Navigated::Yes {
10771                return Ok(Navigated::Yes);
10772            }
10773            match editor.update_in(&mut cx, |editor, window, cx| {
10774                editor.find_all_references(&FindAllReferences, window, cx)
10775            })? {
10776                Some(references) => references.await,
10777                None => Ok(Navigated::No),
10778            }
10779        })
10780    }
10781
10782    pub fn go_to_declaration(
10783        &mut self,
10784        _: &GoToDeclaration,
10785        window: &mut Window,
10786        cx: &mut Context<Self>,
10787    ) -> Task<Result<Navigated>> {
10788        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10789    }
10790
10791    pub fn go_to_declaration_split(
10792        &mut self,
10793        _: &GoToDeclaration,
10794        window: &mut Window,
10795        cx: &mut Context<Self>,
10796    ) -> Task<Result<Navigated>> {
10797        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10798    }
10799
10800    pub fn go_to_implementation(
10801        &mut self,
10802        _: &GoToImplementation,
10803        window: &mut Window,
10804        cx: &mut Context<Self>,
10805    ) -> Task<Result<Navigated>> {
10806        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10807    }
10808
10809    pub fn go_to_implementation_split(
10810        &mut self,
10811        _: &GoToImplementationSplit,
10812        window: &mut Window,
10813        cx: &mut Context<Self>,
10814    ) -> Task<Result<Navigated>> {
10815        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10816    }
10817
10818    pub fn go_to_type_definition(
10819        &mut self,
10820        _: &GoToTypeDefinition,
10821        window: &mut Window,
10822        cx: &mut Context<Self>,
10823    ) -> Task<Result<Navigated>> {
10824        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10825    }
10826
10827    pub fn go_to_definition_split(
10828        &mut self,
10829        _: &GoToDefinitionSplit,
10830        window: &mut Window,
10831        cx: &mut Context<Self>,
10832    ) -> Task<Result<Navigated>> {
10833        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10834    }
10835
10836    pub fn go_to_type_definition_split(
10837        &mut self,
10838        _: &GoToTypeDefinitionSplit,
10839        window: &mut Window,
10840        cx: &mut Context<Self>,
10841    ) -> Task<Result<Navigated>> {
10842        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10843    }
10844
10845    fn go_to_definition_of_kind(
10846        &mut self,
10847        kind: GotoDefinitionKind,
10848        split: bool,
10849        window: &mut Window,
10850        cx: &mut Context<Self>,
10851    ) -> Task<Result<Navigated>> {
10852        let Some(provider) = self.semantics_provider.clone() else {
10853            return Task::ready(Ok(Navigated::No));
10854        };
10855        let head = self.selections.newest::<usize>(cx).head();
10856        let buffer = self.buffer.read(cx);
10857        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10858            text_anchor
10859        } else {
10860            return Task::ready(Ok(Navigated::No));
10861        };
10862
10863        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10864            return Task::ready(Ok(Navigated::No));
10865        };
10866
10867        cx.spawn_in(window, |editor, mut cx| async move {
10868            let definitions = definitions.await?;
10869            let navigated = editor
10870                .update_in(&mut cx, |editor, window, cx| {
10871                    editor.navigate_to_hover_links(
10872                        Some(kind),
10873                        definitions
10874                            .into_iter()
10875                            .filter(|location| {
10876                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10877                            })
10878                            .map(HoverLink::Text)
10879                            .collect::<Vec<_>>(),
10880                        split,
10881                        window,
10882                        cx,
10883                    )
10884                })?
10885                .await?;
10886            anyhow::Ok(navigated)
10887        })
10888    }
10889
10890    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10891        let selection = self.selections.newest_anchor();
10892        let head = selection.head();
10893        let tail = selection.tail();
10894
10895        let Some((buffer, start_position)) =
10896            self.buffer.read(cx).text_anchor_for_position(head, cx)
10897        else {
10898            return;
10899        };
10900
10901        let end_position = if head != tail {
10902            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10903                return;
10904            };
10905            Some(pos)
10906        } else {
10907            None
10908        };
10909
10910        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10911            let url = if let Some(end_pos) = end_position {
10912                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10913            } else {
10914                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10915            };
10916
10917            if let Some(url) = url {
10918                editor.update(&mut cx, |_, cx| {
10919                    cx.open_url(&url);
10920                })
10921            } else {
10922                Ok(())
10923            }
10924        });
10925
10926        url_finder.detach();
10927    }
10928
10929    pub fn open_selected_filename(
10930        &mut self,
10931        _: &OpenSelectedFilename,
10932        window: &mut Window,
10933        cx: &mut Context<Self>,
10934    ) {
10935        let Some(workspace) = self.workspace() else {
10936            return;
10937        };
10938
10939        let position = self.selections.newest_anchor().head();
10940
10941        let Some((buffer, buffer_position)) =
10942            self.buffer.read(cx).text_anchor_for_position(position, cx)
10943        else {
10944            return;
10945        };
10946
10947        let project = self.project.clone();
10948
10949        cx.spawn_in(window, |_, mut cx| async move {
10950            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10951
10952            if let Some((_, path)) = result {
10953                workspace
10954                    .update_in(&mut cx, |workspace, window, cx| {
10955                        workspace.open_resolved_path(path, window, cx)
10956                    })?
10957                    .await?;
10958            }
10959            anyhow::Ok(())
10960        })
10961        .detach();
10962    }
10963
10964    pub(crate) fn navigate_to_hover_links(
10965        &mut self,
10966        kind: Option<GotoDefinitionKind>,
10967        mut definitions: Vec<HoverLink>,
10968        split: bool,
10969        window: &mut Window,
10970        cx: &mut Context<Editor>,
10971    ) -> Task<Result<Navigated>> {
10972        // If there is one definition, just open it directly
10973        if definitions.len() == 1 {
10974            let definition = definitions.pop().unwrap();
10975
10976            enum TargetTaskResult {
10977                Location(Option<Location>),
10978                AlreadyNavigated,
10979            }
10980
10981            let target_task = match definition {
10982                HoverLink::Text(link) => {
10983                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10984                }
10985                HoverLink::InlayHint(lsp_location, server_id) => {
10986                    let computation =
10987                        self.compute_target_location(lsp_location, server_id, window, cx);
10988                    cx.background_spawn(async move {
10989                        let location = computation.await?;
10990                        Ok(TargetTaskResult::Location(location))
10991                    })
10992                }
10993                HoverLink::Url(url) => {
10994                    cx.open_url(&url);
10995                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10996                }
10997                HoverLink::File(path) => {
10998                    if let Some(workspace) = self.workspace() {
10999                        cx.spawn_in(window, |_, mut cx| async move {
11000                            workspace
11001                                .update_in(&mut cx, |workspace, window, cx| {
11002                                    workspace.open_resolved_path(path, window, cx)
11003                                })?
11004                                .await
11005                                .map(|_| TargetTaskResult::AlreadyNavigated)
11006                        })
11007                    } else {
11008                        Task::ready(Ok(TargetTaskResult::Location(None)))
11009                    }
11010                }
11011            };
11012            cx.spawn_in(window, |editor, mut cx| async move {
11013                let target = match target_task.await.context("target resolution task")? {
11014                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11015                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11016                    TargetTaskResult::Location(Some(target)) => target,
11017                };
11018
11019                editor.update_in(&mut cx, |editor, window, cx| {
11020                    let Some(workspace) = editor.workspace() else {
11021                        return Navigated::No;
11022                    };
11023                    let pane = workspace.read(cx).active_pane().clone();
11024
11025                    let range = target.range.to_point(target.buffer.read(cx));
11026                    let range = editor.range_for_match(&range);
11027                    let range = collapse_multiline_range(range);
11028
11029                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11030                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11031                    } else {
11032                        window.defer(cx, move |window, cx| {
11033                            let target_editor: Entity<Self> =
11034                                workspace.update(cx, |workspace, cx| {
11035                                    let pane = if split {
11036                                        workspace.adjacent_pane(window, cx)
11037                                    } else {
11038                                        workspace.active_pane().clone()
11039                                    };
11040
11041                                    workspace.open_project_item(
11042                                        pane,
11043                                        target.buffer.clone(),
11044                                        true,
11045                                        true,
11046                                        window,
11047                                        cx,
11048                                    )
11049                                });
11050                            target_editor.update(cx, |target_editor, cx| {
11051                                // When selecting a definition in a different buffer, disable the nav history
11052                                // to avoid creating a history entry at the previous cursor location.
11053                                pane.update(cx, |pane, _| pane.disable_history());
11054                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11055                                pane.update(cx, |pane, _| pane.enable_history());
11056                            });
11057                        });
11058                    }
11059                    Navigated::Yes
11060                })
11061            })
11062        } else if !definitions.is_empty() {
11063            cx.spawn_in(window, |editor, mut cx| async move {
11064                let (title, location_tasks, workspace) = editor
11065                    .update_in(&mut cx, |editor, window, cx| {
11066                        let tab_kind = match kind {
11067                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11068                            _ => "Definitions",
11069                        };
11070                        let title = definitions
11071                            .iter()
11072                            .find_map(|definition| match definition {
11073                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11074                                    let buffer = origin.buffer.read(cx);
11075                                    format!(
11076                                        "{} for {}",
11077                                        tab_kind,
11078                                        buffer
11079                                            .text_for_range(origin.range.clone())
11080                                            .collect::<String>()
11081                                    )
11082                                }),
11083                                HoverLink::InlayHint(_, _) => None,
11084                                HoverLink::Url(_) => None,
11085                                HoverLink::File(_) => None,
11086                            })
11087                            .unwrap_or(tab_kind.to_string());
11088                        let location_tasks = definitions
11089                            .into_iter()
11090                            .map(|definition| match definition {
11091                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11092                                HoverLink::InlayHint(lsp_location, server_id) => editor
11093                                    .compute_target_location(lsp_location, server_id, window, cx),
11094                                HoverLink::Url(_) => Task::ready(Ok(None)),
11095                                HoverLink::File(_) => Task::ready(Ok(None)),
11096                            })
11097                            .collect::<Vec<_>>();
11098                        (title, location_tasks, editor.workspace().clone())
11099                    })
11100                    .context("location tasks preparation")?;
11101
11102                let locations = future::join_all(location_tasks)
11103                    .await
11104                    .into_iter()
11105                    .filter_map(|location| location.transpose())
11106                    .collect::<Result<_>>()
11107                    .context("location tasks")?;
11108
11109                let Some(workspace) = workspace else {
11110                    return Ok(Navigated::No);
11111                };
11112                let opened = workspace
11113                    .update_in(&mut cx, |workspace, window, cx| {
11114                        Self::open_locations_in_multibuffer(
11115                            workspace,
11116                            locations,
11117                            title,
11118                            split,
11119                            MultibufferSelectionMode::First,
11120                            window,
11121                            cx,
11122                        )
11123                    })
11124                    .ok();
11125
11126                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11127            })
11128        } else {
11129            Task::ready(Ok(Navigated::No))
11130        }
11131    }
11132
11133    fn compute_target_location(
11134        &self,
11135        lsp_location: lsp::Location,
11136        server_id: LanguageServerId,
11137        window: &mut Window,
11138        cx: &mut Context<Self>,
11139    ) -> Task<anyhow::Result<Option<Location>>> {
11140        let Some(project) = self.project.clone() else {
11141            return Task::ready(Ok(None));
11142        };
11143
11144        cx.spawn_in(window, move |editor, mut cx| async move {
11145            let location_task = editor.update(&mut cx, |_, cx| {
11146                project.update(cx, |project, cx| {
11147                    let language_server_name = project
11148                        .language_server_statuses(cx)
11149                        .find(|(id, _)| server_id == *id)
11150                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11151                    language_server_name.map(|language_server_name| {
11152                        project.open_local_buffer_via_lsp(
11153                            lsp_location.uri.clone(),
11154                            server_id,
11155                            language_server_name,
11156                            cx,
11157                        )
11158                    })
11159                })
11160            })?;
11161            let location = match location_task {
11162                Some(task) => Some({
11163                    let target_buffer_handle = task.await.context("open local buffer")?;
11164                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11165                        let target_start = target_buffer
11166                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11167                        let target_end = target_buffer
11168                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11169                        target_buffer.anchor_after(target_start)
11170                            ..target_buffer.anchor_before(target_end)
11171                    })?;
11172                    Location {
11173                        buffer: target_buffer_handle,
11174                        range,
11175                    }
11176                }),
11177                None => None,
11178            };
11179            Ok(location)
11180        })
11181    }
11182
11183    pub fn find_all_references(
11184        &mut self,
11185        _: &FindAllReferences,
11186        window: &mut Window,
11187        cx: &mut Context<Self>,
11188    ) -> Option<Task<Result<Navigated>>> {
11189        let selection = self.selections.newest::<usize>(cx);
11190        let multi_buffer = self.buffer.read(cx);
11191        let head = selection.head();
11192
11193        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11194        let head_anchor = multi_buffer_snapshot.anchor_at(
11195            head,
11196            if head < selection.tail() {
11197                Bias::Right
11198            } else {
11199                Bias::Left
11200            },
11201        );
11202
11203        match self
11204            .find_all_references_task_sources
11205            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11206        {
11207            Ok(_) => {
11208                log::info!(
11209                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11210                );
11211                return None;
11212            }
11213            Err(i) => {
11214                self.find_all_references_task_sources.insert(i, head_anchor);
11215            }
11216        }
11217
11218        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11219        let workspace = self.workspace()?;
11220        let project = workspace.read(cx).project().clone();
11221        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11222        Some(cx.spawn_in(window, |editor, mut cx| async move {
11223            let _cleanup = defer({
11224                let mut cx = cx.clone();
11225                move || {
11226                    let _ = editor.update(&mut cx, |editor, _| {
11227                        if let Ok(i) =
11228                            editor
11229                                .find_all_references_task_sources
11230                                .binary_search_by(|anchor| {
11231                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11232                                })
11233                        {
11234                            editor.find_all_references_task_sources.remove(i);
11235                        }
11236                    });
11237                }
11238            });
11239
11240            let locations = references.await?;
11241            if locations.is_empty() {
11242                return anyhow::Ok(Navigated::No);
11243            }
11244
11245            workspace.update_in(&mut cx, |workspace, window, cx| {
11246                let title = locations
11247                    .first()
11248                    .as_ref()
11249                    .map(|location| {
11250                        let buffer = location.buffer.read(cx);
11251                        format!(
11252                            "References to `{}`",
11253                            buffer
11254                                .text_for_range(location.range.clone())
11255                                .collect::<String>()
11256                        )
11257                    })
11258                    .unwrap();
11259                Self::open_locations_in_multibuffer(
11260                    workspace,
11261                    locations,
11262                    title,
11263                    false,
11264                    MultibufferSelectionMode::First,
11265                    window,
11266                    cx,
11267                );
11268                Navigated::Yes
11269            })
11270        }))
11271    }
11272
11273    /// Opens a multibuffer with the given project locations in it
11274    pub fn open_locations_in_multibuffer(
11275        workspace: &mut Workspace,
11276        mut locations: Vec<Location>,
11277        title: String,
11278        split: bool,
11279        multibuffer_selection_mode: MultibufferSelectionMode,
11280        window: &mut Window,
11281        cx: &mut Context<Workspace>,
11282    ) {
11283        // If there are multiple definitions, open them in a multibuffer
11284        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11285        let mut locations = locations.into_iter().peekable();
11286        let mut ranges = Vec::new();
11287        let capability = workspace.project().read(cx).capability();
11288
11289        let excerpt_buffer = cx.new(|cx| {
11290            let mut multibuffer = MultiBuffer::new(capability);
11291            while let Some(location) = locations.next() {
11292                let buffer = location.buffer.read(cx);
11293                let mut ranges_for_buffer = Vec::new();
11294                let range = location.range.to_offset(buffer);
11295                ranges_for_buffer.push(range.clone());
11296
11297                while let Some(next_location) = locations.peek() {
11298                    if next_location.buffer == location.buffer {
11299                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11300                        locations.next();
11301                    } else {
11302                        break;
11303                    }
11304                }
11305
11306                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11307                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11308                    location.buffer.clone(),
11309                    ranges_for_buffer,
11310                    DEFAULT_MULTIBUFFER_CONTEXT,
11311                    cx,
11312                ))
11313            }
11314
11315            multibuffer.with_title(title)
11316        });
11317
11318        let editor = cx.new(|cx| {
11319            Editor::for_multibuffer(
11320                excerpt_buffer,
11321                Some(workspace.project().clone()),
11322                true,
11323                window,
11324                cx,
11325            )
11326        });
11327        editor.update(cx, |editor, cx| {
11328            match multibuffer_selection_mode {
11329                MultibufferSelectionMode::First => {
11330                    if let Some(first_range) = ranges.first() {
11331                        editor.change_selections(None, window, cx, |selections| {
11332                            selections.clear_disjoint();
11333                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11334                        });
11335                    }
11336                    editor.highlight_background::<Self>(
11337                        &ranges,
11338                        |theme| theme.editor_highlighted_line_background,
11339                        cx,
11340                    );
11341                }
11342                MultibufferSelectionMode::All => {
11343                    editor.change_selections(None, window, cx, |selections| {
11344                        selections.clear_disjoint();
11345                        selections.select_anchor_ranges(ranges);
11346                    });
11347                }
11348            }
11349            editor.register_buffers_with_language_servers(cx);
11350        });
11351
11352        let item = Box::new(editor);
11353        let item_id = item.item_id();
11354
11355        if split {
11356            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11357        } else {
11358            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11359                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11360                    pane.close_current_preview_item(window, cx)
11361                } else {
11362                    None
11363                }
11364            });
11365            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11366        }
11367        workspace.active_pane().update(cx, |pane, cx| {
11368            pane.set_preview_item_id(Some(item_id), cx);
11369        });
11370    }
11371
11372    pub fn rename(
11373        &mut self,
11374        _: &Rename,
11375        window: &mut Window,
11376        cx: &mut Context<Self>,
11377    ) -> Option<Task<Result<()>>> {
11378        use language::ToOffset as _;
11379
11380        let provider = self.semantics_provider.clone()?;
11381        let selection = self.selections.newest_anchor().clone();
11382        let (cursor_buffer, cursor_buffer_position) = self
11383            .buffer
11384            .read(cx)
11385            .text_anchor_for_position(selection.head(), cx)?;
11386        let (tail_buffer, cursor_buffer_position_end) = self
11387            .buffer
11388            .read(cx)
11389            .text_anchor_for_position(selection.tail(), cx)?;
11390        if tail_buffer != cursor_buffer {
11391            return None;
11392        }
11393
11394        let snapshot = cursor_buffer.read(cx).snapshot();
11395        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11396        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11397        let prepare_rename = provider
11398            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11399            .unwrap_or_else(|| Task::ready(Ok(None)));
11400        drop(snapshot);
11401
11402        Some(cx.spawn_in(window, |this, mut cx| async move {
11403            let rename_range = if let Some(range) = prepare_rename.await? {
11404                Some(range)
11405            } else {
11406                this.update(&mut cx, |this, cx| {
11407                    let buffer = this.buffer.read(cx).snapshot(cx);
11408                    let mut buffer_highlights = this
11409                        .document_highlights_for_position(selection.head(), &buffer)
11410                        .filter(|highlight| {
11411                            highlight.start.excerpt_id == selection.head().excerpt_id
11412                                && highlight.end.excerpt_id == selection.head().excerpt_id
11413                        });
11414                    buffer_highlights
11415                        .next()
11416                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11417                })?
11418            };
11419            if let Some(rename_range) = rename_range {
11420                this.update_in(&mut cx, |this, window, cx| {
11421                    let snapshot = cursor_buffer.read(cx).snapshot();
11422                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11423                    let cursor_offset_in_rename_range =
11424                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11425                    let cursor_offset_in_rename_range_end =
11426                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11427
11428                    this.take_rename(false, window, cx);
11429                    let buffer = this.buffer.read(cx).read(cx);
11430                    let cursor_offset = selection.head().to_offset(&buffer);
11431                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11432                    let rename_end = rename_start + rename_buffer_range.len();
11433                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11434                    let mut old_highlight_id = None;
11435                    let old_name: Arc<str> = buffer
11436                        .chunks(rename_start..rename_end, true)
11437                        .map(|chunk| {
11438                            if old_highlight_id.is_none() {
11439                                old_highlight_id = chunk.syntax_highlight_id;
11440                            }
11441                            chunk.text
11442                        })
11443                        .collect::<String>()
11444                        .into();
11445
11446                    drop(buffer);
11447
11448                    // Position the selection in the rename editor so that it matches the current selection.
11449                    this.show_local_selections = false;
11450                    let rename_editor = cx.new(|cx| {
11451                        let mut editor = Editor::single_line(window, cx);
11452                        editor.buffer.update(cx, |buffer, cx| {
11453                            buffer.edit([(0..0, old_name.clone())], None, cx)
11454                        });
11455                        let rename_selection_range = match cursor_offset_in_rename_range
11456                            .cmp(&cursor_offset_in_rename_range_end)
11457                        {
11458                            Ordering::Equal => {
11459                                editor.select_all(&SelectAll, window, cx);
11460                                return editor;
11461                            }
11462                            Ordering::Less => {
11463                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11464                            }
11465                            Ordering::Greater => {
11466                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11467                            }
11468                        };
11469                        if rename_selection_range.end > old_name.len() {
11470                            editor.select_all(&SelectAll, window, cx);
11471                        } else {
11472                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11473                                s.select_ranges([rename_selection_range]);
11474                            });
11475                        }
11476                        editor
11477                    });
11478                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11479                        if e == &EditorEvent::Focused {
11480                            cx.emit(EditorEvent::FocusedIn)
11481                        }
11482                    })
11483                    .detach();
11484
11485                    let write_highlights =
11486                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11487                    let read_highlights =
11488                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11489                    let ranges = write_highlights
11490                        .iter()
11491                        .flat_map(|(_, ranges)| ranges.iter())
11492                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11493                        .cloned()
11494                        .collect();
11495
11496                    this.highlight_text::<Rename>(
11497                        ranges,
11498                        HighlightStyle {
11499                            fade_out: Some(0.6),
11500                            ..Default::default()
11501                        },
11502                        cx,
11503                    );
11504                    let rename_focus_handle = rename_editor.focus_handle(cx);
11505                    window.focus(&rename_focus_handle);
11506                    let block_id = this.insert_blocks(
11507                        [BlockProperties {
11508                            style: BlockStyle::Flex,
11509                            placement: BlockPlacement::Below(range.start),
11510                            height: 1,
11511                            render: Arc::new({
11512                                let rename_editor = rename_editor.clone();
11513                                move |cx: &mut BlockContext| {
11514                                    let mut text_style = cx.editor_style.text.clone();
11515                                    if let Some(highlight_style) = old_highlight_id
11516                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11517                                    {
11518                                        text_style = text_style.highlight(highlight_style);
11519                                    }
11520                                    div()
11521                                        .block_mouse_down()
11522                                        .pl(cx.anchor_x)
11523                                        .child(EditorElement::new(
11524                                            &rename_editor,
11525                                            EditorStyle {
11526                                                background: cx.theme().system().transparent,
11527                                                local_player: cx.editor_style.local_player,
11528                                                text: text_style,
11529                                                scrollbar_width: cx.editor_style.scrollbar_width,
11530                                                syntax: cx.editor_style.syntax.clone(),
11531                                                status: cx.editor_style.status.clone(),
11532                                                inlay_hints_style: HighlightStyle {
11533                                                    font_weight: Some(FontWeight::BOLD),
11534                                                    ..make_inlay_hints_style(cx.app)
11535                                                },
11536                                                inline_completion_styles: make_suggestion_styles(
11537                                                    cx.app,
11538                                                ),
11539                                                ..EditorStyle::default()
11540                                            },
11541                                        ))
11542                                        .into_any_element()
11543                                }
11544                            }),
11545                            priority: 0,
11546                        }],
11547                        Some(Autoscroll::fit()),
11548                        cx,
11549                    )[0];
11550                    this.pending_rename = Some(RenameState {
11551                        range,
11552                        old_name,
11553                        editor: rename_editor,
11554                        block_id,
11555                    });
11556                })?;
11557            }
11558
11559            Ok(())
11560        }))
11561    }
11562
11563    pub fn confirm_rename(
11564        &mut self,
11565        _: &ConfirmRename,
11566        window: &mut Window,
11567        cx: &mut Context<Self>,
11568    ) -> Option<Task<Result<()>>> {
11569        let rename = self.take_rename(false, window, cx)?;
11570        let workspace = self.workspace()?.downgrade();
11571        let (buffer, start) = self
11572            .buffer
11573            .read(cx)
11574            .text_anchor_for_position(rename.range.start, cx)?;
11575        let (end_buffer, _) = self
11576            .buffer
11577            .read(cx)
11578            .text_anchor_for_position(rename.range.end, cx)?;
11579        if buffer != end_buffer {
11580            return None;
11581        }
11582
11583        let old_name = rename.old_name;
11584        let new_name = rename.editor.read(cx).text(cx);
11585
11586        let rename = self.semantics_provider.as_ref()?.perform_rename(
11587            &buffer,
11588            start,
11589            new_name.clone(),
11590            cx,
11591        )?;
11592
11593        Some(cx.spawn_in(window, |editor, mut cx| async move {
11594            let project_transaction = rename.await?;
11595            Self::open_project_transaction(
11596                &editor,
11597                workspace,
11598                project_transaction,
11599                format!("Rename: {}{}", old_name, new_name),
11600                cx.clone(),
11601            )
11602            .await?;
11603
11604            editor.update(&mut cx, |editor, cx| {
11605                editor.refresh_document_highlights(cx);
11606            })?;
11607            Ok(())
11608        }))
11609    }
11610
11611    fn take_rename(
11612        &mut self,
11613        moving_cursor: bool,
11614        window: &mut Window,
11615        cx: &mut Context<Self>,
11616    ) -> Option<RenameState> {
11617        let rename = self.pending_rename.take()?;
11618        if rename.editor.focus_handle(cx).is_focused(window) {
11619            window.focus(&self.focus_handle);
11620        }
11621
11622        self.remove_blocks(
11623            [rename.block_id].into_iter().collect(),
11624            Some(Autoscroll::fit()),
11625            cx,
11626        );
11627        self.clear_highlights::<Rename>(cx);
11628        self.show_local_selections = true;
11629
11630        if moving_cursor {
11631            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11632                editor.selections.newest::<usize>(cx).head()
11633            });
11634
11635            // Update the selection to match the position of the selection inside
11636            // the rename editor.
11637            let snapshot = self.buffer.read(cx).read(cx);
11638            let rename_range = rename.range.to_offset(&snapshot);
11639            let cursor_in_editor = snapshot
11640                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11641                .min(rename_range.end);
11642            drop(snapshot);
11643
11644            self.change_selections(None, window, cx, |s| {
11645                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11646            });
11647        } else {
11648            self.refresh_document_highlights(cx);
11649        }
11650
11651        Some(rename)
11652    }
11653
11654    pub fn pending_rename(&self) -> Option<&RenameState> {
11655        self.pending_rename.as_ref()
11656    }
11657
11658    fn format(
11659        &mut self,
11660        _: &Format,
11661        window: &mut Window,
11662        cx: &mut Context<Self>,
11663    ) -> Option<Task<Result<()>>> {
11664        let project = match &self.project {
11665            Some(project) => project.clone(),
11666            None => return None,
11667        };
11668
11669        Some(self.perform_format(
11670            project,
11671            FormatTrigger::Manual,
11672            FormatTarget::Buffers,
11673            window,
11674            cx,
11675        ))
11676    }
11677
11678    fn format_selections(
11679        &mut self,
11680        _: &FormatSelections,
11681        window: &mut Window,
11682        cx: &mut Context<Self>,
11683    ) -> Option<Task<Result<()>>> {
11684        let project = match &self.project {
11685            Some(project) => project.clone(),
11686            None => return None,
11687        };
11688
11689        let ranges = self
11690            .selections
11691            .all_adjusted(cx)
11692            .into_iter()
11693            .map(|selection| selection.range())
11694            .collect_vec();
11695
11696        Some(self.perform_format(
11697            project,
11698            FormatTrigger::Manual,
11699            FormatTarget::Ranges(ranges),
11700            window,
11701            cx,
11702        ))
11703    }
11704
11705    fn perform_format(
11706        &mut self,
11707        project: Entity<Project>,
11708        trigger: FormatTrigger,
11709        target: FormatTarget,
11710        window: &mut Window,
11711        cx: &mut Context<Self>,
11712    ) -> Task<Result<()>> {
11713        let buffer = self.buffer.clone();
11714        let (buffers, target) = match target {
11715            FormatTarget::Buffers => {
11716                let mut buffers = buffer.read(cx).all_buffers();
11717                if trigger == FormatTrigger::Save {
11718                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11719                }
11720                (buffers, LspFormatTarget::Buffers)
11721            }
11722            FormatTarget::Ranges(selection_ranges) => {
11723                let multi_buffer = buffer.read(cx);
11724                let snapshot = multi_buffer.read(cx);
11725                let mut buffers = HashSet::default();
11726                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11727                    BTreeMap::new();
11728                for selection_range in selection_ranges {
11729                    for (buffer, buffer_range, _) in
11730                        snapshot.range_to_buffer_ranges(selection_range)
11731                    {
11732                        let buffer_id = buffer.remote_id();
11733                        let start = buffer.anchor_before(buffer_range.start);
11734                        let end = buffer.anchor_after(buffer_range.end);
11735                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11736                        buffer_id_to_ranges
11737                            .entry(buffer_id)
11738                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11739                            .or_insert_with(|| vec![start..end]);
11740                    }
11741                }
11742                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11743            }
11744        };
11745
11746        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11747        let format = project.update(cx, |project, cx| {
11748            project.format(buffers, target, true, trigger, cx)
11749        });
11750
11751        cx.spawn_in(window, |_, mut cx| async move {
11752            let transaction = futures::select_biased! {
11753                () = timeout => {
11754                    log::warn!("timed out waiting for formatting");
11755                    None
11756                }
11757                transaction = format.log_err().fuse() => transaction,
11758            };
11759
11760            buffer
11761                .update(&mut cx, |buffer, cx| {
11762                    if let Some(transaction) = transaction {
11763                        if !buffer.is_singleton() {
11764                            buffer.push_transaction(&transaction.0, cx);
11765                        }
11766                    }
11767
11768                    cx.notify();
11769                })
11770                .ok();
11771
11772            Ok(())
11773        })
11774    }
11775
11776    fn restart_language_server(
11777        &mut self,
11778        _: &RestartLanguageServer,
11779        _: &mut Window,
11780        cx: &mut Context<Self>,
11781    ) {
11782        if let Some(project) = self.project.clone() {
11783            self.buffer.update(cx, |multi_buffer, cx| {
11784                project.update(cx, |project, cx| {
11785                    project.restart_language_servers_for_buffers(
11786                        multi_buffer.all_buffers().into_iter().collect(),
11787                        cx,
11788                    );
11789                });
11790            })
11791        }
11792    }
11793
11794    fn cancel_language_server_work(
11795        workspace: &mut Workspace,
11796        _: &actions::CancelLanguageServerWork,
11797        _: &mut Window,
11798        cx: &mut Context<Workspace>,
11799    ) {
11800        let project = workspace.project();
11801        let buffers = workspace
11802            .active_item(cx)
11803            .and_then(|item| item.act_as::<Editor>(cx))
11804            .map_or(HashSet::default(), |editor| {
11805                editor.read(cx).buffer.read(cx).all_buffers()
11806            });
11807        project.update(cx, |project, cx| {
11808            project.cancel_language_server_work_for_buffers(buffers, cx);
11809        });
11810    }
11811
11812    fn show_character_palette(
11813        &mut self,
11814        _: &ShowCharacterPalette,
11815        window: &mut Window,
11816        _: &mut Context<Self>,
11817    ) {
11818        window.show_character_palette();
11819    }
11820
11821    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11822        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11823            let buffer = self.buffer.read(cx).snapshot(cx);
11824            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11825            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11826            let is_valid = buffer
11827                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11828                .any(|entry| {
11829                    entry.diagnostic.is_primary
11830                        && !entry.range.is_empty()
11831                        && entry.range.start == primary_range_start
11832                        && entry.diagnostic.message == active_diagnostics.primary_message
11833                });
11834
11835            if is_valid != active_diagnostics.is_valid {
11836                active_diagnostics.is_valid = is_valid;
11837                let mut new_styles = HashMap::default();
11838                for (block_id, diagnostic) in &active_diagnostics.blocks {
11839                    new_styles.insert(
11840                        *block_id,
11841                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11842                    );
11843                }
11844                self.display_map.update(cx, |display_map, _cx| {
11845                    display_map.replace_blocks(new_styles)
11846                });
11847            }
11848        }
11849    }
11850
11851    fn activate_diagnostics(
11852        &mut self,
11853        buffer_id: BufferId,
11854        group_id: usize,
11855        window: &mut Window,
11856        cx: &mut Context<Self>,
11857    ) {
11858        self.dismiss_diagnostics(cx);
11859        let snapshot = self.snapshot(window, cx);
11860        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11861            let buffer = self.buffer.read(cx).snapshot(cx);
11862
11863            let mut primary_range = None;
11864            let mut primary_message = None;
11865            let diagnostic_group = buffer
11866                .diagnostic_group(buffer_id, group_id)
11867                .filter_map(|entry| {
11868                    let start = entry.range.start;
11869                    let end = entry.range.end;
11870                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11871                        && (start.row == end.row
11872                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11873                    {
11874                        return None;
11875                    }
11876                    if entry.diagnostic.is_primary {
11877                        primary_range = Some(entry.range.clone());
11878                        primary_message = Some(entry.diagnostic.message.clone());
11879                    }
11880                    Some(entry)
11881                })
11882                .collect::<Vec<_>>();
11883            let primary_range = primary_range?;
11884            let primary_message = primary_message?;
11885
11886            let blocks = display_map
11887                .insert_blocks(
11888                    diagnostic_group.iter().map(|entry| {
11889                        let diagnostic = entry.diagnostic.clone();
11890                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11891                        BlockProperties {
11892                            style: BlockStyle::Fixed,
11893                            placement: BlockPlacement::Below(
11894                                buffer.anchor_after(entry.range.start),
11895                            ),
11896                            height: message_height,
11897                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11898                            priority: 0,
11899                        }
11900                    }),
11901                    cx,
11902                )
11903                .into_iter()
11904                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11905                .collect();
11906
11907            Some(ActiveDiagnosticGroup {
11908                primary_range: buffer.anchor_before(primary_range.start)
11909                    ..buffer.anchor_after(primary_range.end),
11910                primary_message,
11911                group_id,
11912                blocks,
11913                is_valid: true,
11914            })
11915        });
11916    }
11917
11918    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11919        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11920            self.display_map.update(cx, |display_map, cx| {
11921                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11922            });
11923            cx.notify();
11924        }
11925    }
11926
11927    pub fn set_selections_from_remote(
11928        &mut self,
11929        selections: Vec<Selection<Anchor>>,
11930        pending_selection: Option<Selection<Anchor>>,
11931        window: &mut Window,
11932        cx: &mut Context<Self>,
11933    ) {
11934        let old_cursor_position = self.selections.newest_anchor().head();
11935        self.selections.change_with(cx, |s| {
11936            s.select_anchors(selections);
11937            if let Some(pending_selection) = pending_selection {
11938                s.set_pending(pending_selection, SelectMode::Character);
11939            } else {
11940                s.clear_pending();
11941            }
11942        });
11943        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11944    }
11945
11946    fn push_to_selection_history(&mut self) {
11947        self.selection_history.push(SelectionHistoryEntry {
11948            selections: self.selections.disjoint_anchors(),
11949            select_next_state: self.select_next_state.clone(),
11950            select_prev_state: self.select_prev_state.clone(),
11951            add_selections_state: self.add_selections_state.clone(),
11952        });
11953    }
11954
11955    pub fn transact(
11956        &mut self,
11957        window: &mut Window,
11958        cx: &mut Context<Self>,
11959        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11960    ) -> Option<TransactionId> {
11961        self.start_transaction_at(Instant::now(), window, cx);
11962        update(self, window, cx);
11963        self.end_transaction_at(Instant::now(), cx)
11964    }
11965
11966    pub fn start_transaction_at(
11967        &mut self,
11968        now: Instant,
11969        window: &mut Window,
11970        cx: &mut Context<Self>,
11971    ) {
11972        self.end_selection(window, cx);
11973        if let Some(tx_id) = self
11974            .buffer
11975            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11976        {
11977            self.selection_history
11978                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11979            cx.emit(EditorEvent::TransactionBegun {
11980                transaction_id: tx_id,
11981            })
11982        }
11983    }
11984
11985    pub fn end_transaction_at(
11986        &mut self,
11987        now: Instant,
11988        cx: &mut Context<Self>,
11989    ) -> Option<TransactionId> {
11990        if let Some(transaction_id) = self
11991            .buffer
11992            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11993        {
11994            if let Some((_, end_selections)) =
11995                self.selection_history.transaction_mut(transaction_id)
11996            {
11997                *end_selections = Some(self.selections.disjoint_anchors());
11998            } else {
11999                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12000            }
12001
12002            cx.emit(EditorEvent::Edited { transaction_id });
12003            Some(transaction_id)
12004        } else {
12005            None
12006        }
12007    }
12008
12009    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12010        if self.selection_mark_mode {
12011            self.change_selections(None, window, cx, |s| {
12012                s.move_with(|_, sel| {
12013                    sel.collapse_to(sel.head(), SelectionGoal::None);
12014                });
12015            })
12016        }
12017        self.selection_mark_mode = true;
12018        cx.notify();
12019    }
12020
12021    pub fn swap_selection_ends(
12022        &mut self,
12023        _: &actions::SwapSelectionEnds,
12024        window: &mut Window,
12025        cx: &mut Context<Self>,
12026    ) {
12027        self.change_selections(None, window, cx, |s| {
12028            s.move_with(|_, sel| {
12029                if sel.start != sel.end {
12030                    sel.reversed = !sel.reversed
12031                }
12032            });
12033        });
12034        self.request_autoscroll(Autoscroll::newest(), cx);
12035        cx.notify();
12036    }
12037
12038    pub fn toggle_fold(
12039        &mut self,
12040        _: &actions::ToggleFold,
12041        window: &mut Window,
12042        cx: &mut Context<Self>,
12043    ) {
12044        if self.is_singleton(cx) {
12045            let selection = self.selections.newest::<Point>(cx);
12046
12047            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12048            let range = if selection.is_empty() {
12049                let point = selection.head().to_display_point(&display_map);
12050                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12051                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12052                    .to_point(&display_map);
12053                start..end
12054            } else {
12055                selection.range()
12056            };
12057            if display_map.folds_in_range(range).next().is_some() {
12058                self.unfold_lines(&Default::default(), window, cx)
12059            } else {
12060                self.fold(&Default::default(), window, cx)
12061            }
12062        } else {
12063            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12064            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12065                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12066                .map(|(snapshot, _, _)| snapshot.remote_id())
12067                .collect();
12068
12069            for buffer_id in buffer_ids {
12070                if self.is_buffer_folded(buffer_id, cx) {
12071                    self.unfold_buffer(buffer_id, cx);
12072                } else {
12073                    self.fold_buffer(buffer_id, cx);
12074                }
12075            }
12076        }
12077    }
12078
12079    pub fn toggle_fold_recursive(
12080        &mut self,
12081        _: &actions::ToggleFoldRecursive,
12082        window: &mut Window,
12083        cx: &mut Context<Self>,
12084    ) {
12085        let selection = self.selections.newest::<Point>(cx);
12086
12087        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12088        let range = if selection.is_empty() {
12089            let point = selection.head().to_display_point(&display_map);
12090            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12091            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12092                .to_point(&display_map);
12093            start..end
12094        } else {
12095            selection.range()
12096        };
12097        if display_map.folds_in_range(range).next().is_some() {
12098            self.unfold_recursive(&Default::default(), window, cx)
12099        } else {
12100            self.fold_recursive(&Default::default(), window, cx)
12101        }
12102    }
12103
12104    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12105        if self.is_singleton(cx) {
12106            let mut to_fold = Vec::new();
12107            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12108            let selections = self.selections.all_adjusted(cx);
12109
12110            for selection in selections {
12111                let range = selection.range().sorted();
12112                let buffer_start_row = range.start.row;
12113
12114                if range.start.row != range.end.row {
12115                    let mut found = false;
12116                    let mut row = range.start.row;
12117                    while row <= range.end.row {
12118                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12119                        {
12120                            found = true;
12121                            row = crease.range().end.row + 1;
12122                            to_fold.push(crease);
12123                        } else {
12124                            row += 1
12125                        }
12126                    }
12127                    if found {
12128                        continue;
12129                    }
12130                }
12131
12132                for row in (0..=range.start.row).rev() {
12133                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12134                        if crease.range().end.row >= buffer_start_row {
12135                            to_fold.push(crease);
12136                            if row <= range.start.row {
12137                                break;
12138                            }
12139                        }
12140                    }
12141                }
12142            }
12143
12144            self.fold_creases(to_fold, true, window, cx);
12145        } else {
12146            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12147
12148            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12149                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12150                .map(|(snapshot, _, _)| snapshot.remote_id())
12151                .collect();
12152            for buffer_id in buffer_ids {
12153                self.fold_buffer(buffer_id, cx);
12154            }
12155        }
12156    }
12157
12158    fn fold_at_level(
12159        &mut self,
12160        fold_at: &FoldAtLevel,
12161        window: &mut Window,
12162        cx: &mut Context<Self>,
12163    ) {
12164        if !self.buffer.read(cx).is_singleton() {
12165            return;
12166        }
12167
12168        let fold_at_level = fold_at.0;
12169        let snapshot = self.buffer.read(cx).snapshot(cx);
12170        let mut to_fold = Vec::new();
12171        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12172
12173        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12174            while start_row < end_row {
12175                match self
12176                    .snapshot(window, cx)
12177                    .crease_for_buffer_row(MultiBufferRow(start_row))
12178                {
12179                    Some(crease) => {
12180                        let nested_start_row = crease.range().start.row + 1;
12181                        let nested_end_row = crease.range().end.row;
12182
12183                        if current_level < fold_at_level {
12184                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12185                        } else if current_level == fold_at_level {
12186                            to_fold.push(crease);
12187                        }
12188
12189                        start_row = nested_end_row + 1;
12190                    }
12191                    None => start_row += 1,
12192                }
12193            }
12194        }
12195
12196        self.fold_creases(to_fold, true, window, cx);
12197    }
12198
12199    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12200        if self.buffer.read(cx).is_singleton() {
12201            let mut fold_ranges = Vec::new();
12202            let snapshot = self.buffer.read(cx).snapshot(cx);
12203
12204            for row in 0..snapshot.max_row().0 {
12205                if let Some(foldable_range) = self
12206                    .snapshot(window, cx)
12207                    .crease_for_buffer_row(MultiBufferRow(row))
12208                {
12209                    fold_ranges.push(foldable_range);
12210                }
12211            }
12212
12213            self.fold_creases(fold_ranges, true, window, cx);
12214        } else {
12215            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12216                editor
12217                    .update_in(&mut cx, |editor, _, cx| {
12218                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12219                            editor.fold_buffer(buffer_id, cx);
12220                        }
12221                    })
12222                    .ok();
12223            });
12224        }
12225    }
12226
12227    pub fn fold_function_bodies(
12228        &mut self,
12229        _: &actions::FoldFunctionBodies,
12230        window: &mut Window,
12231        cx: &mut Context<Self>,
12232    ) {
12233        let snapshot = self.buffer.read(cx).snapshot(cx);
12234
12235        let ranges = snapshot
12236            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12237            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12238            .collect::<Vec<_>>();
12239
12240        let creases = ranges
12241            .into_iter()
12242            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12243            .collect();
12244
12245        self.fold_creases(creases, true, window, cx);
12246    }
12247
12248    pub fn fold_recursive(
12249        &mut self,
12250        _: &actions::FoldRecursive,
12251        window: &mut Window,
12252        cx: &mut Context<Self>,
12253    ) {
12254        let mut to_fold = Vec::new();
12255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12256        let selections = self.selections.all_adjusted(cx);
12257
12258        for selection in selections {
12259            let range = selection.range().sorted();
12260            let buffer_start_row = range.start.row;
12261
12262            if range.start.row != range.end.row {
12263                let mut found = false;
12264                for row in range.start.row..=range.end.row {
12265                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12266                        found = true;
12267                        to_fold.push(crease);
12268                    }
12269                }
12270                if found {
12271                    continue;
12272                }
12273            }
12274
12275            for row in (0..=range.start.row).rev() {
12276                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12277                    if crease.range().end.row >= buffer_start_row {
12278                        to_fold.push(crease);
12279                    } else {
12280                        break;
12281                    }
12282                }
12283            }
12284        }
12285
12286        self.fold_creases(to_fold, true, window, cx);
12287    }
12288
12289    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12290        let buffer_row = fold_at.buffer_row;
12291        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12292
12293        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12294            let autoscroll = self
12295                .selections
12296                .all::<Point>(cx)
12297                .iter()
12298                .any(|selection| crease.range().overlaps(&selection.range()));
12299
12300            self.fold_creases(vec![crease], autoscroll, window, cx);
12301        }
12302    }
12303
12304    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12305        if self.is_singleton(cx) {
12306            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12307            let buffer = &display_map.buffer_snapshot;
12308            let selections = self.selections.all::<Point>(cx);
12309            let ranges = selections
12310                .iter()
12311                .map(|s| {
12312                    let range = s.display_range(&display_map).sorted();
12313                    let mut start = range.start.to_point(&display_map);
12314                    let mut end = range.end.to_point(&display_map);
12315                    start.column = 0;
12316                    end.column = buffer.line_len(MultiBufferRow(end.row));
12317                    start..end
12318                })
12319                .collect::<Vec<_>>();
12320
12321            self.unfold_ranges(&ranges, true, true, cx);
12322        } else {
12323            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12324            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12325                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12326                .map(|(snapshot, _, _)| snapshot.remote_id())
12327                .collect();
12328            for buffer_id in buffer_ids {
12329                self.unfold_buffer(buffer_id, cx);
12330            }
12331        }
12332    }
12333
12334    pub fn unfold_recursive(
12335        &mut self,
12336        _: &UnfoldRecursive,
12337        _window: &mut Window,
12338        cx: &mut Context<Self>,
12339    ) {
12340        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12341        let selections = self.selections.all::<Point>(cx);
12342        let ranges = selections
12343            .iter()
12344            .map(|s| {
12345                let mut range = s.display_range(&display_map).sorted();
12346                *range.start.column_mut() = 0;
12347                *range.end.column_mut() = display_map.line_len(range.end.row());
12348                let start = range.start.to_point(&display_map);
12349                let end = range.end.to_point(&display_map);
12350                start..end
12351            })
12352            .collect::<Vec<_>>();
12353
12354        self.unfold_ranges(&ranges, true, true, cx);
12355    }
12356
12357    pub fn unfold_at(
12358        &mut self,
12359        unfold_at: &UnfoldAt,
12360        _window: &mut Window,
12361        cx: &mut Context<Self>,
12362    ) {
12363        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12364
12365        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12366            ..Point::new(
12367                unfold_at.buffer_row.0,
12368                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12369            );
12370
12371        let autoscroll = self
12372            .selections
12373            .all::<Point>(cx)
12374            .iter()
12375            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12376
12377        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12378    }
12379
12380    pub fn unfold_all(
12381        &mut self,
12382        _: &actions::UnfoldAll,
12383        _window: &mut Window,
12384        cx: &mut Context<Self>,
12385    ) {
12386        if self.buffer.read(cx).is_singleton() {
12387            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12388            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12389        } else {
12390            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12391                editor
12392                    .update(&mut cx, |editor, cx| {
12393                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12394                            editor.unfold_buffer(buffer_id, cx);
12395                        }
12396                    })
12397                    .ok();
12398            });
12399        }
12400    }
12401
12402    pub fn fold_selected_ranges(
12403        &mut self,
12404        _: &FoldSelectedRanges,
12405        window: &mut Window,
12406        cx: &mut Context<Self>,
12407    ) {
12408        let selections = self.selections.all::<Point>(cx);
12409        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12410        let line_mode = self.selections.line_mode;
12411        let ranges = selections
12412            .into_iter()
12413            .map(|s| {
12414                if line_mode {
12415                    let start = Point::new(s.start.row, 0);
12416                    let end = Point::new(
12417                        s.end.row,
12418                        display_map
12419                            .buffer_snapshot
12420                            .line_len(MultiBufferRow(s.end.row)),
12421                    );
12422                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12423                } else {
12424                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12425                }
12426            })
12427            .collect::<Vec<_>>();
12428        self.fold_creases(ranges, true, window, cx);
12429    }
12430
12431    pub fn fold_ranges<T: ToOffset + Clone>(
12432        &mut self,
12433        ranges: Vec<Range<T>>,
12434        auto_scroll: bool,
12435        window: &mut Window,
12436        cx: &mut Context<Self>,
12437    ) {
12438        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12439        let ranges = ranges
12440            .into_iter()
12441            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12442            .collect::<Vec<_>>();
12443        self.fold_creases(ranges, auto_scroll, window, cx);
12444    }
12445
12446    pub fn fold_creases<T: ToOffset + Clone>(
12447        &mut self,
12448        creases: Vec<Crease<T>>,
12449        auto_scroll: bool,
12450        window: &mut Window,
12451        cx: &mut Context<Self>,
12452    ) {
12453        if creases.is_empty() {
12454            return;
12455        }
12456
12457        let mut buffers_affected = HashSet::default();
12458        let multi_buffer = self.buffer().read(cx);
12459        for crease in &creases {
12460            if let Some((_, buffer, _)) =
12461                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12462            {
12463                buffers_affected.insert(buffer.read(cx).remote_id());
12464            };
12465        }
12466
12467        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12468
12469        if auto_scroll {
12470            self.request_autoscroll(Autoscroll::fit(), cx);
12471        }
12472
12473        cx.notify();
12474
12475        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12476            // Clear diagnostics block when folding a range that contains it.
12477            let snapshot = self.snapshot(window, cx);
12478            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12479                drop(snapshot);
12480                self.active_diagnostics = Some(active_diagnostics);
12481                self.dismiss_diagnostics(cx);
12482            } else {
12483                self.active_diagnostics = Some(active_diagnostics);
12484            }
12485        }
12486
12487        self.scrollbar_marker_state.dirty = true;
12488    }
12489
12490    /// Removes any folds whose ranges intersect any of the given ranges.
12491    pub fn unfold_ranges<T: ToOffset + Clone>(
12492        &mut self,
12493        ranges: &[Range<T>],
12494        inclusive: bool,
12495        auto_scroll: bool,
12496        cx: &mut Context<Self>,
12497    ) {
12498        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12499            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12500        });
12501    }
12502
12503    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12504        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12505            return;
12506        }
12507        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12508        self.display_map
12509            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12510        cx.emit(EditorEvent::BufferFoldToggled {
12511            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12512            folded: true,
12513        });
12514        cx.notify();
12515    }
12516
12517    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12518        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12519            return;
12520        }
12521        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12522        self.display_map.update(cx, |display_map, cx| {
12523            display_map.unfold_buffer(buffer_id, cx);
12524        });
12525        cx.emit(EditorEvent::BufferFoldToggled {
12526            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12527            folded: false,
12528        });
12529        cx.notify();
12530    }
12531
12532    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12533        self.display_map.read(cx).is_buffer_folded(buffer)
12534    }
12535
12536    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12537        self.display_map.read(cx).folded_buffers()
12538    }
12539
12540    /// Removes any folds with the given ranges.
12541    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12542        &mut self,
12543        ranges: &[Range<T>],
12544        type_id: TypeId,
12545        auto_scroll: bool,
12546        cx: &mut Context<Self>,
12547    ) {
12548        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12549            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12550        });
12551    }
12552
12553    fn remove_folds_with<T: ToOffset + Clone>(
12554        &mut self,
12555        ranges: &[Range<T>],
12556        auto_scroll: bool,
12557        cx: &mut Context<Self>,
12558        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12559    ) {
12560        if ranges.is_empty() {
12561            return;
12562        }
12563
12564        let mut buffers_affected = HashSet::default();
12565        let multi_buffer = self.buffer().read(cx);
12566        for range in ranges {
12567            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12568                buffers_affected.insert(buffer.read(cx).remote_id());
12569            };
12570        }
12571
12572        self.display_map.update(cx, update);
12573
12574        if auto_scroll {
12575            self.request_autoscroll(Autoscroll::fit(), cx);
12576        }
12577
12578        cx.notify();
12579        self.scrollbar_marker_state.dirty = true;
12580        self.active_indent_guides_state.dirty = true;
12581    }
12582
12583    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12584        self.display_map.read(cx).fold_placeholder.clone()
12585    }
12586
12587    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12588        self.buffer.update(cx, |buffer, cx| {
12589            buffer.set_all_diff_hunks_expanded(cx);
12590        });
12591    }
12592
12593    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12594        self.distinguish_unstaged_diff_hunks = true;
12595    }
12596
12597    pub fn expand_all_diff_hunks(
12598        &mut self,
12599        _: &ExpandAllHunkDiffs,
12600        _window: &mut Window,
12601        cx: &mut Context<Self>,
12602    ) {
12603        self.buffer.update(cx, |buffer, cx| {
12604            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12605        });
12606    }
12607
12608    pub fn toggle_selected_diff_hunks(
12609        &mut self,
12610        _: &ToggleSelectedDiffHunks,
12611        _window: &mut Window,
12612        cx: &mut Context<Self>,
12613    ) {
12614        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12615        self.toggle_diff_hunks_in_ranges(ranges, cx);
12616    }
12617
12618    fn diff_hunks_in_ranges<'a>(
12619        &'a self,
12620        ranges: &'a [Range<Anchor>],
12621        buffer: &'a MultiBufferSnapshot,
12622    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12623        ranges.iter().flat_map(move |range| {
12624            let end_excerpt_id = range.end.excerpt_id;
12625            let range = range.to_point(buffer);
12626            let mut peek_end = range.end;
12627            if range.end.row < buffer.max_row().0 {
12628                peek_end = Point::new(range.end.row + 1, 0);
12629            }
12630            buffer
12631                .diff_hunks_in_range(range.start..peek_end)
12632                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12633        })
12634    }
12635
12636    pub fn has_stageable_diff_hunks_in_ranges(
12637        &self,
12638        ranges: &[Range<Anchor>],
12639        snapshot: &MultiBufferSnapshot,
12640    ) -> bool {
12641        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12642        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12643    }
12644
12645    pub fn toggle_staged_selected_diff_hunks(
12646        &mut self,
12647        _: &ToggleStagedSelectedDiffHunks,
12648        _window: &mut Window,
12649        cx: &mut Context<Self>,
12650    ) {
12651        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12652        self.stage_or_unstage_diff_hunks(&ranges, cx);
12653    }
12654
12655    pub fn stage_or_unstage_diff_hunks(
12656        &mut self,
12657        ranges: &[Range<Anchor>],
12658        cx: &mut Context<Self>,
12659    ) {
12660        let Some(project) = &self.project else {
12661            return;
12662        };
12663        let snapshot = self.buffer.read(cx).snapshot(cx);
12664        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12665
12666        let chunk_by = self
12667            .diff_hunks_in_ranges(&ranges, &snapshot)
12668            .chunk_by(|hunk| hunk.buffer_id);
12669        for (buffer_id, hunks) in &chunk_by {
12670            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12671                log::debug!("no buffer for id");
12672                continue;
12673            };
12674            let buffer = buffer.read(cx).snapshot();
12675            let Some((repo, path)) = project
12676                .read(cx)
12677                .repository_and_path_for_buffer_id(buffer_id, cx)
12678            else {
12679                log::debug!("no git repo for buffer id");
12680                continue;
12681            };
12682            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12683                log::debug!("no diff for buffer id");
12684                continue;
12685            };
12686            let Some(secondary_diff) = diff.secondary_diff() else {
12687                log::debug!("no secondary diff for buffer id");
12688                continue;
12689            };
12690
12691            let edits = diff.secondary_edits_for_stage_or_unstage(
12692                stage,
12693                hunks.map(|hunk| {
12694                    (
12695                        hunk.diff_base_byte_range.clone(),
12696                        hunk.secondary_diff_base_byte_range.clone(),
12697                        hunk.buffer_range.clone(),
12698                    )
12699                }),
12700                &buffer,
12701            );
12702
12703            let index_base = secondary_diff.base_text().map_or_else(
12704                || Rope::from(""),
12705                |snapshot| snapshot.text.as_rope().clone(),
12706            );
12707            let index_buffer = cx.new(|cx| {
12708                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12709            });
12710            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12711                index_buffer.edit(edits, None, cx);
12712                index_buffer.snapshot().as_rope().to_string()
12713            });
12714            let new_index_text = if new_index_text.is_empty()
12715                && (diff.is_single_insertion
12716                    || buffer
12717                        .file()
12718                        .map_or(false, |file| file.disk_state() == DiskState::New))
12719            {
12720                log::debug!("removing from index");
12721                None
12722            } else {
12723                Some(new_index_text)
12724            };
12725
12726            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12727        }
12728    }
12729
12730    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12731        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12732        self.buffer
12733            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12734    }
12735
12736    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12737        self.buffer.update(cx, |buffer, cx| {
12738            let ranges = vec![Anchor::min()..Anchor::max()];
12739            if !buffer.all_diff_hunks_expanded()
12740                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12741            {
12742                buffer.collapse_diff_hunks(ranges, cx);
12743                true
12744            } else {
12745                false
12746            }
12747        })
12748    }
12749
12750    fn toggle_diff_hunks_in_ranges(
12751        &mut self,
12752        ranges: Vec<Range<Anchor>>,
12753        cx: &mut Context<'_, Editor>,
12754    ) {
12755        self.buffer.update(cx, |buffer, cx| {
12756            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12757            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12758        })
12759    }
12760
12761    fn toggle_diff_hunks_in_ranges_narrow(
12762        &mut self,
12763        ranges: Vec<Range<Anchor>>,
12764        cx: &mut Context<'_, Editor>,
12765    ) {
12766        self.buffer.update(cx, |buffer, cx| {
12767            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12768            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12769        })
12770    }
12771
12772    pub(crate) fn apply_all_diff_hunks(
12773        &mut self,
12774        _: &ApplyAllDiffHunks,
12775        window: &mut Window,
12776        cx: &mut Context<Self>,
12777    ) {
12778        let buffers = self.buffer.read(cx).all_buffers();
12779        for branch_buffer in buffers {
12780            branch_buffer.update(cx, |branch_buffer, cx| {
12781                branch_buffer.merge_into_base(Vec::new(), cx);
12782            });
12783        }
12784
12785        if let Some(project) = self.project.clone() {
12786            self.save(true, project, window, cx).detach_and_log_err(cx);
12787        }
12788    }
12789
12790    pub(crate) fn apply_selected_diff_hunks(
12791        &mut self,
12792        _: &ApplyDiffHunk,
12793        window: &mut Window,
12794        cx: &mut Context<Self>,
12795    ) {
12796        let snapshot = self.snapshot(window, cx);
12797        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12798        let mut ranges_by_buffer = HashMap::default();
12799        self.transact(window, cx, |editor, _window, cx| {
12800            for hunk in hunks {
12801                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12802                    ranges_by_buffer
12803                        .entry(buffer.clone())
12804                        .or_insert_with(Vec::new)
12805                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12806                }
12807            }
12808
12809            for (buffer, ranges) in ranges_by_buffer {
12810                buffer.update(cx, |buffer, cx| {
12811                    buffer.merge_into_base(ranges, cx);
12812                });
12813            }
12814        });
12815
12816        if let Some(project) = self.project.clone() {
12817            self.save(true, project, window, cx).detach_and_log_err(cx);
12818        }
12819    }
12820
12821    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12822        if hovered != self.gutter_hovered {
12823            self.gutter_hovered = hovered;
12824            cx.notify();
12825        }
12826    }
12827
12828    pub fn insert_blocks(
12829        &mut self,
12830        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12831        autoscroll: Option<Autoscroll>,
12832        cx: &mut Context<Self>,
12833    ) -> Vec<CustomBlockId> {
12834        let blocks = self
12835            .display_map
12836            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12837        if let Some(autoscroll) = autoscroll {
12838            self.request_autoscroll(autoscroll, cx);
12839        }
12840        cx.notify();
12841        blocks
12842    }
12843
12844    pub fn resize_blocks(
12845        &mut self,
12846        heights: HashMap<CustomBlockId, u32>,
12847        autoscroll: Option<Autoscroll>,
12848        cx: &mut Context<Self>,
12849    ) {
12850        self.display_map
12851            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12852        if let Some(autoscroll) = autoscroll {
12853            self.request_autoscroll(autoscroll, cx);
12854        }
12855        cx.notify();
12856    }
12857
12858    pub fn replace_blocks(
12859        &mut self,
12860        renderers: HashMap<CustomBlockId, RenderBlock>,
12861        autoscroll: Option<Autoscroll>,
12862        cx: &mut Context<Self>,
12863    ) {
12864        self.display_map
12865            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12866        if let Some(autoscroll) = autoscroll {
12867            self.request_autoscroll(autoscroll, cx);
12868        }
12869        cx.notify();
12870    }
12871
12872    pub fn remove_blocks(
12873        &mut self,
12874        block_ids: HashSet<CustomBlockId>,
12875        autoscroll: Option<Autoscroll>,
12876        cx: &mut Context<Self>,
12877    ) {
12878        self.display_map.update(cx, |display_map, cx| {
12879            display_map.remove_blocks(block_ids, cx)
12880        });
12881        if let Some(autoscroll) = autoscroll {
12882            self.request_autoscroll(autoscroll, cx);
12883        }
12884        cx.notify();
12885    }
12886
12887    pub fn row_for_block(
12888        &self,
12889        block_id: CustomBlockId,
12890        cx: &mut Context<Self>,
12891    ) -> Option<DisplayRow> {
12892        self.display_map
12893            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12894    }
12895
12896    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12897        self.focused_block = Some(focused_block);
12898    }
12899
12900    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12901        self.focused_block.take()
12902    }
12903
12904    pub fn insert_creases(
12905        &mut self,
12906        creases: impl IntoIterator<Item = Crease<Anchor>>,
12907        cx: &mut Context<Self>,
12908    ) -> Vec<CreaseId> {
12909        self.display_map
12910            .update(cx, |map, cx| map.insert_creases(creases, cx))
12911    }
12912
12913    pub fn remove_creases(
12914        &mut self,
12915        ids: impl IntoIterator<Item = CreaseId>,
12916        cx: &mut Context<Self>,
12917    ) {
12918        self.display_map
12919            .update(cx, |map, cx| map.remove_creases(ids, cx));
12920    }
12921
12922    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12923        self.display_map
12924            .update(cx, |map, cx| map.snapshot(cx))
12925            .longest_row()
12926    }
12927
12928    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12929        self.display_map
12930            .update(cx, |map, cx| map.snapshot(cx))
12931            .max_point()
12932    }
12933
12934    pub fn text(&self, cx: &App) -> String {
12935        self.buffer.read(cx).read(cx).text()
12936    }
12937
12938    pub fn is_empty(&self, cx: &App) -> bool {
12939        self.buffer.read(cx).read(cx).is_empty()
12940    }
12941
12942    pub fn text_option(&self, cx: &App) -> Option<String> {
12943        let text = self.text(cx);
12944        let text = text.trim();
12945
12946        if text.is_empty() {
12947            return None;
12948        }
12949
12950        Some(text.to_string())
12951    }
12952
12953    pub fn set_text(
12954        &mut self,
12955        text: impl Into<Arc<str>>,
12956        window: &mut Window,
12957        cx: &mut Context<Self>,
12958    ) {
12959        self.transact(window, cx, |this, _, cx| {
12960            this.buffer
12961                .read(cx)
12962                .as_singleton()
12963                .expect("you can only call set_text on editors for singleton buffers")
12964                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12965        });
12966    }
12967
12968    pub fn display_text(&self, cx: &mut App) -> String {
12969        self.display_map
12970            .update(cx, |map, cx| map.snapshot(cx))
12971            .text()
12972    }
12973
12974    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12975        let mut wrap_guides = smallvec::smallvec![];
12976
12977        if self.show_wrap_guides == Some(false) {
12978            return wrap_guides;
12979        }
12980
12981        let settings = self.buffer.read(cx).settings_at(0, cx);
12982        if settings.show_wrap_guides {
12983            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12984                wrap_guides.push((soft_wrap as usize, true));
12985            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12986                wrap_guides.push((soft_wrap as usize, true));
12987            }
12988            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12989        }
12990
12991        wrap_guides
12992    }
12993
12994    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12995        let settings = self.buffer.read(cx).settings_at(0, cx);
12996        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12997        match mode {
12998            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12999                SoftWrap::None
13000            }
13001            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13002            language_settings::SoftWrap::PreferredLineLength => {
13003                SoftWrap::Column(settings.preferred_line_length)
13004            }
13005            language_settings::SoftWrap::Bounded => {
13006                SoftWrap::Bounded(settings.preferred_line_length)
13007            }
13008        }
13009    }
13010
13011    pub fn set_soft_wrap_mode(
13012        &mut self,
13013        mode: language_settings::SoftWrap,
13014
13015        cx: &mut Context<Self>,
13016    ) {
13017        self.soft_wrap_mode_override = Some(mode);
13018        cx.notify();
13019    }
13020
13021    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13022        self.text_style_refinement = Some(style);
13023    }
13024
13025    /// called by the Element so we know what style we were most recently rendered with.
13026    pub(crate) fn set_style(
13027        &mut self,
13028        style: EditorStyle,
13029        window: &mut Window,
13030        cx: &mut Context<Self>,
13031    ) {
13032        let rem_size = window.rem_size();
13033        self.display_map.update(cx, |map, cx| {
13034            map.set_font(
13035                style.text.font(),
13036                style.text.font_size.to_pixels(rem_size),
13037                cx,
13038            )
13039        });
13040        self.style = Some(style);
13041    }
13042
13043    pub fn style(&self) -> Option<&EditorStyle> {
13044        self.style.as_ref()
13045    }
13046
13047    // Called by the element. This method is not designed to be called outside of the editor
13048    // element's layout code because it does not notify when rewrapping is computed synchronously.
13049    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13050        self.display_map
13051            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13052    }
13053
13054    pub fn set_soft_wrap(&mut self) {
13055        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13056    }
13057
13058    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13059        if self.soft_wrap_mode_override.is_some() {
13060            self.soft_wrap_mode_override.take();
13061        } else {
13062            let soft_wrap = match self.soft_wrap_mode(cx) {
13063                SoftWrap::GitDiff => return,
13064                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13065                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13066                    language_settings::SoftWrap::None
13067                }
13068            };
13069            self.soft_wrap_mode_override = Some(soft_wrap);
13070        }
13071        cx.notify();
13072    }
13073
13074    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13075        let Some(workspace) = self.workspace() else {
13076            return;
13077        };
13078        let fs = workspace.read(cx).app_state().fs.clone();
13079        let current_show = TabBarSettings::get_global(cx).show;
13080        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13081            setting.show = Some(!current_show);
13082        });
13083    }
13084
13085    pub fn toggle_indent_guides(
13086        &mut self,
13087        _: &ToggleIndentGuides,
13088        _: &mut Window,
13089        cx: &mut Context<Self>,
13090    ) {
13091        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13092            self.buffer
13093                .read(cx)
13094                .settings_at(0, cx)
13095                .indent_guides
13096                .enabled
13097        });
13098        self.show_indent_guides = Some(!currently_enabled);
13099        cx.notify();
13100    }
13101
13102    fn should_show_indent_guides(&self) -> Option<bool> {
13103        self.show_indent_guides
13104    }
13105
13106    pub fn toggle_line_numbers(
13107        &mut self,
13108        _: &ToggleLineNumbers,
13109        _: &mut Window,
13110        cx: &mut Context<Self>,
13111    ) {
13112        let mut editor_settings = EditorSettings::get_global(cx).clone();
13113        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13114        EditorSettings::override_global(editor_settings, cx);
13115    }
13116
13117    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13118        self.use_relative_line_numbers
13119            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13120    }
13121
13122    pub fn toggle_relative_line_numbers(
13123        &mut self,
13124        _: &ToggleRelativeLineNumbers,
13125        _: &mut Window,
13126        cx: &mut Context<Self>,
13127    ) {
13128        let is_relative = self.should_use_relative_line_numbers(cx);
13129        self.set_relative_line_number(Some(!is_relative), cx)
13130    }
13131
13132    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13133        self.use_relative_line_numbers = is_relative;
13134        cx.notify();
13135    }
13136
13137    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13138        self.show_gutter = show_gutter;
13139        cx.notify();
13140    }
13141
13142    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13143        self.show_scrollbars = show_scrollbars;
13144        cx.notify();
13145    }
13146
13147    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13148        self.show_line_numbers = Some(show_line_numbers);
13149        cx.notify();
13150    }
13151
13152    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13153        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13154        cx.notify();
13155    }
13156
13157    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13158        self.show_code_actions = Some(show_code_actions);
13159        cx.notify();
13160    }
13161
13162    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13163        self.show_runnables = Some(show_runnables);
13164        cx.notify();
13165    }
13166
13167    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13168        if self.display_map.read(cx).masked != masked {
13169            self.display_map.update(cx, |map, _| map.masked = masked);
13170        }
13171        cx.notify()
13172    }
13173
13174    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13175        self.show_wrap_guides = Some(show_wrap_guides);
13176        cx.notify();
13177    }
13178
13179    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13180        self.show_indent_guides = Some(show_indent_guides);
13181        cx.notify();
13182    }
13183
13184    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13185        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13186            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13187                if let Some(dir) = file.abs_path(cx).parent() {
13188                    return Some(dir.to_owned());
13189                }
13190            }
13191
13192            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13193                return Some(project_path.path.to_path_buf());
13194            }
13195        }
13196
13197        None
13198    }
13199
13200    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13201        self.active_excerpt(cx)?
13202            .1
13203            .read(cx)
13204            .file()
13205            .and_then(|f| f.as_local())
13206    }
13207
13208    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13209        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13210            let buffer = buffer.read(cx);
13211            if let Some(project_path) = buffer.project_path(cx) {
13212                let project = self.project.as_ref()?.read(cx);
13213                project.absolute_path(&project_path, cx)
13214            } else {
13215                buffer
13216                    .file()
13217                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13218            }
13219        })
13220    }
13221
13222    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13223        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13224            let project_path = buffer.read(cx).project_path(cx)?;
13225            let project = self.project.as_ref()?.read(cx);
13226            let entry = project.entry_for_path(&project_path, cx)?;
13227            let path = entry.path.to_path_buf();
13228            Some(path)
13229        })
13230    }
13231
13232    pub fn reveal_in_finder(
13233        &mut self,
13234        _: &RevealInFileManager,
13235        _window: &mut Window,
13236        cx: &mut Context<Self>,
13237    ) {
13238        if let Some(target) = self.target_file(cx) {
13239            cx.reveal_path(&target.abs_path(cx));
13240        }
13241    }
13242
13243    pub fn copy_path(
13244        &mut self,
13245        _: &zed_actions::workspace::CopyPath,
13246        _window: &mut Window,
13247        cx: &mut Context<Self>,
13248    ) {
13249        if let Some(path) = self.target_file_abs_path(cx) {
13250            if let Some(path) = path.to_str() {
13251                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13252            }
13253        }
13254    }
13255
13256    pub fn copy_relative_path(
13257        &mut self,
13258        _: &zed_actions::workspace::CopyRelativePath,
13259        _window: &mut Window,
13260        cx: &mut Context<Self>,
13261    ) {
13262        if let Some(path) = self.target_file_path(cx) {
13263            if let Some(path) = path.to_str() {
13264                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13265            }
13266        }
13267    }
13268
13269    pub fn copy_file_name_without_extension(
13270        &mut self,
13271        _: &CopyFileNameWithoutExtension,
13272        _: &mut Window,
13273        cx: &mut Context<Self>,
13274    ) {
13275        if let Some(file) = self.target_file(cx) {
13276            if let Some(file_stem) = file.path().file_stem() {
13277                if let Some(name) = file_stem.to_str() {
13278                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13279                }
13280            }
13281        }
13282    }
13283
13284    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13285        if let Some(file) = self.target_file(cx) {
13286            if let Some(file_name) = file.path().file_name() {
13287                if let Some(name) = file_name.to_str() {
13288                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13289                }
13290            }
13291        }
13292    }
13293
13294    pub fn toggle_git_blame(
13295        &mut self,
13296        _: &ToggleGitBlame,
13297        window: &mut Window,
13298        cx: &mut Context<Self>,
13299    ) {
13300        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13301
13302        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13303            self.start_git_blame(true, window, cx);
13304        }
13305
13306        cx.notify();
13307    }
13308
13309    pub fn toggle_git_blame_inline(
13310        &mut self,
13311        _: &ToggleGitBlameInline,
13312        window: &mut Window,
13313        cx: &mut Context<Self>,
13314    ) {
13315        self.toggle_git_blame_inline_internal(true, window, cx);
13316        cx.notify();
13317    }
13318
13319    pub fn git_blame_inline_enabled(&self) -> bool {
13320        self.git_blame_inline_enabled
13321    }
13322
13323    pub fn toggle_selection_menu(
13324        &mut self,
13325        _: &ToggleSelectionMenu,
13326        _: &mut Window,
13327        cx: &mut Context<Self>,
13328    ) {
13329        self.show_selection_menu = self
13330            .show_selection_menu
13331            .map(|show_selections_menu| !show_selections_menu)
13332            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13333
13334        cx.notify();
13335    }
13336
13337    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13338        self.show_selection_menu
13339            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13340    }
13341
13342    fn start_git_blame(
13343        &mut self,
13344        user_triggered: bool,
13345        window: &mut Window,
13346        cx: &mut Context<Self>,
13347    ) {
13348        if let Some(project) = self.project.as_ref() {
13349            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13350                return;
13351            };
13352
13353            if buffer.read(cx).file().is_none() {
13354                return;
13355            }
13356
13357            let focused = self.focus_handle(cx).contains_focused(window, cx);
13358
13359            let project = project.clone();
13360            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13361            self.blame_subscription =
13362                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13363            self.blame = Some(blame);
13364        }
13365    }
13366
13367    fn toggle_git_blame_inline_internal(
13368        &mut self,
13369        user_triggered: bool,
13370        window: &mut Window,
13371        cx: &mut Context<Self>,
13372    ) {
13373        if self.git_blame_inline_enabled {
13374            self.git_blame_inline_enabled = false;
13375            self.show_git_blame_inline = false;
13376            self.show_git_blame_inline_delay_task.take();
13377        } else {
13378            self.git_blame_inline_enabled = true;
13379            self.start_git_blame_inline(user_triggered, window, cx);
13380        }
13381
13382        cx.notify();
13383    }
13384
13385    fn start_git_blame_inline(
13386        &mut self,
13387        user_triggered: bool,
13388        window: &mut Window,
13389        cx: &mut Context<Self>,
13390    ) {
13391        self.start_git_blame(user_triggered, window, cx);
13392
13393        if ProjectSettings::get_global(cx)
13394            .git
13395            .inline_blame_delay()
13396            .is_some()
13397        {
13398            self.start_inline_blame_timer(window, cx);
13399        } else {
13400            self.show_git_blame_inline = true
13401        }
13402    }
13403
13404    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13405        self.blame.as_ref()
13406    }
13407
13408    pub fn show_git_blame_gutter(&self) -> bool {
13409        self.show_git_blame_gutter
13410    }
13411
13412    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13413        self.show_git_blame_gutter && self.has_blame_entries(cx)
13414    }
13415
13416    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13417        self.show_git_blame_inline
13418            && self.focus_handle.is_focused(window)
13419            && !self.newest_selection_head_on_empty_line(cx)
13420            && self.has_blame_entries(cx)
13421    }
13422
13423    fn has_blame_entries(&self, cx: &App) -> bool {
13424        self.blame()
13425            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13426    }
13427
13428    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13429        let cursor_anchor = self.selections.newest_anchor().head();
13430
13431        let snapshot = self.buffer.read(cx).snapshot(cx);
13432        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13433
13434        snapshot.line_len(buffer_row) == 0
13435    }
13436
13437    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13438        let buffer_and_selection = maybe!({
13439            let selection = self.selections.newest::<Point>(cx);
13440            let selection_range = selection.range();
13441
13442            let multi_buffer = self.buffer().read(cx);
13443            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13444            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13445
13446            let (buffer, range, _) = if selection.reversed {
13447                buffer_ranges.first()
13448            } else {
13449                buffer_ranges.last()
13450            }?;
13451
13452            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13453                ..text::ToPoint::to_point(&range.end, &buffer).row;
13454            Some((
13455                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13456                selection,
13457            ))
13458        });
13459
13460        let Some((buffer, selection)) = buffer_and_selection else {
13461            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13462        };
13463
13464        let Some(project) = self.project.as_ref() else {
13465            return Task::ready(Err(anyhow!("editor does not have project")));
13466        };
13467
13468        project.update(cx, |project, cx| {
13469            project.get_permalink_to_line(&buffer, selection, cx)
13470        })
13471    }
13472
13473    pub fn copy_permalink_to_line(
13474        &mut self,
13475        _: &CopyPermalinkToLine,
13476        window: &mut Window,
13477        cx: &mut Context<Self>,
13478    ) {
13479        let permalink_task = self.get_permalink_to_line(cx);
13480        let workspace = self.workspace();
13481
13482        cx.spawn_in(window, |_, mut cx| async move {
13483            match permalink_task.await {
13484                Ok(permalink) => {
13485                    cx.update(|_, cx| {
13486                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13487                    })
13488                    .ok();
13489                }
13490                Err(err) => {
13491                    let message = format!("Failed to copy permalink: {err}");
13492
13493                    Err::<(), anyhow::Error>(err).log_err();
13494
13495                    if let Some(workspace) = workspace {
13496                        workspace
13497                            .update_in(&mut cx, |workspace, _, cx| {
13498                                struct CopyPermalinkToLine;
13499
13500                                workspace.show_toast(
13501                                    Toast::new(
13502                                        NotificationId::unique::<CopyPermalinkToLine>(),
13503                                        message,
13504                                    ),
13505                                    cx,
13506                                )
13507                            })
13508                            .ok();
13509                    }
13510                }
13511            }
13512        })
13513        .detach();
13514    }
13515
13516    pub fn copy_file_location(
13517        &mut self,
13518        _: &CopyFileLocation,
13519        _: &mut Window,
13520        cx: &mut Context<Self>,
13521    ) {
13522        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13523        if let Some(file) = self.target_file(cx) {
13524            if let Some(path) = file.path().to_str() {
13525                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13526            }
13527        }
13528    }
13529
13530    pub fn open_permalink_to_line(
13531        &mut self,
13532        _: &OpenPermalinkToLine,
13533        window: &mut Window,
13534        cx: &mut Context<Self>,
13535    ) {
13536        let permalink_task = self.get_permalink_to_line(cx);
13537        let workspace = self.workspace();
13538
13539        cx.spawn_in(window, |_, mut cx| async move {
13540            match permalink_task.await {
13541                Ok(permalink) => {
13542                    cx.update(|_, cx| {
13543                        cx.open_url(permalink.as_ref());
13544                    })
13545                    .ok();
13546                }
13547                Err(err) => {
13548                    let message = format!("Failed to open permalink: {err}");
13549
13550                    Err::<(), anyhow::Error>(err).log_err();
13551
13552                    if let Some(workspace) = workspace {
13553                        workspace
13554                            .update(&mut cx, |workspace, cx| {
13555                                struct OpenPermalinkToLine;
13556
13557                                workspace.show_toast(
13558                                    Toast::new(
13559                                        NotificationId::unique::<OpenPermalinkToLine>(),
13560                                        message,
13561                                    ),
13562                                    cx,
13563                                )
13564                            })
13565                            .ok();
13566                    }
13567                }
13568            }
13569        })
13570        .detach();
13571    }
13572
13573    pub fn insert_uuid_v4(
13574        &mut self,
13575        _: &InsertUuidV4,
13576        window: &mut Window,
13577        cx: &mut Context<Self>,
13578    ) {
13579        self.insert_uuid(UuidVersion::V4, window, cx);
13580    }
13581
13582    pub fn insert_uuid_v7(
13583        &mut self,
13584        _: &InsertUuidV7,
13585        window: &mut Window,
13586        cx: &mut Context<Self>,
13587    ) {
13588        self.insert_uuid(UuidVersion::V7, window, cx);
13589    }
13590
13591    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13592        self.transact(window, cx, |this, window, cx| {
13593            let edits = this
13594                .selections
13595                .all::<Point>(cx)
13596                .into_iter()
13597                .map(|selection| {
13598                    let uuid = match version {
13599                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13600                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13601                    };
13602
13603                    (selection.range(), uuid.to_string())
13604                });
13605            this.edit(edits, cx);
13606            this.refresh_inline_completion(true, false, window, cx);
13607        });
13608    }
13609
13610    pub fn open_selections_in_multibuffer(
13611        &mut self,
13612        _: &OpenSelectionsInMultibuffer,
13613        window: &mut Window,
13614        cx: &mut Context<Self>,
13615    ) {
13616        let multibuffer = self.buffer.read(cx);
13617
13618        let Some(buffer) = multibuffer.as_singleton() else {
13619            return;
13620        };
13621
13622        let Some(workspace) = self.workspace() else {
13623            return;
13624        };
13625
13626        let locations = self
13627            .selections
13628            .disjoint_anchors()
13629            .iter()
13630            .map(|range| Location {
13631                buffer: buffer.clone(),
13632                range: range.start.text_anchor..range.end.text_anchor,
13633            })
13634            .collect::<Vec<_>>();
13635
13636        let title = multibuffer.title(cx).to_string();
13637
13638        cx.spawn_in(window, |_, mut cx| async move {
13639            workspace.update_in(&mut cx, |workspace, window, cx| {
13640                Self::open_locations_in_multibuffer(
13641                    workspace,
13642                    locations,
13643                    format!("Selections for '{title}'"),
13644                    false,
13645                    MultibufferSelectionMode::All,
13646                    window,
13647                    cx,
13648                );
13649            })
13650        })
13651        .detach();
13652    }
13653
13654    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13655    /// last highlight added will be used.
13656    ///
13657    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13658    pub fn highlight_rows<T: 'static>(
13659        &mut self,
13660        range: Range<Anchor>,
13661        color: Hsla,
13662        should_autoscroll: bool,
13663        cx: &mut Context<Self>,
13664    ) {
13665        let snapshot = self.buffer().read(cx).snapshot(cx);
13666        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13667        let ix = row_highlights.binary_search_by(|highlight| {
13668            Ordering::Equal
13669                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13670                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13671        });
13672
13673        if let Err(mut ix) = ix {
13674            let index = post_inc(&mut self.highlight_order);
13675
13676            // If this range intersects with the preceding highlight, then merge it with
13677            // the preceding highlight. Otherwise insert a new highlight.
13678            let mut merged = false;
13679            if ix > 0 {
13680                let prev_highlight = &mut row_highlights[ix - 1];
13681                if prev_highlight
13682                    .range
13683                    .end
13684                    .cmp(&range.start, &snapshot)
13685                    .is_ge()
13686                {
13687                    ix -= 1;
13688                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13689                        prev_highlight.range.end = range.end;
13690                    }
13691                    merged = true;
13692                    prev_highlight.index = index;
13693                    prev_highlight.color = color;
13694                    prev_highlight.should_autoscroll = should_autoscroll;
13695                }
13696            }
13697
13698            if !merged {
13699                row_highlights.insert(
13700                    ix,
13701                    RowHighlight {
13702                        range: range.clone(),
13703                        index,
13704                        color,
13705                        should_autoscroll,
13706                    },
13707                );
13708            }
13709
13710            // If any of the following highlights intersect with this one, merge them.
13711            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13712                let highlight = &row_highlights[ix];
13713                if next_highlight
13714                    .range
13715                    .start
13716                    .cmp(&highlight.range.end, &snapshot)
13717                    .is_le()
13718                {
13719                    if next_highlight
13720                        .range
13721                        .end
13722                        .cmp(&highlight.range.end, &snapshot)
13723                        .is_gt()
13724                    {
13725                        row_highlights[ix].range.end = next_highlight.range.end;
13726                    }
13727                    row_highlights.remove(ix + 1);
13728                } else {
13729                    break;
13730                }
13731            }
13732        }
13733    }
13734
13735    /// Remove any highlighted row ranges of the given type that intersect the
13736    /// given ranges.
13737    pub fn remove_highlighted_rows<T: 'static>(
13738        &mut self,
13739        ranges_to_remove: Vec<Range<Anchor>>,
13740        cx: &mut Context<Self>,
13741    ) {
13742        let snapshot = self.buffer().read(cx).snapshot(cx);
13743        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13744        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13745        row_highlights.retain(|highlight| {
13746            while let Some(range_to_remove) = ranges_to_remove.peek() {
13747                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13748                    Ordering::Less | Ordering::Equal => {
13749                        ranges_to_remove.next();
13750                    }
13751                    Ordering::Greater => {
13752                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13753                            Ordering::Less | Ordering::Equal => {
13754                                return false;
13755                            }
13756                            Ordering::Greater => break,
13757                        }
13758                    }
13759                }
13760            }
13761
13762            true
13763        })
13764    }
13765
13766    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13767    pub fn clear_row_highlights<T: 'static>(&mut self) {
13768        self.highlighted_rows.remove(&TypeId::of::<T>());
13769    }
13770
13771    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13772    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13773        self.highlighted_rows
13774            .get(&TypeId::of::<T>())
13775            .map_or(&[] as &[_], |vec| vec.as_slice())
13776            .iter()
13777            .map(|highlight| (highlight.range.clone(), highlight.color))
13778    }
13779
13780    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13781    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13782    /// Allows to ignore certain kinds of highlights.
13783    pub fn highlighted_display_rows(
13784        &self,
13785        window: &mut Window,
13786        cx: &mut App,
13787    ) -> BTreeMap<DisplayRow, Background> {
13788        let snapshot = self.snapshot(window, cx);
13789        let mut used_highlight_orders = HashMap::default();
13790        self.highlighted_rows
13791            .iter()
13792            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13793            .fold(
13794                BTreeMap::<DisplayRow, Background>::new(),
13795                |mut unique_rows, highlight| {
13796                    let start = highlight.range.start.to_display_point(&snapshot);
13797                    let end = highlight.range.end.to_display_point(&snapshot);
13798                    let start_row = start.row().0;
13799                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13800                        && end.column() == 0
13801                    {
13802                        end.row().0.saturating_sub(1)
13803                    } else {
13804                        end.row().0
13805                    };
13806                    for row in start_row..=end_row {
13807                        let used_index =
13808                            used_highlight_orders.entry(row).or_insert(highlight.index);
13809                        if highlight.index >= *used_index {
13810                            *used_index = highlight.index;
13811                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13812                        }
13813                    }
13814                    unique_rows
13815                },
13816            )
13817    }
13818
13819    pub fn highlighted_display_row_for_autoscroll(
13820        &self,
13821        snapshot: &DisplaySnapshot,
13822    ) -> Option<DisplayRow> {
13823        self.highlighted_rows
13824            .values()
13825            .flat_map(|highlighted_rows| highlighted_rows.iter())
13826            .filter_map(|highlight| {
13827                if highlight.should_autoscroll {
13828                    Some(highlight.range.start.to_display_point(snapshot).row())
13829                } else {
13830                    None
13831                }
13832            })
13833            .min()
13834    }
13835
13836    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13837        self.highlight_background::<SearchWithinRange>(
13838            ranges,
13839            |colors| colors.editor_document_highlight_read_background,
13840            cx,
13841        )
13842    }
13843
13844    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13845        self.breadcrumb_header = Some(new_header);
13846    }
13847
13848    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13849        self.clear_background_highlights::<SearchWithinRange>(cx);
13850    }
13851
13852    pub fn highlight_background<T: 'static>(
13853        &mut self,
13854        ranges: &[Range<Anchor>],
13855        color_fetcher: fn(&ThemeColors) -> Hsla,
13856        cx: &mut Context<Self>,
13857    ) {
13858        self.background_highlights
13859            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13860        self.scrollbar_marker_state.dirty = true;
13861        cx.notify();
13862    }
13863
13864    pub fn clear_background_highlights<T: 'static>(
13865        &mut self,
13866        cx: &mut Context<Self>,
13867    ) -> Option<BackgroundHighlight> {
13868        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13869        if !text_highlights.1.is_empty() {
13870            self.scrollbar_marker_state.dirty = true;
13871            cx.notify();
13872        }
13873        Some(text_highlights)
13874    }
13875
13876    pub fn highlight_gutter<T: 'static>(
13877        &mut self,
13878        ranges: &[Range<Anchor>],
13879        color_fetcher: fn(&App) -> Hsla,
13880        cx: &mut Context<Self>,
13881    ) {
13882        self.gutter_highlights
13883            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13884        cx.notify();
13885    }
13886
13887    pub fn clear_gutter_highlights<T: 'static>(
13888        &mut self,
13889        cx: &mut Context<Self>,
13890    ) -> Option<GutterHighlight> {
13891        cx.notify();
13892        self.gutter_highlights.remove(&TypeId::of::<T>())
13893    }
13894
13895    #[cfg(feature = "test-support")]
13896    pub fn all_text_background_highlights(
13897        &self,
13898        window: &mut Window,
13899        cx: &mut Context<Self>,
13900    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13901        let snapshot = self.snapshot(window, cx);
13902        let buffer = &snapshot.buffer_snapshot;
13903        let start = buffer.anchor_before(0);
13904        let end = buffer.anchor_after(buffer.len());
13905        let theme = cx.theme().colors();
13906        self.background_highlights_in_range(start..end, &snapshot, theme)
13907    }
13908
13909    #[cfg(feature = "test-support")]
13910    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13911        let snapshot = self.buffer().read(cx).snapshot(cx);
13912
13913        let highlights = self
13914            .background_highlights
13915            .get(&TypeId::of::<items::BufferSearchHighlights>());
13916
13917        if let Some((_color, ranges)) = highlights {
13918            ranges
13919                .iter()
13920                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13921                .collect_vec()
13922        } else {
13923            vec![]
13924        }
13925    }
13926
13927    fn document_highlights_for_position<'a>(
13928        &'a self,
13929        position: Anchor,
13930        buffer: &'a MultiBufferSnapshot,
13931    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13932        let read_highlights = self
13933            .background_highlights
13934            .get(&TypeId::of::<DocumentHighlightRead>())
13935            .map(|h| &h.1);
13936        let write_highlights = self
13937            .background_highlights
13938            .get(&TypeId::of::<DocumentHighlightWrite>())
13939            .map(|h| &h.1);
13940        let left_position = position.bias_left(buffer);
13941        let right_position = position.bias_right(buffer);
13942        read_highlights
13943            .into_iter()
13944            .chain(write_highlights)
13945            .flat_map(move |ranges| {
13946                let start_ix = match ranges.binary_search_by(|probe| {
13947                    let cmp = probe.end.cmp(&left_position, buffer);
13948                    if cmp.is_ge() {
13949                        Ordering::Greater
13950                    } else {
13951                        Ordering::Less
13952                    }
13953                }) {
13954                    Ok(i) | Err(i) => i,
13955                };
13956
13957                ranges[start_ix..]
13958                    .iter()
13959                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13960            })
13961    }
13962
13963    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13964        self.background_highlights
13965            .get(&TypeId::of::<T>())
13966            .map_or(false, |(_, highlights)| !highlights.is_empty())
13967    }
13968
13969    pub fn background_highlights_in_range(
13970        &self,
13971        search_range: Range<Anchor>,
13972        display_snapshot: &DisplaySnapshot,
13973        theme: &ThemeColors,
13974    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13975        let mut results = Vec::new();
13976        for (color_fetcher, ranges) in self.background_highlights.values() {
13977            let color = color_fetcher(theme);
13978            let start_ix = match ranges.binary_search_by(|probe| {
13979                let cmp = probe
13980                    .end
13981                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13982                if cmp.is_gt() {
13983                    Ordering::Greater
13984                } else {
13985                    Ordering::Less
13986                }
13987            }) {
13988                Ok(i) | Err(i) => i,
13989            };
13990            for range in &ranges[start_ix..] {
13991                if range
13992                    .start
13993                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13994                    .is_ge()
13995                {
13996                    break;
13997                }
13998
13999                let start = range.start.to_display_point(display_snapshot);
14000                let end = range.end.to_display_point(display_snapshot);
14001                results.push((start..end, color))
14002            }
14003        }
14004        results
14005    }
14006
14007    pub fn background_highlight_row_ranges<T: 'static>(
14008        &self,
14009        search_range: Range<Anchor>,
14010        display_snapshot: &DisplaySnapshot,
14011        count: usize,
14012    ) -> Vec<RangeInclusive<DisplayPoint>> {
14013        let mut results = Vec::new();
14014        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14015            return vec![];
14016        };
14017
14018        let start_ix = match ranges.binary_search_by(|probe| {
14019            let cmp = probe
14020                .end
14021                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14022            if cmp.is_gt() {
14023                Ordering::Greater
14024            } else {
14025                Ordering::Less
14026            }
14027        }) {
14028            Ok(i) | Err(i) => i,
14029        };
14030        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14031            if let (Some(start_display), Some(end_display)) = (start, end) {
14032                results.push(
14033                    start_display.to_display_point(display_snapshot)
14034                        ..=end_display.to_display_point(display_snapshot),
14035                );
14036            }
14037        };
14038        let mut start_row: Option<Point> = None;
14039        let mut end_row: Option<Point> = None;
14040        if ranges.len() > count {
14041            return Vec::new();
14042        }
14043        for range in &ranges[start_ix..] {
14044            if range
14045                .start
14046                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14047                .is_ge()
14048            {
14049                break;
14050            }
14051            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14052            if let Some(current_row) = &end_row {
14053                if end.row == current_row.row {
14054                    continue;
14055                }
14056            }
14057            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14058            if start_row.is_none() {
14059                assert_eq!(end_row, None);
14060                start_row = Some(start);
14061                end_row = Some(end);
14062                continue;
14063            }
14064            if let Some(current_end) = end_row.as_mut() {
14065                if start.row > current_end.row + 1 {
14066                    push_region(start_row, end_row);
14067                    start_row = Some(start);
14068                    end_row = Some(end);
14069                } else {
14070                    // Merge two hunks.
14071                    *current_end = end;
14072                }
14073            } else {
14074                unreachable!();
14075            }
14076        }
14077        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14078        push_region(start_row, end_row);
14079        results
14080    }
14081
14082    pub fn gutter_highlights_in_range(
14083        &self,
14084        search_range: Range<Anchor>,
14085        display_snapshot: &DisplaySnapshot,
14086        cx: &App,
14087    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14088        let mut results = Vec::new();
14089        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14090            let color = color_fetcher(cx);
14091            let start_ix = match ranges.binary_search_by(|probe| {
14092                let cmp = probe
14093                    .end
14094                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14095                if cmp.is_gt() {
14096                    Ordering::Greater
14097                } else {
14098                    Ordering::Less
14099                }
14100            }) {
14101                Ok(i) | Err(i) => i,
14102            };
14103            for range in &ranges[start_ix..] {
14104                if range
14105                    .start
14106                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14107                    .is_ge()
14108                {
14109                    break;
14110                }
14111
14112                let start = range.start.to_display_point(display_snapshot);
14113                let end = range.end.to_display_point(display_snapshot);
14114                results.push((start..end, color))
14115            }
14116        }
14117        results
14118    }
14119
14120    /// Get the text ranges corresponding to the redaction query
14121    pub fn redacted_ranges(
14122        &self,
14123        search_range: Range<Anchor>,
14124        display_snapshot: &DisplaySnapshot,
14125        cx: &App,
14126    ) -> Vec<Range<DisplayPoint>> {
14127        display_snapshot
14128            .buffer_snapshot
14129            .redacted_ranges(search_range, |file| {
14130                if let Some(file) = file {
14131                    file.is_private()
14132                        && EditorSettings::get(
14133                            Some(SettingsLocation {
14134                                worktree_id: file.worktree_id(cx),
14135                                path: file.path().as_ref(),
14136                            }),
14137                            cx,
14138                        )
14139                        .redact_private_values
14140                } else {
14141                    false
14142                }
14143            })
14144            .map(|range| {
14145                range.start.to_display_point(display_snapshot)
14146                    ..range.end.to_display_point(display_snapshot)
14147            })
14148            .collect()
14149    }
14150
14151    pub fn highlight_text<T: 'static>(
14152        &mut self,
14153        ranges: Vec<Range<Anchor>>,
14154        style: HighlightStyle,
14155        cx: &mut Context<Self>,
14156    ) {
14157        self.display_map.update(cx, |map, _| {
14158            map.highlight_text(TypeId::of::<T>(), ranges, style)
14159        });
14160        cx.notify();
14161    }
14162
14163    pub(crate) fn highlight_inlays<T: 'static>(
14164        &mut self,
14165        highlights: Vec<InlayHighlight>,
14166        style: HighlightStyle,
14167        cx: &mut Context<Self>,
14168    ) {
14169        self.display_map.update(cx, |map, _| {
14170            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14171        });
14172        cx.notify();
14173    }
14174
14175    pub fn text_highlights<'a, T: 'static>(
14176        &'a self,
14177        cx: &'a App,
14178    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14179        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14180    }
14181
14182    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14183        let cleared = self
14184            .display_map
14185            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14186        if cleared {
14187            cx.notify();
14188        }
14189    }
14190
14191    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14192        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14193            && self.focus_handle.is_focused(window)
14194    }
14195
14196    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14197        self.show_cursor_when_unfocused = is_enabled;
14198        cx.notify();
14199    }
14200
14201    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14202        cx.notify();
14203    }
14204
14205    fn on_buffer_event(
14206        &mut self,
14207        multibuffer: &Entity<MultiBuffer>,
14208        event: &multi_buffer::Event,
14209        window: &mut Window,
14210        cx: &mut Context<Self>,
14211    ) {
14212        match event {
14213            multi_buffer::Event::Edited {
14214                singleton_buffer_edited,
14215                edited_buffer: buffer_edited,
14216            } => {
14217                self.scrollbar_marker_state.dirty = true;
14218                self.active_indent_guides_state.dirty = true;
14219                self.refresh_active_diagnostics(cx);
14220                self.refresh_code_actions(window, cx);
14221                if self.has_active_inline_completion() {
14222                    self.update_visible_inline_completion(window, cx);
14223                }
14224                if let Some(buffer) = buffer_edited {
14225                    let buffer_id = buffer.read(cx).remote_id();
14226                    if !self.registered_buffers.contains_key(&buffer_id) {
14227                        if let Some(project) = self.project.as_ref() {
14228                            project.update(cx, |project, cx| {
14229                                self.registered_buffers.insert(
14230                                    buffer_id,
14231                                    project.register_buffer_with_language_servers(&buffer, cx),
14232                                );
14233                            })
14234                        }
14235                    }
14236                }
14237                cx.emit(EditorEvent::BufferEdited);
14238                cx.emit(SearchEvent::MatchesInvalidated);
14239                if *singleton_buffer_edited {
14240                    if let Some(project) = &self.project {
14241                        #[allow(clippy::mutable_key_type)]
14242                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14243                            multibuffer
14244                                .all_buffers()
14245                                .into_iter()
14246                                .filter_map(|buffer| {
14247                                    buffer.update(cx, |buffer, cx| {
14248                                        let language = buffer.language()?;
14249                                        let should_discard = project.update(cx, |project, cx| {
14250                                            project.is_local()
14251                                                && !project.has_language_servers_for(buffer, cx)
14252                                        });
14253                                        should_discard.not().then_some(language.clone())
14254                                    })
14255                                })
14256                                .collect::<HashSet<_>>()
14257                        });
14258                        if !languages_affected.is_empty() {
14259                            self.refresh_inlay_hints(
14260                                InlayHintRefreshReason::BufferEdited(languages_affected),
14261                                cx,
14262                            );
14263                        }
14264                    }
14265                }
14266
14267                let Some(project) = &self.project else { return };
14268                let (telemetry, is_via_ssh) = {
14269                    let project = project.read(cx);
14270                    let telemetry = project.client().telemetry().clone();
14271                    let is_via_ssh = project.is_via_ssh();
14272                    (telemetry, is_via_ssh)
14273                };
14274                refresh_linked_ranges(self, window, cx);
14275                telemetry.log_edit_event("editor", is_via_ssh);
14276            }
14277            multi_buffer::Event::ExcerptsAdded {
14278                buffer,
14279                predecessor,
14280                excerpts,
14281            } => {
14282                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14283                let buffer_id = buffer.read(cx).remote_id();
14284                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14285                    if let Some(project) = &self.project {
14286                        get_uncommitted_diff_for_buffer(
14287                            project,
14288                            [buffer.clone()],
14289                            self.buffer.clone(),
14290                            cx,
14291                        )
14292                        .detach();
14293                    }
14294                }
14295                cx.emit(EditorEvent::ExcerptsAdded {
14296                    buffer: buffer.clone(),
14297                    predecessor: *predecessor,
14298                    excerpts: excerpts.clone(),
14299                });
14300                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14301            }
14302            multi_buffer::Event::ExcerptsRemoved { ids } => {
14303                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14304                let buffer = self.buffer.read(cx);
14305                self.registered_buffers
14306                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14307                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14308            }
14309            multi_buffer::Event::ExcerptsEdited { ids } => {
14310                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14311            }
14312            multi_buffer::Event::ExcerptsExpanded { ids } => {
14313                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14314                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14315            }
14316            multi_buffer::Event::Reparsed(buffer_id) => {
14317                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14318
14319                cx.emit(EditorEvent::Reparsed(*buffer_id));
14320            }
14321            multi_buffer::Event::DiffHunksToggled => {
14322                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14323            }
14324            multi_buffer::Event::LanguageChanged(buffer_id) => {
14325                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14326                cx.emit(EditorEvent::Reparsed(*buffer_id));
14327                cx.notify();
14328            }
14329            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14330            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14331            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14332                cx.emit(EditorEvent::TitleChanged)
14333            }
14334            // multi_buffer::Event::DiffBaseChanged => {
14335            //     self.scrollbar_marker_state.dirty = true;
14336            //     cx.emit(EditorEvent::DiffBaseChanged);
14337            //     cx.notify();
14338            // }
14339            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14340            multi_buffer::Event::DiagnosticsUpdated => {
14341                self.refresh_active_diagnostics(cx);
14342                self.scrollbar_marker_state.dirty = true;
14343                cx.notify();
14344            }
14345            _ => {}
14346        };
14347    }
14348
14349    fn on_display_map_changed(
14350        &mut self,
14351        _: Entity<DisplayMap>,
14352        _: &mut Window,
14353        cx: &mut Context<Self>,
14354    ) {
14355        cx.notify();
14356    }
14357
14358    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14359        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14360        self.refresh_inline_completion(true, false, window, cx);
14361        self.refresh_inlay_hints(
14362            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14363                self.selections.newest_anchor().head(),
14364                &self.buffer.read(cx).snapshot(cx),
14365                cx,
14366            )),
14367            cx,
14368        );
14369
14370        let old_cursor_shape = self.cursor_shape;
14371
14372        {
14373            let editor_settings = EditorSettings::get_global(cx);
14374            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14375            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14376            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14377        }
14378
14379        if old_cursor_shape != self.cursor_shape {
14380            cx.emit(EditorEvent::CursorShapeChanged);
14381        }
14382
14383        let project_settings = ProjectSettings::get_global(cx);
14384        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14385
14386        if self.mode == EditorMode::Full {
14387            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14388            if self.git_blame_inline_enabled != inline_blame_enabled {
14389                self.toggle_git_blame_inline_internal(false, window, cx);
14390            }
14391        }
14392
14393        cx.notify();
14394    }
14395
14396    pub fn set_searchable(&mut self, searchable: bool) {
14397        self.searchable = searchable;
14398    }
14399
14400    pub fn searchable(&self) -> bool {
14401        self.searchable
14402    }
14403
14404    fn open_proposed_changes_editor(
14405        &mut self,
14406        _: &OpenProposedChangesEditor,
14407        window: &mut Window,
14408        cx: &mut Context<Self>,
14409    ) {
14410        let Some(workspace) = self.workspace() else {
14411            cx.propagate();
14412            return;
14413        };
14414
14415        let selections = self.selections.all::<usize>(cx);
14416        let multi_buffer = self.buffer.read(cx);
14417        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14418        let mut new_selections_by_buffer = HashMap::default();
14419        for selection in selections {
14420            for (buffer, range, _) in
14421                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14422            {
14423                let mut range = range.to_point(buffer);
14424                range.start.column = 0;
14425                range.end.column = buffer.line_len(range.end.row);
14426                new_selections_by_buffer
14427                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14428                    .or_insert(Vec::new())
14429                    .push(range)
14430            }
14431        }
14432
14433        let proposed_changes_buffers = new_selections_by_buffer
14434            .into_iter()
14435            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14436            .collect::<Vec<_>>();
14437        let proposed_changes_editor = cx.new(|cx| {
14438            ProposedChangesEditor::new(
14439                "Proposed changes",
14440                proposed_changes_buffers,
14441                self.project.clone(),
14442                window,
14443                cx,
14444            )
14445        });
14446
14447        window.defer(cx, move |window, cx| {
14448            workspace.update(cx, |workspace, cx| {
14449                workspace.active_pane().update(cx, |pane, cx| {
14450                    pane.add_item(
14451                        Box::new(proposed_changes_editor),
14452                        true,
14453                        true,
14454                        None,
14455                        window,
14456                        cx,
14457                    );
14458                });
14459            });
14460        });
14461    }
14462
14463    pub fn open_excerpts_in_split(
14464        &mut self,
14465        _: &OpenExcerptsSplit,
14466        window: &mut Window,
14467        cx: &mut Context<Self>,
14468    ) {
14469        self.open_excerpts_common(None, true, window, cx)
14470    }
14471
14472    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14473        self.open_excerpts_common(None, false, window, cx)
14474    }
14475
14476    fn open_excerpts_common(
14477        &mut self,
14478        jump_data: Option<JumpData>,
14479        split: bool,
14480        window: &mut Window,
14481        cx: &mut Context<Self>,
14482    ) {
14483        let Some(workspace) = self.workspace() else {
14484            cx.propagate();
14485            return;
14486        };
14487
14488        if self.buffer.read(cx).is_singleton() {
14489            cx.propagate();
14490            return;
14491        }
14492
14493        let mut new_selections_by_buffer = HashMap::default();
14494        match &jump_data {
14495            Some(JumpData::MultiBufferPoint {
14496                excerpt_id,
14497                position,
14498                anchor,
14499                line_offset_from_top,
14500            }) => {
14501                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14502                if let Some(buffer) = multi_buffer_snapshot
14503                    .buffer_id_for_excerpt(*excerpt_id)
14504                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14505                {
14506                    let buffer_snapshot = buffer.read(cx).snapshot();
14507                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14508                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14509                    } else {
14510                        buffer_snapshot.clip_point(*position, Bias::Left)
14511                    };
14512                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14513                    new_selections_by_buffer.insert(
14514                        buffer,
14515                        (
14516                            vec![jump_to_offset..jump_to_offset],
14517                            Some(*line_offset_from_top),
14518                        ),
14519                    );
14520                }
14521            }
14522            Some(JumpData::MultiBufferRow {
14523                row,
14524                line_offset_from_top,
14525            }) => {
14526                let point = MultiBufferPoint::new(row.0, 0);
14527                if let Some((buffer, buffer_point, _)) =
14528                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14529                {
14530                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14531                    new_selections_by_buffer
14532                        .entry(buffer)
14533                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14534                        .0
14535                        .push(buffer_offset..buffer_offset)
14536                }
14537            }
14538            None => {
14539                let selections = self.selections.all::<usize>(cx);
14540                let multi_buffer = self.buffer.read(cx);
14541                for selection in selections {
14542                    for (buffer, mut range, _) in multi_buffer
14543                        .snapshot(cx)
14544                        .range_to_buffer_ranges(selection.range())
14545                    {
14546                        // When editing branch buffers, jump to the corresponding location
14547                        // in their base buffer.
14548                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14549                        let buffer = buffer_handle.read(cx);
14550                        if let Some(base_buffer) = buffer.base_buffer() {
14551                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14552                            buffer_handle = base_buffer;
14553                        }
14554
14555                        if selection.reversed {
14556                            mem::swap(&mut range.start, &mut range.end);
14557                        }
14558                        new_selections_by_buffer
14559                            .entry(buffer_handle)
14560                            .or_insert((Vec::new(), None))
14561                            .0
14562                            .push(range)
14563                    }
14564                }
14565            }
14566        }
14567
14568        if new_selections_by_buffer.is_empty() {
14569            return;
14570        }
14571
14572        // We defer the pane interaction because we ourselves are a workspace item
14573        // and activating a new item causes the pane to call a method on us reentrantly,
14574        // which panics if we're on the stack.
14575        window.defer(cx, move |window, cx| {
14576            workspace.update(cx, |workspace, cx| {
14577                let pane = if split {
14578                    workspace.adjacent_pane(window, cx)
14579                } else {
14580                    workspace.active_pane().clone()
14581                };
14582
14583                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14584                    let editor = buffer
14585                        .read(cx)
14586                        .file()
14587                        .is_none()
14588                        .then(|| {
14589                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14590                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14591                            // Instead, we try to activate the existing editor in the pane first.
14592                            let (editor, pane_item_index) =
14593                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14594                                    let editor = item.downcast::<Editor>()?;
14595                                    let singleton_buffer =
14596                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14597                                    if singleton_buffer == buffer {
14598                                        Some((editor, i))
14599                                    } else {
14600                                        None
14601                                    }
14602                                })?;
14603                            pane.update(cx, |pane, cx| {
14604                                pane.activate_item(pane_item_index, true, true, window, cx)
14605                            });
14606                            Some(editor)
14607                        })
14608                        .flatten()
14609                        .unwrap_or_else(|| {
14610                            workspace.open_project_item::<Self>(
14611                                pane.clone(),
14612                                buffer,
14613                                true,
14614                                true,
14615                                window,
14616                                cx,
14617                            )
14618                        });
14619
14620                    editor.update(cx, |editor, cx| {
14621                        let autoscroll = match scroll_offset {
14622                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14623                            None => Autoscroll::newest(),
14624                        };
14625                        let nav_history = editor.nav_history.take();
14626                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14627                            s.select_ranges(ranges);
14628                        });
14629                        editor.nav_history = nav_history;
14630                    });
14631                }
14632            })
14633        });
14634    }
14635
14636    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14637        let snapshot = self.buffer.read(cx).read(cx);
14638        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14639        Some(
14640            ranges
14641                .iter()
14642                .map(move |range| {
14643                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14644                })
14645                .collect(),
14646        )
14647    }
14648
14649    fn selection_replacement_ranges(
14650        &self,
14651        range: Range<OffsetUtf16>,
14652        cx: &mut App,
14653    ) -> Vec<Range<OffsetUtf16>> {
14654        let selections = self.selections.all::<OffsetUtf16>(cx);
14655        let newest_selection = selections
14656            .iter()
14657            .max_by_key(|selection| selection.id)
14658            .unwrap();
14659        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14660        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14661        let snapshot = self.buffer.read(cx).read(cx);
14662        selections
14663            .into_iter()
14664            .map(|mut selection| {
14665                selection.start.0 =
14666                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14667                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14668                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14669                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14670            })
14671            .collect()
14672    }
14673
14674    fn report_editor_event(
14675        &self,
14676        event_type: &'static str,
14677        file_extension: Option<String>,
14678        cx: &App,
14679    ) {
14680        if cfg!(any(test, feature = "test-support")) {
14681            return;
14682        }
14683
14684        let Some(project) = &self.project else { return };
14685
14686        // If None, we are in a file without an extension
14687        let file = self
14688            .buffer
14689            .read(cx)
14690            .as_singleton()
14691            .and_then(|b| b.read(cx).file());
14692        let file_extension = file_extension.or(file
14693            .as_ref()
14694            .and_then(|file| Path::new(file.file_name(cx)).extension())
14695            .and_then(|e| e.to_str())
14696            .map(|a| a.to_string()));
14697
14698        let vim_mode = cx
14699            .global::<SettingsStore>()
14700            .raw_user_settings()
14701            .get("vim_mode")
14702            == Some(&serde_json::Value::Bool(true));
14703
14704        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14705        let copilot_enabled = edit_predictions_provider
14706            == language::language_settings::EditPredictionProvider::Copilot;
14707        let copilot_enabled_for_language = self
14708            .buffer
14709            .read(cx)
14710            .settings_at(0, cx)
14711            .show_edit_predictions;
14712
14713        let project = project.read(cx);
14714        telemetry::event!(
14715            event_type,
14716            file_extension,
14717            vim_mode,
14718            copilot_enabled,
14719            copilot_enabled_for_language,
14720            edit_predictions_provider,
14721            is_via_ssh = project.is_via_ssh(),
14722        );
14723    }
14724
14725    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14726    /// with each line being an array of {text, highlight} objects.
14727    fn copy_highlight_json(
14728        &mut self,
14729        _: &CopyHighlightJson,
14730        window: &mut Window,
14731        cx: &mut Context<Self>,
14732    ) {
14733        #[derive(Serialize)]
14734        struct Chunk<'a> {
14735            text: String,
14736            highlight: Option<&'a str>,
14737        }
14738
14739        let snapshot = self.buffer.read(cx).snapshot(cx);
14740        let range = self
14741            .selected_text_range(false, window, cx)
14742            .and_then(|selection| {
14743                if selection.range.is_empty() {
14744                    None
14745                } else {
14746                    Some(selection.range)
14747                }
14748            })
14749            .unwrap_or_else(|| 0..snapshot.len());
14750
14751        let chunks = snapshot.chunks(range, true);
14752        let mut lines = Vec::new();
14753        let mut line: VecDeque<Chunk> = VecDeque::new();
14754
14755        let Some(style) = self.style.as_ref() else {
14756            return;
14757        };
14758
14759        for chunk in chunks {
14760            let highlight = chunk
14761                .syntax_highlight_id
14762                .and_then(|id| id.name(&style.syntax));
14763            let mut chunk_lines = chunk.text.split('\n').peekable();
14764            while let Some(text) = chunk_lines.next() {
14765                let mut merged_with_last_token = false;
14766                if let Some(last_token) = line.back_mut() {
14767                    if last_token.highlight == highlight {
14768                        last_token.text.push_str(text);
14769                        merged_with_last_token = true;
14770                    }
14771                }
14772
14773                if !merged_with_last_token {
14774                    line.push_back(Chunk {
14775                        text: text.into(),
14776                        highlight,
14777                    });
14778                }
14779
14780                if chunk_lines.peek().is_some() {
14781                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14782                        line.pop_front();
14783                    }
14784                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14785                        line.pop_back();
14786                    }
14787
14788                    lines.push(mem::take(&mut line));
14789                }
14790            }
14791        }
14792
14793        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14794            return;
14795        };
14796        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14797    }
14798
14799    pub fn open_context_menu(
14800        &mut self,
14801        _: &OpenContextMenu,
14802        window: &mut Window,
14803        cx: &mut Context<Self>,
14804    ) {
14805        self.request_autoscroll(Autoscroll::newest(), cx);
14806        let position = self.selections.newest_display(cx).start;
14807        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14808    }
14809
14810    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14811        &self.inlay_hint_cache
14812    }
14813
14814    pub fn replay_insert_event(
14815        &mut self,
14816        text: &str,
14817        relative_utf16_range: Option<Range<isize>>,
14818        window: &mut Window,
14819        cx: &mut Context<Self>,
14820    ) {
14821        if !self.input_enabled {
14822            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14823            return;
14824        }
14825        if let Some(relative_utf16_range) = relative_utf16_range {
14826            let selections = self.selections.all::<OffsetUtf16>(cx);
14827            self.change_selections(None, window, cx, |s| {
14828                let new_ranges = selections.into_iter().map(|range| {
14829                    let start = OffsetUtf16(
14830                        range
14831                            .head()
14832                            .0
14833                            .saturating_add_signed(relative_utf16_range.start),
14834                    );
14835                    let end = OffsetUtf16(
14836                        range
14837                            .head()
14838                            .0
14839                            .saturating_add_signed(relative_utf16_range.end),
14840                    );
14841                    start..end
14842                });
14843                s.select_ranges(new_ranges);
14844            });
14845        }
14846
14847        self.handle_input(text, window, cx);
14848    }
14849
14850    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14851        let Some(provider) = self.semantics_provider.as_ref() else {
14852            return false;
14853        };
14854
14855        let mut supports = false;
14856        self.buffer().update(cx, |this, cx| {
14857            this.for_each_buffer(|buffer| {
14858                supports |= provider.supports_inlay_hints(buffer, cx);
14859            });
14860        });
14861
14862        supports
14863    }
14864
14865    pub fn is_focused(&self, window: &Window) -> bool {
14866        self.focus_handle.is_focused(window)
14867    }
14868
14869    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14870        cx.emit(EditorEvent::Focused);
14871
14872        if let Some(descendant) = self
14873            .last_focused_descendant
14874            .take()
14875            .and_then(|descendant| descendant.upgrade())
14876        {
14877            window.focus(&descendant);
14878        } else {
14879            if let Some(blame) = self.blame.as_ref() {
14880                blame.update(cx, GitBlame::focus)
14881            }
14882
14883            self.blink_manager.update(cx, BlinkManager::enable);
14884            self.show_cursor_names(window, cx);
14885            self.buffer.update(cx, |buffer, cx| {
14886                buffer.finalize_last_transaction(cx);
14887                if self.leader_peer_id.is_none() {
14888                    buffer.set_active_selections(
14889                        &self.selections.disjoint_anchors(),
14890                        self.selections.line_mode,
14891                        self.cursor_shape,
14892                        cx,
14893                    );
14894                }
14895            });
14896        }
14897    }
14898
14899    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14900        cx.emit(EditorEvent::FocusedIn)
14901    }
14902
14903    fn handle_focus_out(
14904        &mut self,
14905        event: FocusOutEvent,
14906        _window: &mut Window,
14907        _cx: &mut Context<Self>,
14908    ) {
14909        if event.blurred != self.focus_handle {
14910            self.last_focused_descendant = Some(event.blurred);
14911        }
14912    }
14913
14914    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14915        self.blink_manager.update(cx, BlinkManager::disable);
14916        self.buffer
14917            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14918
14919        if let Some(blame) = self.blame.as_ref() {
14920            blame.update(cx, GitBlame::blur)
14921        }
14922        if !self.hover_state.focused(window, cx) {
14923            hide_hover(self, cx);
14924        }
14925        if !self
14926            .context_menu
14927            .borrow()
14928            .as_ref()
14929            .is_some_and(|context_menu| context_menu.focused(window, cx))
14930        {
14931            self.hide_context_menu(window, cx);
14932        }
14933        self.discard_inline_completion(false, cx);
14934        cx.emit(EditorEvent::Blurred);
14935        cx.notify();
14936    }
14937
14938    pub fn register_action<A: Action>(
14939        &mut self,
14940        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14941    ) -> Subscription {
14942        let id = self.next_editor_action_id.post_inc();
14943        let listener = Arc::new(listener);
14944        self.editor_actions.borrow_mut().insert(
14945            id,
14946            Box::new(move |window, _| {
14947                let listener = listener.clone();
14948                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14949                    let action = action.downcast_ref().unwrap();
14950                    if phase == DispatchPhase::Bubble {
14951                        listener(action, window, cx)
14952                    }
14953                })
14954            }),
14955        );
14956
14957        let editor_actions = self.editor_actions.clone();
14958        Subscription::new(move || {
14959            editor_actions.borrow_mut().remove(&id);
14960        })
14961    }
14962
14963    pub fn file_header_size(&self) -> u32 {
14964        FILE_HEADER_HEIGHT
14965    }
14966
14967    pub fn revert(
14968        &mut self,
14969        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14970        window: &mut Window,
14971        cx: &mut Context<Self>,
14972    ) {
14973        self.buffer().update(cx, |multi_buffer, cx| {
14974            for (buffer_id, changes) in revert_changes {
14975                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14976                    buffer.update(cx, |buffer, cx| {
14977                        buffer.edit(
14978                            changes.into_iter().map(|(range, text)| {
14979                                (range, text.to_string().map(Arc::<str>::from))
14980                            }),
14981                            None,
14982                            cx,
14983                        );
14984                    });
14985                }
14986            }
14987        });
14988        self.change_selections(None, window, cx, |selections| selections.refresh());
14989    }
14990
14991    pub fn to_pixel_point(
14992        &self,
14993        source: multi_buffer::Anchor,
14994        editor_snapshot: &EditorSnapshot,
14995        window: &mut Window,
14996    ) -> Option<gpui::Point<Pixels>> {
14997        let source_point = source.to_display_point(editor_snapshot);
14998        self.display_to_pixel_point(source_point, editor_snapshot, window)
14999    }
15000
15001    pub fn display_to_pixel_point(
15002        &self,
15003        source: DisplayPoint,
15004        editor_snapshot: &EditorSnapshot,
15005        window: &mut Window,
15006    ) -> Option<gpui::Point<Pixels>> {
15007        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15008        let text_layout_details = self.text_layout_details(window);
15009        let scroll_top = text_layout_details
15010            .scroll_anchor
15011            .scroll_position(editor_snapshot)
15012            .y;
15013
15014        if source.row().as_f32() < scroll_top.floor() {
15015            return None;
15016        }
15017        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15018        let source_y = line_height * (source.row().as_f32() - scroll_top);
15019        Some(gpui::Point::new(source_x, source_y))
15020    }
15021
15022    pub fn has_visible_completions_menu(&self) -> bool {
15023        !self.edit_prediction_preview_is_active()
15024            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15025                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15026            })
15027    }
15028
15029    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15030        self.addons
15031            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15032    }
15033
15034    pub fn unregister_addon<T: Addon>(&mut self) {
15035        self.addons.remove(&std::any::TypeId::of::<T>());
15036    }
15037
15038    pub fn addon<T: Addon>(&self) -> Option<&T> {
15039        let type_id = std::any::TypeId::of::<T>();
15040        self.addons
15041            .get(&type_id)
15042            .and_then(|item| item.to_any().downcast_ref::<T>())
15043    }
15044
15045    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15046        let text_layout_details = self.text_layout_details(window);
15047        let style = &text_layout_details.editor_style;
15048        let font_id = window.text_system().resolve_font(&style.text.font());
15049        let font_size = style.text.font_size.to_pixels(window.rem_size());
15050        let line_height = style.text.line_height_in_pixels(window.rem_size());
15051        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15052
15053        gpui::Size::new(em_width, line_height)
15054    }
15055
15056    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15057        self.load_diff_task.clone()
15058    }
15059
15060    fn read_selections_from_db(
15061        &mut self,
15062        item_id: u64,
15063        workspace_id: WorkspaceId,
15064        window: &mut Window,
15065        cx: &mut Context<Editor>,
15066    ) {
15067        if !self.is_singleton(cx)
15068            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15069        {
15070            return;
15071        }
15072        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15073            return;
15074        };
15075        if selections.is_empty() {
15076            return;
15077        }
15078
15079        let snapshot = self.buffer.read(cx).snapshot(cx);
15080        self.change_selections(None, window, cx, |s| {
15081            s.select_ranges(selections.into_iter().map(|(start, end)| {
15082                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15083            }));
15084        });
15085    }
15086}
15087
15088fn get_uncommitted_diff_for_buffer(
15089    project: &Entity<Project>,
15090    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15091    buffer: Entity<MultiBuffer>,
15092    cx: &mut App,
15093) -> Task<()> {
15094    let mut tasks = Vec::new();
15095    project.update(cx, |project, cx| {
15096        for buffer in buffers {
15097            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15098        }
15099    });
15100    cx.spawn(|mut cx| async move {
15101        let diffs = futures::future::join_all(tasks).await;
15102        buffer
15103            .update(&mut cx, |buffer, cx| {
15104                for diff in diffs.into_iter().flatten() {
15105                    buffer.add_diff(diff, cx);
15106                }
15107            })
15108            .ok();
15109    })
15110}
15111
15112fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15113    let tab_size = tab_size.get() as usize;
15114    let mut width = offset;
15115
15116    for ch in text.chars() {
15117        width += if ch == '\t' {
15118            tab_size - (width % tab_size)
15119        } else {
15120            1
15121        };
15122    }
15123
15124    width - offset
15125}
15126
15127#[cfg(test)]
15128mod tests {
15129    use super::*;
15130
15131    #[test]
15132    fn test_string_size_with_expanded_tabs() {
15133        let nz = |val| NonZeroU32::new(val).unwrap();
15134        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15135        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15136        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15137        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15138        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15139        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15140        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15141        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15142    }
15143}
15144
15145/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15146struct WordBreakingTokenizer<'a> {
15147    input: &'a str,
15148}
15149
15150impl<'a> WordBreakingTokenizer<'a> {
15151    fn new(input: &'a str) -> Self {
15152        Self { input }
15153    }
15154}
15155
15156fn is_char_ideographic(ch: char) -> bool {
15157    use unicode_script::Script::*;
15158    use unicode_script::UnicodeScript;
15159    matches!(ch.script(), Han | Tangut | Yi)
15160}
15161
15162fn is_grapheme_ideographic(text: &str) -> bool {
15163    text.chars().any(is_char_ideographic)
15164}
15165
15166fn is_grapheme_whitespace(text: &str) -> bool {
15167    text.chars().any(|x| x.is_whitespace())
15168}
15169
15170fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15171    text.chars().next().map_or(false, |ch| {
15172        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15173    })
15174}
15175
15176#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15177struct WordBreakToken<'a> {
15178    token: &'a str,
15179    grapheme_len: usize,
15180    is_whitespace: bool,
15181}
15182
15183impl<'a> Iterator for WordBreakingTokenizer<'a> {
15184    /// Yields a span, the count of graphemes in the token, and whether it was
15185    /// whitespace. Note that it also breaks at word boundaries.
15186    type Item = WordBreakToken<'a>;
15187
15188    fn next(&mut self) -> Option<Self::Item> {
15189        use unicode_segmentation::UnicodeSegmentation;
15190        if self.input.is_empty() {
15191            return None;
15192        }
15193
15194        let mut iter = self.input.graphemes(true).peekable();
15195        let mut offset = 0;
15196        let mut graphemes = 0;
15197        if let Some(first_grapheme) = iter.next() {
15198            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15199            offset += first_grapheme.len();
15200            graphemes += 1;
15201            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15202                if let Some(grapheme) = iter.peek().copied() {
15203                    if should_stay_with_preceding_ideograph(grapheme) {
15204                        offset += grapheme.len();
15205                        graphemes += 1;
15206                    }
15207                }
15208            } else {
15209                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15210                let mut next_word_bound = words.peek().copied();
15211                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15212                    next_word_bound = words.next();
15213                }
15214                while let Some(grapheme) = iter.peek().copied() {
15215                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15216                        break;
15217                    };
15218                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15219                        break;
15220                    };
15221                    offset += grapheme.len();
15222                    graphemes += 1;
15223                    iter.next();
15224                }
15225            }
15226            let token = &self.input[..offset];
15227            self.input = &self.input[offset..];
15228            if is_whitespace {
15229                Some(WordBreakToken {
15230                    token: " ",
15231                    grapheme_len: 1,
15232                    is_whitespace: true,
15233                })
15234            } else {
15235                Some(WordBreakToken {
15236                    token,
15237                    grapheme_len: graphemes,
15238                    is_whitespace: false,
15239                })
15240            }
15241        } else {
15242            None
15243        }
15244    }
15245}
15246
15247#[test]
15248fn test_word_breaking_tokenizer() {
15249    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15250        ("", &[]),
15251        ("  ", &[(" ", 1, true)]),
15252        ("Ʒ", &[("Ʒ", 1, false)]),
15253        ("Ǽ", &[("Ǽ", 1, false)]),
15254        ("", &[("", 1, false)]),
15255        ("⋑⋑", &[("⋑⋑", 2, false)]),
15256        (
15257            "原理,进而",
15258            &[
15259                ("", 1, false),
15260                ("理,", 2, false),
15261                ("", 1, false),
15262                ("", 1, false),
15263            ],
15264        ),
15265        (
15266            "hello world",
15267            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15268        ),
15269        (
15270            "hello, world",
15271            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15272        ),
15273        (
15274            "  hello world",
15275            &[
15276                (" ", 1, true),
15277                ("hello", 5, false),
15278                (" ", 1, true),
15279                ("world", 5, false),
15280            ],
15281        ),
15282        (
15283            "这是什么 \n 钢笔",
15284            &[
15285                ("", 1, false),
15286                ("", 1, false),
15287                ("", 1, false),
15288                ("", 1, false),
15289                (" ", 1, true),
15290                ("", 1, false),
15291                ("", 1, false),
15292            ],
15293        ),
15294        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15295    ];
15296
15297    for (input, result) in tests {
15298        assert_eq!(
15299            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15300            result
15301                .iter()
15302                .copied()
15303                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15304                    token,
15305                    grapheme_len,
15306                    is_whitespace,
15307                })
15308                .collect::<Vec<_>>()
15309        );
15310    }
15311}
15312
15313fn wrap_with_prefix(
15314    line_prefix: String,
15315    unwrapped_text: String,
15316    wrap_column: usize,
15317    tab_size: NonZeroU32,
15318) -> String {
15319    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15320    let mut wrapped_text = String::new();
15321    let mut current_line = line_prefix.clone();
15322
15323    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15324    let mut current_line_len = line_prefix_len;
15325    for WordBreakToken {
15326        token,
15327        grapheme_len,
15328        is_whitespace,
15329    } in tokenizer
15330    {
15331        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15332            wrapped_text.push_str(current_line.trim_end());
15333            wrapped_text.push('\n');
15334            current_line.truncate(line_prefix.len());
15335            current_line_len = line_prefix_len;
15336            if !is_whitespace {
15337                current_line.push_str(token);
15338                current_line_len += grapheme_len;
15339            }
15340        } else if !is_whitespace {
15341            current_line.push_str(token);
15342            current_line_len += grapheme_len;
15343        } else if current_line_len != line_prefix_len {
15344            current_line.push(' ');
15345            current_line_len += 1;
15346        }
15347    }
15348
15349    if !current_line.is_empty() {
15350        wrapped_text.push_str(&current_line);
15351    }
15352    wrapped_text
15353}
15354
15355#[test]
15356fn test_wrap_with_prefix() {
15357    assert_eq!(
15358        wrap_with_prefix(
15359            "# ".to_string(),
15360            "abcdefg".to_string(),
15361            4,
15362            NonZeroU32::new(4).unwrap()
15363        ),
15364        "# abcdefg"
15365    );
15366    assert_eq!(
15367        wrap_with_prefix(
15368            "".to_string(),
15369            "\thello world".to_string(),
15370            8,
15371            NonZeroU32::new(4).unwrap()
15372        ),
15373        "hello\nworld"
15374    );
15375    assert_eq!(
15376        wrap_with_prefix(
15377            "// ".to_string(),
15378            "xx \nyy zz aa bb cc".to_string(),
15379            12,
15380            NonZeroU32::new(4).unwrap()
15381        ),
15382        "// xx yy zz\n// aa bb cc"
15383    );
15384    assert_eq!(
15385        wrap_with_prefix(
15386            String::new(),
15387            "这是什么 \n 钢笔".to_string(),
15388            3,
15389            NonZeroU32::new(4).unwrap()
15390        ),
15391        "这是什\n么 钢\n"
15392    );
15393}
15394
15395pub trait CollaborationHub {
15396    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15397    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15398    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15399}
15400
15401impl CollaborationHub for Entity<Project> {
15402    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15403        self.read(cx).collaborators()
15404    }
15405
15406    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15407        self.read(cx).user_store().read(cx).participant_indices()
15408    }
15409
15410    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15411        let this = self.read(cx);
15412        let user_ids = this.collaborators().values().map(|c| c.user_id);
15413        this.user_store().read_with(cx, |user_store, cx| {
15414            user_store.participant_names(user_ids, cx)
15415        })
15416    }
15417}
15418
15419pub trait SemanticsProvider {
15420    fn hover(
15421        &self,
15422        buffer: &Entity<Buffer>,
15423        position: text::Anchor,
15424        cx: &mut App,
15425    ) -> Option<Task<Vec<project::Hover>>>;
15426
15427    fn inlay_hints(
15428        &self,
15429        buffer_handle: Entity<Buffer>,
15430        range: Range<text::Anchor>,
15431        cx: &mut App,
15432    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15433
15434    fn resolve_inlay_hint(
15435        &self,
15436        hint: InlayHint,
15437        buffer_handle: Entity<Buffer>,
15438        server_id: LanguageServerId,
15439        cx: &mut App,
15440    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15441
15442    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15443
15444    fn document_highlights(
15445        &self,
15446        buffer: &Entity<Buffer>,
15447        position: text::Anchor,
15448        cx: &mut App,
15449    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15450
15451    fn definitions(
15452        &self,
15453        buffer: &Entity<Buffer>,
15454        position: text::Anchor,
15455        kind: GotoDefinitionKind,
15456        cx: &mut App,
15457    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15458
15459    fn range_for_rename(
15460        &self,
15461        buffer: &Entity<Buffer>,
15462        position: text::Anchor,
15463        cx: &mut App,
15464    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15465
15466    fn perform_rename(
15467        &self,
15468        buffer: &Entity<Buffer>,
15469        position: text::Anchor,
15470        new_name: String,
15471        cx: &mut App,
15472    ) -> Option<Task<Result<ProjectTransaction>>>;
15473}
15474
15475pub trait CompletionProvider {
15476    fn completions(
15477        &self,
15478        buffer: &Entity<Buffer>,
15479        buffer_position: text::Anchor,
15480        trigger: CompletionContext,
15481        window: &mut Window,
15482        cx: &mut Context<Editor>,
15483    ) -> Task<Result<Vec<Completion>>>;
15484
15485    fn resolve_completions(
15486        &self,
15487        buffer: Entity<Buffer>,
15488        completion_indices: Vec<usize>,
15489        completions: Rc<RefCell<Box<[Completion]>>>,
15490        cx: &mut Context<Editor>,
15491    ) -> Task<Result<bool>>;
15492
15493    fn apply_additional_edits_for_completion(
15494        &self,
15495        _buffer: Entity<Buffer>,
15496        _completions: Rc<RefCell<Box<[Completion]>>>,
15497        _completion_index: usize,
15498        _push_to_history: bool,
15499        _cx: &mut Context<Editor>,
15500    ) -> Task<Result<Option<language::Transaction>>> {
15501        Task::ready(Ok(None))
15502    }
15503
15504    fn is_completion_trigger(
15505        &self,
15506        buffer: &Entity<Buffer>,
15507        position: language::Anchor,
15508        text: &str,
15509        trigger_in_words: bool,
15510        cx: &mut Context<Editor>,
15511    ) -> bool;
15512
15513    fn sort_completions(&self) -> bool {
15514        true
15515    }
15516}
15517
15518pub trait CodeActionProvider {
15519    fn id(&self) -> Arc<str>;
15520
15521    fn code_actions(
15522        &self,
15523        buffer: &Entity<Buffer>,
15524        range: Range<text::Anchor>,
15525        window: &mut Window,
15526        cx: &mut App,
15527    ) -> Task<Result<Vec<CodeAction>>>;
15528
15529    fn apply_code_action(
15530        &self,
15531        buffer_handle: Entity<Buffer>,
15532        action: CodeAction,
15533        excerpt_id: ExcerptId,
15534        push_to_history: bool,
15535        window: &mut Window,
15536        cx: &mut App,
15537    ) -> Task<Result<ProjectTransaction>>;
15538}
15539
15540impl CodeActionProvider for Entity<Project> {
15541    fn id(&self) -> Arc<str> {
15542        "project".into()
15543    }
15544
15545    fn code_actions(
15546        &self,
15547        buffer: &Entity<Buffer>,
15548        range: Range<text::Anchor>,
15549        _window: &mut Window,
15550        cx: &mut App,
15551    ) -> Task<Result<Vec<CodeAction>>> {
15552        self.update(cx, |project, cx| {
15553            project.code_actions(buffer, range, None, cx)
15554        })
15555    }
15556
15557    fn apply_code_action(
15558        &self,
15559        buffer_handle: Entity<Buffer>,
15560        action: CodeAction,
15561        _excerpt_id: ExcerptId,
15562        push_to_history: bool,
15563        _window: &mut Window,
15564        cx: &mut App,
15565    ) -> Task<Result<ProjectTransaction>> {
15566        self.update(cx, |project, cx| {
15567            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15568        })
15569    }
15570}
15571
15572fn snippet_completions(
15573    project: &Project,
15574    buffer: &Entity<Buffer>,
15575    buffer_position: text::Anchor,
15576    cx: &mut App,
15577) -> Task<Result<Vec<Completion>>> {
15578    let language = buffer.read(cx).language_at(buffer_position);
15579    let language_name = language.as_ref().map(|language| language.lsp_id());
15580    let snippet_store = project.snippets().read(cx);
15581    let snippets = snippet_store.snippets_for(language_name, cx);
15582
15583    if snippets.is_empty() {
15584        return Task::ready(Ok(vec![]));
15585    }
15586    let snapshot = buffer.read(cx).text_snapshot();
15587    let chars: String = snapshot
15588        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15589        .collect();
15590
15591    let scope = language.map(|language| language.default_scope());
15592    let executor = cx.background_executor().clone();
15593
15594    cx.background_spawn(async move {
15595        let classifier = CharClassifier::new(scope).for_completion(true);
15596        let mut last_word = chars
15597            .chars()
15598            .take_while(|c| classifier.is_word(*c))
15599            .collect::<String>();
15600        last_word = last_word.chars().rev().collect();
15601
15602        if last_word.is_empty() {
15603            return Ok(vec![]);
15604        }
15605
15606        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15607        let to_lsp = |point: &text::Anchor| {
15608            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15609            point_to_lsp(end)
15610        };
15611        let lsp_end = to_lsp(&buffer_position);
15612
15613        let candidates = snippets
15614            .iter()
15615            .enumerate()
15616            .flat_map(|(ix, snippet)| {
15617                snippet
15618                    .prefix
15619                    .iter()
15620                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15621            })
15622            .collect::<Vec<StringMatchCandidate>>();
15623
15624        let mut matches = fuzzy::match_strings(
15625            &candidates,
15626            &last_word,
15627            last_word.chars().any(|c| c.is_uppercase()),
15628            100,
15629            &Default::default(),
15630            executor,
15631        )
15632        .await;
15633
15634        // Remove all candidates where the query's start does not match the start of any word in the candidate
15635        if let Some(query_start) = last_word.chars().next() {
15636            matches.retain(|string_match| {
15637                split_words(&string_match.string).any(|word| {
15638                    // Check that the first codepoint of the word as lowercase matches the first
15639                    // codepoint of the query as lowercase
15640                    word.chars()
15641                        .flat_map(|codepoint| codepoint.to_lowercase())
15642                        .zip(query_start.to_lowercase())
15643                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15644                })
15645            });
15646        }
15647
15648        let matched_strings = matches
15649            .into_iter()
15650            .map(|m| m.string)
15651            .collect::<HashSet<_>>();
15652
15653        let result: Vec<Completion> = snippets
15654            .into_iter()
15655            .filter_map(|snippet| {
15656                let matching_prefix = snippet
15657                    .prefix
15658                    .iter()
15659                    .find(|prefix| matched_strings.contains(*prefix))?;
15660                let start = as_offset - last_word.len();
15661                let start = snapshot.anchor_before(start);
15662                let range = start..buffer_position;
15663                let lsp_start = to_lsp(&start);
15664                let lsp_range = lsp::Range {
15665                    start: lsp_start,
15666                    end: lsp_end,
15667                };
15668                Some(Completion {
15669                    old_range: range,
15670                    new_text: snippet.body.clone(),
15671                    resolved: false,
15672                    label: CodeLabel {
15673                        text: matching_prefix.clone(),
15674                        runs: vec![],
15675                        filter_range: 0..matching_prefix.len(),
15676                    },
15677                    server_id: LanguageServerId(usize::MAX),
15678                    documentation: snippet
15679                        .description
15680                        .clone()
15681                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
15682                    lsp_completion: lsp::CompletionItem {
15683                        label: snippet.prefix.first().unwrap().clone(),
15684                        kind: Some(CompletionItemKind::SNIPPET),
15685                        label_details: snippet.description.as_ref().map(|description| {
15686                            lsp::CompletionItemLabelDetails {
15687                                detail: Some(description.clone()),
15688                                description: None,
15689                            }
15690                        }),
15691                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15692                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15693                            lsp::InsertReplaceEdit {
15694                                new_text: snippet.body.clone(),
15695                                insert: lsp_range,
15696                                replace: lsp_range,
15697                            },
15698                        )),
15699                        filter_text: Some(snippet.body.clone()),
15700                        sort_text: Some(char::MAX.to_string()),
15701                        ..Default::default()
15702                    },
15703                    confirm: None,
15704                })
15705            })
15706            .collect();
15707
15708        Ok(result)
15709    })
15710}
15711
15712impl CompletionProvider for Entity<Project> {
15713    fn completions(
15714        &self,
15715        buffer: &Entity<Buffer>,
15716        buffer_position: text::Anchor,
15717        options: CompletionContext,
15718        _window: &mut Window,
15719        cx: &mut Context<Editor>,
15720    ) -> Task<Result<Vec<Completion>>> {
15721        self.update(cx, |project, cx| {
15722            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15723            let project_completions = project.completions(buffer, buffer_position, options, cx);
15724            cx.background_spawn(async move {
15725                let mut completions = project_completions.await?;
15726                let snippets_completions = snippets.await?;
15727                completions.extend(snippets_completions);
15728                Ok(completions)
15729            })
15730        })
15731    }
15732
15733    fn resolve_completions(
15734        &self,
15735        buffer: Entity<Buffer>,
15736        completion_indices: Vec<usize>,
15737        completions: Rc<RefCell<Box<[Completion]>>>,
15738        cx: &mut Context<Editor>,
15739    ) -> Task<Result<bool>> {
15740        self.update(cx, |project, cx| {
15741            project.lsp_store().update(cx, |lsp_store, cx| {
15742                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15743            })
15744        })
15745    }
15746
15747    fn apply_additional_edits_for_completion(
15748        &self,
15749        buffer: Entity<Buffer>,
15750        completions: Rc<RefCell<Box<[Completion]>>>,
15751        completion_index: usize,
15752        push_to_history: bool,
15753        cx: &mut Context<Editor>,
15754    ) -> Task<Result<Option<language::Transaction>>> {
15755        self.update(cx, |project, cx| {
15756            project.lsp_store().update(cx, |lsp_store, cx| {
15757                lsp_store.apply_additional_edits_for_completion(
15758                    buffer,
15759                    completions,
15760                    completion_index,
15761                    push_to_history,
15762                    cx,
15763                )
15764            })
15765        })
15766    }
15767
15768    fn is_completion_trigger(
15769        &self,
15770        buffer: &Entity<Buffer>,
15771        position: language::Anchor,
15772        text: &str,
15773        trigger_in_words: bool,
15774        cx: &mut Context<Editor>,
15775    ) -> bool {
15776        let mut chars = text.chars();
15777        let char = if let Some(char) = chars.next() {
15778            char
15779        } else {
15780            return false;
15781        };
15782        if chars.next().is_some() {
15783            return false;
15784        }
15785
15786        let buffer = buffer.read(cx);
15787        let snapshot = buffer.snapshot();
15788        if !snapshot.settings_at(position, cx).show_completions_on_input {
15789            return false;
15790        }
15791        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15792        if trigger_in_words && classifier.is_word(char) {
15793            return true;
15794        }
15795
15796        buffer.completion_triggers().contains(text)
15797    }
15798}
15799
15800impl SemanticsProvider for Entity<Project> {
15801    fn hover(
15802        &self,
15803        buffer: &Entity<Buffer>,
15804        position: text::Anchor,
15805        cx: &mut App,
15806    ) -> Option<Task<Vec<project::Hover>>> {
15807        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15808    }
15809
15810    fn document_highlights(
15811        &self,
15812        buffer: &Entity<Buffer>,
15813        position: text::Anchor,
15814        cx: &mut App,
15815    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15816        Some(self.update(cx, |project, cx| {
15817            project.document_highlights(buffer, position, cx)
15818        }))
15819    }
15820
15821    fn definitions(
15822        &self,
15823        buffer: &Entity<Buffer>,
15824        position: text::Anchor,
15825        kind: GotoDefinitionKind,
15826        cx: &mut App,
15827    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15828        Some(self.update(cx, |project, cx| match kind {
15829            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15830            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15831            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15832            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15833        }))
15834    }
15835
15836    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15837        // TODO: make this work for remote projects
15838        self.update(cx, |this, cx| {
15839            buffer.update(cx, |buffer, cx| {
15840                this.any_language_server_supports_inlay_hints(buffer, cx)
15841            })
15842        })
15843    }
15844
15845    fn inlay_hints(
15846        &self,
15847        buffer_handle: Entity<Buffer>,
15848        range: Range<text::Anchor>,
15849        cx: &mut App,
15850    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15851        Some(self.update(cx, |project, cx| {
15852            project.inlay_hints(buffer_handle, range, cx)
15853        }))
15854    }
15855
15856    fn resolve_inlay_hint(
15857        &self,
15858        hint: InlayHint,
15859        buffer_handle: Entity<Buffer>,
15860        server_id: LanguageServerId,
15861        cx: &mut App,
15862    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15863        Some(self.update(cx, |project, cx| {
15864            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15865        }))
15866    }
15867
15868    fn range_for_rename(
15869        &self,
15870        buffer: &Entity<Buffer>,
15871        position: text::Anchor,
15872        cx: &mut App,
15873    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15874        Some(self.update(cx, |project, cx| {
15875            let buffer = buffer.clone();
15876            let task = project.prepare_rename(buffer.clone(), position, cx);
15877            cx.spawn(|_, mut cx| async move {
15878                Ok(match task.await? {
15879                    PrepareRenameResponse::Success(range) => Some(range),
15880                    PrepareRenameResponse::InvalidPosition => None,
15881                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15882                        // Fallback on using TreeSitter info to determine identifier range
15883                        buffer.update(&mut cx, |buffer, _| {
15884                            let snapshot = buffer.snapshot();
15885                            let (range, kind) = snapshot.surrounding_word(position);
15886                            if kind != Some(CharKind::Word) {
15887                                return None;
15888                            }
15889                            Some(
15890                                snapshot.anchor_before(range.start)
15891                                    ..snapshot.anchor_after(range.end),
15892                            )
15893                        })?
15894                    }
15895                })
15896            })
15897        }))
15898    }
15899
15900    fn perform_rename(
15901        &self,
15902        buffer: &Entity<Buffer>,
15903        position: text::Anchor,
15904        new_name: String,
15905        cx: &mut App,
15906    ) -> Option<Task<Result<ProjectTransaction>>> {
15907        Some(self.update(cx, |project, cx| {
15908            project.perform_rename(buffer.clone(), position, new_name, cx)
15909        }))
15910    }
15911}
15912
15913fn inlay_hint_settings(
15914    location: Anchor,
15915    snapshot: &MultiBufferSnapshot,
15916    cx: &mut Context<Editor>,
15917) -> InlayHintSettings {
15918    let file = snapshot.file_at(location);
15919    let language = snapshot.language_at(location).map(|l| l.name());
15920    language_settings(language, file, cx).inlay_hints
15921}
15922
15923fn consume_contiguous_rows(
15924    contiguous_row_selections: &mut Vec<Selection<Point>>,
15925    selection: &Selection<Point>,
15926    display_map: &DisplaySnapshot,
15927    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15928) -> (MultiBufferRow, MultiBufferRow) {
15929    contiguous_row_selections.push(selection.clone());
15930    let start_row = MultiBufferRow(selection.start.row);
15931    let mut end_row = ending_row(selection, display_map);
15932
15933    while let Some(next_selection) = selections.peek() {
15934        if next_selection.start.row <= end_row.0 {
15935            end_row = ending_row(next_selection, display_map);
15936            contiguous_row_selections.push(selections.next().unwrap().clone());
15937        } else {
15938            break;
15939        }
15940    }
15941    (start_row, end_row)
15942}
15943
15944fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15945    if next_selection.end.column > 0 || next_selection.is_empty() {
15946        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15947    } else {
15948        MultiBufferRow(next_selection.end.row)
15949    }
15950}
15951
15952impl EditorSnapshot {
15953    pub fn remote_selections_in_range<'a>(
15954        &'a self,
15955        range: &'a Range<Anchor>,
15956        collaboration_hub: &dyn CollaborationHub,
15957        cx: &'a App,
15958    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15959        let participant_names = collaboration_hub.user_names(cx);
15960        let participant_indices = collaboration_hub.user_participant_indices(cx);
15961        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15962        let collaborators_by_replica_id = collaborators_by_peer_id
15963            .iter()
15964            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15965            .collect::<HashMap<_, _>>();
15966        self.buffer_snapshot
15967            .selections_in_range(range, false)
15968            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15969                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15970                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15971                let user_name = participant_names.get(&collaborator.user_id).cloned();
15972                Some(RemoteSelection {
15973                    replica_id,
15974                    selection,
15975                    cursor_shape,
15976                    line_mode,
15977                    participant_index,
15978                    peer_id: collaborator.peer_id,
15979                    user_name,
15980                })
15981            })
15982    }
15983
15984    pub fn hunks_for_ranges(
15985        &self,
15986        ranges: impl Iterator<Item = Range<Point>>,
15987    ) -> Vec<MultiBufferDiffHunk> {
15988        let mut hunks = Vec::new();
15989        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15990            HashMap::default();
15991        for query_range in ranges {
15992            let query_rows =
15993                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15994            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15995                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15996            ) {
15997                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15998                // when the caret is just above or just below the deleted hunk.
15999                let allow_adjacent = hunk.status().is_removed();
16000                let related_to_selection = if allow_adjacent {
16001                    hunk.row_range.overlaps(&query_rows)
16002                        || hunk.row_range.start == query_rows.end
16003                        || hunk.row_range.end == query_rows.start
16004                } else {
16005                    hunk.row_range.overlaps(&query_rows)
16006                };
16007                if related_to_selection {
16008                    if !processed_buffer_rows
16009                        .entry(hunk.buffer_id)
16010                        .or_default()
16011                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16012                    {
16013                        continue;
16014                    }
16015                    hunks.push(hunk);
16016                }
16017            }
16018        }
16019
16020        hunks
16021    }
16022
16023    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16024        self.display_snapshot.buffer_snapshot.language_at(position)
16025    }
16026
16027    pub fn is_focused(&self) -> bool {
16028        self.is_focused
16029    }
16030
16031    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16032        self.placeholder_text.as_ref()
16033    }
16034
16035    pub fn scroll_position(&self) -> gpui::Point<f32> {
16036        self.scroll_anchor.scroll_position(&self.display_snapshot)
16037    }
16038
16039    fn gutter_dimensions(
16040        &self,
16041        font_id: FontId,
16042        font_size: Pixels,
16043        max_line_number_width: Pixels,
16044        cx: &App,
16045    ) -> Option<GutterDimensions> {
16046        if !self.show_gutter {
16047            return None;
16048        }
16049
16050        let descent = cx.text_system().descent(font_id, font_size);
16051        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16052        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16053
16054        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16055            matches!(
16056                ProjectSettings::get_global(cx).git.git_gutter,
16057                Some(GitGutterSetting::TrackedFiles)
16058            )
16059        });
16060        let gutter_settings = EditorSettings::get_global(cx).gutter;
16061        let show_line_numbers = self
16062            .show_line_numbers
16063            .unwrap_or(gutter_settings.line_numbers);
16064        let line_gutter_width = if show_line_numbers {
16065            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16066            let min_width_for_number_on_gutter = em_advance * 4.0;
16067            max_line_number_width.max(min_width_for_number_on_gutter)
16068        } else {
16069            0.0.into()
16070        };
16071
16072        let show_code_actions = self
16073            .show_code_actions
16074            .unwrap_or(gutter_settings.code_actions);
16075
16076        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16077
16078        let git_blame_entries_width =
16079            self.git_blame_gutter_max_author_length
16080                .map(|max_author_length| {
16081                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16082
16083                    /// The number of characters to dedicate to gaps and margins.
16084                    const SPACING_WIDTH: usize = 4;
16085
16086                    let max_char_count = max_author_length
16087                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16088                        + ::git::SHORT_SHA_LENGTH
16089                        + MAX_RELATIVE_TIMESTAMP.len()
16090                        + SPACING_WIDTH;
16091
16092                    em_advance * max_char_count
16093                });
16094
16095        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16096        left_padding += if show_code_actions || show_runnables {
16097            em_width * 3.0
16098        } else if show_git_gutter && show_line_numbers {
16099            em_width * 2.0
16100        } else if show_git_gutter || show_line_numbers {
16101            em_width
16102        } else {
16103            px(0.)
16104        };
16105
16106        let right_padding = if gutter_settings.folds && show_line_numbers {
16107            em_width * 4.0
16108        } else if gutter_settings.folds {
16109            em_width * 3.0
16110        } else if show_line_numbers {
16111            em_width
16112        } else {
16113            px(0.)
16114        };
16115
16116        Some(GutterDimensions {
16117            left_padding,
16118            right_padding,
16119            width: line_gutter_width + left_padding + right_padding,
16120            margin: -descent,
16121            git_blame_entries_width,
16122        })
16123    }
16124
16125    pub fn render_crease_toggle(
16126        &self,
16127        buffer_row: MultiBufferRow,
16128        row_contains_cursor: bool,
16129        editor: Entity<Editor>,
16130        window: &mut Window,
16131        cx: &mut App,
16132    ) -> Option<AnyElement> {
16133        let folded = self.is_line_folded(buffer_row);
16134        let mut is_foldable = false;
16135
16136        if let Some(crease) = self
16137            .crease_snapshot
16138            .query_row(buffer_row, &self.buffer_snapshot)
16139        {
16140            is_foldable = true;
16141            match crease {
16142                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16143                    if let Some(render_toggle) = render_toggle {
16144                        let toggle_callback =
16145                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16146                                if folded {
16147                                    editor.update(cx, |editor, cx| {
16148                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16149                                    });
16150                                } else {
16151                                    editor.update(cx, |editor, cx| {
16152                                        editor.unfold_at(
16153                                            &crate::UnfoldAt { buffer_row },
16154                                            window,
16155                                            cx,
16156                                        )
16157                                    });
16158                                }
16159                            });
16160                        return Some((render_toggle)(
16161                            buffer_row,
16162                            folded,
16163                            toggle_callback,
16164                            window,
16165                            cx,
16166                        ));
16167                    }
16168                }
16169            }
16170        }
16171
16172        is_foldable |= self.starts_indent(buffer_row);
16173
16174        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16175            Some(
16176                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16177                    .toggle_state(folded)
16178                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16179                        if folded {
16180                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16181                        } else {
16182                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16183                        }
16184                    }))
16185                    .into_any_element(),
16186            )
16187        } else {
16188            None
16189        }
16190    }
16191
16192    pub fn render_crease_trailer(
16193        &self,
16194        buffer_row: MultiBufferRow,
16195        window: &mut Window,
16196        cx: &mut App,
16197    ) -> Option<AnyElement> {
16198        let folded = self.is_line_folded(buffer_row);
16199        if let Crease::Inline { render_trailer, .. } = self
16200            .crease_snapshot
16201            .query_row(buffer_row, &self.buffer_snapshot)?
16202        {
16203            let render_trailer = render_trailer.as_ref()?;
16204            Some(render_trailer(buffer_row, folded, window, cx))
16205        } else {
16206            None
16207        }
16208    }
16209}
16210
16211impl Deref for EditorSnapshot {
16212    type Target = DisplaySnapshot;
16213
16214    fn deref(&self) -> &Self::Target {
16215        &self.display_snapshot
16216    }
16217}
16218
16219#[derive(Clone, Debug, PartialEq, Eq)]
16220pub enum EditorEvent {
16221    InputIgnored {
16222        text: Arc<str>,
16223    },
16224    InputHandled {
16225        utf16_range_to_replace: Option<Range<isize>>,
16226        text: Arc<str>,
16227    },
16228    ExcerptsAdded {
16229        buffer: Entity<Buffer>,
16230        predecessor: ExcerptId,
16231        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16232    },
16233    ExcerptsRemoved {
16234        ids: Vec<ExcerptId>,
16235    },
16236    BufferFoldToggled {
16237        ids: Vec<ExcerptId>,
16238        folded: bool,
16239    },
16240    ExcerptsEdited {
16241        ids: Vec<ExcerptId>,
16242    },
16243    ExcerptsExpanded {
16244        ids: Vec<ExcerptId>,
16245    },
16246    BufferEdited,
16247    Edited {
16248        transaction_id: clock::Lamport,
16249    },
16250    Reparsed(BufferId),
16251    Focused,
16252    FocusedIn,
16253    Blurred,
16254    DirtyChanged,
16255    Saved,
16256    TitleChanged,
16257    DiffBaseChanged,
16258    SelectionsChanged {
16259        local: bool,
16260    },
16261    ScrollPositionChanged {
16262        local: bool,
16263        autoscroll: bool,
16264    },
16265    Closed,
16266    TransactionUndone {
16267        transaction_id: clock::Lamport,
16268    },
16269    TransactionBegun {
16270        transaction_id: clock::Lamport,
16271    },
16272    Reloaded,
16273    CursorShapeChanged,
16274}
16275
16276impl EventEmitter<EditorEvent> for Editor {}
16277
16278impl Focusable for Editor {
16279    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16280        self.focus_handle.clone()
16281    }
16282}
16283
16284impl Render for Editor {
16285    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16286        let settings = ThemeSettings::get_global(cx);
16287
16288        let mut text_style = match self.mode {
16289            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16290                color: cx.theme().colors().editor_foreground,
16291                font_family: settings.ui_font.family.clone(),
16292                font_features: settings.ui_font.features.clone(),
16293                font_fallbacks: settings.ui_font.fallbacks.clone(),
16294                font_size: rems(0.875).into(),
16295                font_weight: settings.ui_font.weight,
16296                line_height: relative(settings.buffer_line_height.value()),
16297                ..Default::default()
16298            },
16299            EditorMode::Full => TextStyle {
16300                color: cx.theme().colors().editor_foreground,
16301                font_family: settings.buffer_font.family.clone(),
16302                font_features: settings.buffer_font.features.clone(),
16303                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16304                font_size: settings.buffer_font_size(cx).into(),
16305                font_weight: settings.buffer_font.weight,
16306                line_height: relative(settings.buffer_line_height.value()),
16307                ..Default::default()
16308            },
16309        };
16310        if let Some(text_style_refinement) = &self.text_style_refinement {
16311            text_style.refine(text_style_refinement)
16312        }
16313
16314        let background = match self.mode {
16315            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16316            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16317            EditorMode::Full => cx.theme().colors().editor_background,
16318        };
16319
16320        EditorElement::new(
16321            &cx.entity(),
16322            EditorStyle {
16323                background,
16324                local_player: cx.theme().players().local(),
16325                text: text_style,
16326                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16327                syntax: cx.theme().syntax().clone(),
16328                status: cx.theme().status().clone(),
16329                inlay_hints_style: make_inlay_hints_style(cx),
16330                inline_completion_styles: make_suggestion_styles(cx),
16331                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16332            },
16333        )
16334    }
16335}
16336
16337impl EntityInputHandler for Editor {
16338    fn text_for_range(
16339        &mut self,
16340        range_utf16: Range<usize>,
16341        adjusted_range: &mut Option<Range<usize>>,
16342        _: &mut Window,
16343        cx: &mut Context<Self>,
16344    ) -> Option<String> {
16345        let snapshot = self.buffer.read(cx).read(cx);
16346        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16347        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16348        if (start.0..end.0) != range_utf16 {
16349            adjusted_range.replace(start.0..end.0);
16350        }
16351        Some(snapshot.text_for_range(start..end).collect())
16352    }
16353
16354    fn selected_text_range(
16355        &mut self,
16356        ignore_disabled_input: bool,
16357        _: &mut Window,
16358        cx: &mut Context<Self>,
16359    ) -> Option<UTF16Selection> {
16360        // Prevent the IME menu from appearing when holding down an alphabetic key
16361        // while input is disabled.
16362        if !ignore_disabled_input && !self.input_enabled {
16363            return None;
16364        }
16365
16366        let selection = self.selections.newest::<OffsetUtf16>(cx);
16367        let range = selection.range();
16368
16369        Some(UTF16Selection {
16370            range: range.start.0..range.end.0,
16371            reversed: selection.reversed,
16372        })
16373    }
16374
16375    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16376        let snapshot = self.buffer.read(cx).read(cx);
16377        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16378        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16379    }
16380
16381    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16382        self.clear_highlights::<InputComposition>(cx);
16383        self.ime_transaction.take();
16384    }
16385
16386    fn replace_text_in_range(
16387        &mut self,
16388        range_utf16: Option<Range<usize>>,
16389        text: &str,
16390        window: &mut Window,
16391        cx: &mut Context<Self>,
16392    ) {
16393        if !self.input_enabled {
16394            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16395            return;
16396        }
16397
16398        self.transact(window, cx, |this, window, cx| {
16399            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16400                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16401                Some(this.selection_replacement_ranges(range_utf16, cx))
16402            } else {
16403                this.marked_text_ranges(cx)
16404            };
16405
16406            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16407                let newest_selection_id = this.selections.newest_anchor().id;
16408                this.selections
16409                    .all::<OffsetUtf16>(cx)
16410                    .iter()
16411                    .zip(ranges_to_replace.iter())
16412                    .find_map(|(selection, range)| {
16413                        if selection.id == newest_selection_id {
16414                            Some(
16415                                (range.start.0 as isize - selection.head().0 as isize)
16416                                    ..(range.end.0 as isize - selection.head().0 as isize),
16417                            )
16418                        } else {
16419                            None
16420                        }
16421                    })
16422            });
16423
16424            cx.emit(EditorEvent::InputHandled {
16425                utf16_range_to_replace: range_to_replace,
16426                text: text.into(),
16427            });
16428
16429            if let Some(new_selected_ranges) = new_selected_ranges {
16430                this.change_selections(None, window, cx, |selections| {
16431                    selections.select_ranges(new_selected_ranges)
16432                });
16433                this.backspace(&Default::default(), window, cx);
16434            }
16435
16436            this.handle_input(text, window, cx);
16437        });
16438
16439        if let Some(transaction) = self.ime_transaction {
16440            self.buffer.update(cx, |buffer, cx| {
16441                buffer.group_until_transaction(transaction, cx);
16442            });
16443        }
16444
16445        self.unmark_text(window, cx);
16446    }
16447
16448    fn replace_and_mark_text_in_range(
16449        &mut self,
16450        range_utf16: Option<Range<usize>>,
16451        text: &str,
16452        new_selected_range_utf16: Option<Range<usize>>,
16453        window: &mut Window,
16454        cx: &mut Context<Self>,
16455    ) {
16456        if !self.input_enabled {
16457            return;
16458        }
16459
16460        let transaction = self.transact(window, cx, |this, window, cx| {
16461            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16462                let snapshot = this.buffer.read(cx).read(cx);
16463                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16464                    for marked_range in &mut marked_ranges {
16465                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16466                        marked_range.start.0 += relative_range_utf16.start;
16467                        marked_range.start =
16468                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16469                        marked_range.end =
16470                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16471                    }
16472                }
16473                Some(marked_ranges)
16474            } else if let Some(range_utf16) = range_utf16 {
16475                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16476                Some(this.selection_replacement_ranges(range_utf16, cx))
16477            } else {
16478                None
16479            };
16480
16481            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16482                let newest_selection_id = this.selections.newest_anchor().id;
16483                this.selections
16484                    .all::<OffsetUtf16>(cx)
16485                    .iter()
16486                    .zip(ranges_to_replace.iter())
16487                    .find_map(|(selection, range)| {
16488                        if selection.id == newest_selection_id {
16489                            Some(
16490                                (range.start.0 as isize - selection.head().0 as isize)
16491                                    ..(range.end.0 as isize - selection.head().0 as isize),
16492                            )
16493                        } else {
16494                            None
16495                        }
16496                    })
16497            });
16498
16499            cx.emit(EditorEvent::InputHandled {
16500                utf16_range_to_replace: range_to_replace,
16501                text: text.into(),
16502            });
16503
16504            if let Some(ranges) = ranges_to_replace {
16505                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16506            }
16507
16508            let marked_ranges = {
16509                let snapshot = this.buffer.read(cx).read(cx);
16510                this.selections
16511                    .disjoint_anchors()
16512                    .iter()
16513                    .map(|selection| {
16514                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16515                    })
16516                    .collect::<Vec<_>>()
16517            };
16518
16519            if text.is_empty() {
16520                this.unmark_text(window, cx);
16521            } else {
16522                this.highlight_text::<InputComposition>(
16523                    marked_ranges.clone(),
16524                    HighlightStyle {
16525                        underline: Some(UnderlineStyle {
16526                            thickness: px(1.),
16527                            color: None,
16528                            wavy: false,
16529                        }),
16530                        ..Default::default()
16531                    },
16532                    cx,
16533                );
16534            }
16535
16536            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16537            let use_autoclose = this.use_autoclose;
16538            let use_auto_surround = this.use_auto_surround;
16539            this.set_use_autoclose(false);
16540            this.set_use_auto_surround(false);
16541            this.handle_input(text, window, cx);
16542            this.set_use_autoclose(use_autoclose);
16543            this.set_use_auto_surround(use_auto_surround);
16544
16545            if let Some(new_selected_range) = new_selected_range_utf16 {
16546                let snapshot = this.buffer.read(cx).read(cx);
16547                let new_selected_ranges = marked_ranges
16548                    .into_iter()
16549                    .map(|marked_range| {
16550                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16551                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16552                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16553                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16554                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16555                    })
16556                    .collect::<Vec<_>>();
16557
16558                drop(snapshot);
16559                this.change_selections(None, window, cx, |selections| {
16560                    selections.select_ranges(new_selected_ranges)
16561                });
16562            }
16563        });
16564
16565        self.ime_transaction = self.ime_transaction.or(transaction);
16566        if let Some(transaction) = self.ime_transaction {
16567            self.buffer.update(cx, |buffer, cx| {
16568                buffer.group_until_transaction(transaction, cx);
16569            });
16570        }
16571
16572        if self.text_highlights::<InputComposition>(cx).is_none() {
16573            self.ime_transaction.take();
16574        }
16575    }
16576
16577    fn bounds_for_range(
16578        &mut self,
16579        range_utf16: Range<usize>,
16580        element_bounds: gpui::Bounds<Pixels>,
16581        window: &mut Window,
16582        cx: &mut Context<Self>,
16583    ) -> Option<gpui::Bounds<Pixels>> {
16584        let text_layout_details = self.text_layout_details(window);
16585        let gpui::Size {
16586            width: em_width,
16587            height: line_height,
16588        } = self.character_size(window);
16589
16590        let snapshot = self.snapshot(window, cx);
16591        let scroll_position = snapshot.scroll_position();
16592        let scroll_left = scroll_position.x * em_width;
16593
16594        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16595        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16596            + self.gutter_dimensions.width
16597            + self.gutter_dimensions.margin;
16598        let y = line_height * (start.row().as_f32() - scroll_position.y);
16599
16600        Some(Bounds {
16601            origin: element_bounds.origin + point(x, y),
16602            size: size(em_width, line_height),
16603        })
16604    }
16605
16606    fn character_index_for_point(
16607        &mut self,
16608        point: gpui::Point<Pixels>,
16609        _window: &mut Window,
16610        _cx: &mut Context<Self>,
16611    ) -> Option<usize> {
16612        let position_map = self.last_position_map.as_ref()?;
16613        if !position_map.text_hitbox.contains(&point) {
16614            return None;
16615        }
16616        let display_point = position_map.point_for_position(point).previous_valid;
16617        let anchor = position_map
16618            .snapshot
16619            .display_point_to_anchor(display_point, Bias::Left);
16620        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16621        Some(utf16_offset.0)
16622    }
16623}
16624
16625trait SelectionExt {
16626    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16627    fn spanned_rows(
16628        &self,
16629        include_end_if_at_line_start: bool,
16630        map: &DisplaySnapshot,
16631    ) -> Range<MultiBufferRow>;
16632}
16633
16634impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16635    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16636        let start = self
16637            .start
16638            .to_point(&map.buffer_snapshot)
16639            .to_display_point(map);
16640        let end = self
16641            .end
16642            .to_point(&map.buffer_snapshot)
16643            .to_display_point(map);
16644        if self.reversed {
16645            end..start
16646        } else {
16647            start..end
16648        }
16649    }
16650
16651    fn spanned_rows(
16652        &self,
16653        include_end_if_at_line_start: bool,
16654        map: &DisplaySnapshot,
16655    ) -> Range<MultiBufferRow> {
16656        let start = self.start.to_point(&map.buffer_snapshot);
16657        let mut end = self.end.to_point(&map.buffer_snapshot);
16658        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16659            end.row -= 1;
16660        }
16661
16662        let buffer_start = map.prev_line_boundary(start).0;
16663        let buffer_end = map.next_line_boundary(end).0;
16664        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16665    }
16666}
16667
16668impl<T: InvalidationRegion> InvalidationStack<T> {
16669    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16670    where
16671        S: Clone + ToOffset,
16672    {
16673        while let Some(region) = self.last() {
16674            let all_selections_inside_invalidation_ranges =
16675                if selections.len() == region.ranges().len() {
16676                    selections
16677                        .iter()
16678                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16679                        .all(|(selection, invalidation_range)| {
16680                            let head = selection.head().to_offset(buffer);
16681                            invalidation_range.start <= head && invalidation_range.end >= head
16682                        })
16683                } else {
16684                    false
16685                };
16686
16687            if all_selections_inside_invalidation_ranges {
16688                break;
16689            } else {
16690                self.pop();
16691            }
16692        }
16693    }
16694}
16695
16696impl<T> Default for InvalidationStack<T> {
16697    fn default() -> Self {
16698        Self(Default::default())
16699    }
16700}
16701
16702impl<T> Deref for InvalidationStack<T> {
16703    type Target = Vec<T>;
16704
16705    fn deref(&self) -> &Self::Target {
16706        &self.0
16707    }
16708}
16709
16710impl<T> DerefMut for InvalidationStack<T> {
16711    fn deref_mut(&mut self) -> &mut Self::Target {
16712        &mut self.0
16713    }
16714}
16715
16716impl InvalidationRegion for SnippetState {
16717    fn ranges(&self) -> &[Range<Anchor>] {
16718        &self.ranges[self.active_index]
16719    }
16720}
16721
16722pub fn diagnostic_block_renderer(
16723    diagnostic: Diagnostic,
16724    max_message_rows: Option<u8>,
16725    allow_closing: bool,
16726    _is_valid: bool,
16727) -> RenderBlock {
16728    let (text_without_backticks, code_ranges) =
16729        highlight_diagnostic_message(&diagnostic, max_message_rows);
16730
16731    Arc::new(move |cx: &mut BlockContext| {
16732        let group_id: SharedString = cx.block_id.to_string().into();
16733
16734        let mut text_style = cx.window.text_style().clone();
16735        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16736        let theme_settings = ThemeSettings::get_global(cx);
16737        text_style.font_family = theme_settings.buffer_font.family.clone();
16738        text_style.font_style = theme_settings.buffer_font.style;
16739        text_style.font_features = theme_settings.buffer_font.features.clone();
16740        text_style.font_weight = theme_settings.buffer_font.weight;
16741
16742        let multi_line_diagnostic = diagnostic.message.contains('\n');
16743
16744        let buttons = |diagnostic: &Diagnostic| {
16745            if multi_line_diagnostic {
16746                v_flex()
16747            } else {
16748                h_flex()
16749            }
16750            .when(allow_closing, |div| {
16751                div.children(diagnostic.is_primary.then(|| {
16752                    IconButton::new("close-block", IconName::XCircle)
16753                        .icon_color(Color::Muted)
16754                        .size(ButtonSize::Compact)
16755                        .style(ButtonStyle::Transparent)
16756                        .visible_on_hover(group_id.clone())
16757                        .on_click(move |_click, window, cx| {
16758                            window.dispatch_action(Box::new(Cancel), cx)
16759                        })
16760                        .tooltip(|window, cx| {
16761                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16762                        })
16763                }))
16764            })
16765            .child(
16766                IconButton::new("copy-block", IconName::Copy)
16767                    .icon_color(Color::Muted)
16768                    .size(ButtonSize::Compact)
16769                    .style(ButtonStyle::Transparent)
16770                    .visible_on_hover(group_id.clone())
16771                    .on_click({
16772                        let message = diagnostic.message.clone();
16773                        move |_click, _, cx| {
16774                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16775                        }
16776                    })
16777                    .tooltip(Tooltip::text("Copy diagnostic message")),
16778            )
16779        };
16780
16781        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16782            AvailableSpace::min_size(),
16783            cx.window,
16784            cx.app,
16785        );
16786
16787        h_flex()
16788            .id(cx.block_id)
16789            .group(group_id.clone())
16790            .relative()
16791            .size_full()
16792            .block_mouse_down()
16793            .pl(cx.gutter_dimensions.width)
16794            .w(cx.max_width - cx.gutter_dimensions.full_width())
16795            .child(
16796                div()
16797                    .flex()
16798                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16799                    .flex_shrink(),
16800            )
16801            .child(buttons(&diagnostic))
16802            .child(div().flex().flex_shrink_0().child(
16803                StyledText::new(text_without_backticks.clone()).with_highlights(
16804                    &text_style,
16805                    code_ranges.iter().map(|range| {
16806                        (
16807                            range.clone(),
16808                            HighlightStyle {
16809                                font_weight: Some(FontWeight::BOLD),
16810                                ..Default::default()
16811                            },
16812                        )
16813                    }),
16814                ),
16815            ))
16816            .into_any_element()
16817    })
16818}
16819
16820fn inline_completion_edit_text(
16821    current_snapshot: &BufferSnapshot,
16822    edits: &[(Range<Anchor>, String)],
16823    edit_preview: &EditPreview,
16824    include_deletions: bool,
16825    cx: &App,
16826) -> HighlightedText {
16827    let edits = edits
16828        .iter()
16829        .map(|(anchor, text)| {
16830            (
16831                anchor.start.text_anchor..anchor.end.text_anchor,
16832                text.clone(),
16833            )
16834        })
16835        .collect::<Vec<_>>();
16836
16837    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16838}
16839
16840pub fn highlight_diagnostic_message(
16841    diagnostic: &Diagnostic,
16842    mut max_message_rows: Option<u8>,
16843) -> (SharedString, Vec<Range<usize>>) {
16844    let mut text_without_backticks = String::new();
16845    let mut code_ranges = Vec::new();
16846
16847    if let Some(source) = &diagnostic.source {
16848        text_without_backticks.push_str(source);
16849        code_ranges.push(0..source.len());
16850        text_without_backticks.push_str(": ");
16851    }
16852
16853    let mut prev_offset = 0;
16854    let mut in_code_block = false;
16855    let has_row_limit = max_message_rows.is_some();
16856    let mut newline_indices = diagnostic
16857        .message
16858        .match_indices('\n')
16859        .filter(|_| has_row_limit)
16860        .map(|(ix, _)| ix)
16861        .fuse()
16862        .peekable();
16863
16864    for (quote_ix, _) in diagnostic
16865        .message
16866        .match_indices('`')
16867        .chain([(diagnostic.message.len(), "")])
16868    {
16869        let mut first_newline_ix = None;
16870        let mut last_newline_ix = None;
16871        while let Some(newline_ix) = newline_indices.peek() {
16872            if *newline_ix < quote_ix {
16873                if first_newline_ix.is_none() {
16874                    first_newline_ix = Some(*newline_ix);
16875                }
16876                last_newline_ix = Some(*newline_ix);
16877
16878                if let Some(rows_left) = &mut max_message_rows {
16879                    if *rows_left == 0 {
16880                        break;
16881                    } else {
16882                        *rows_left -= 1;
16883                    }
16884                }
16885                let _ = newline_indices.next();
16886            } else {
16887                break;
16888            }
16889        }
16890        let prev_len = text_without_backticks.len();
16891        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16892        text_without_backticks.push_str(new_text);
16893        if in_code_block {
16894            code_ranges.push(prev_len..text_without_backticks.len());
16895        }
16896        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16897        in_code_block = !in_code_block;
16898        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16899            text_without_backticks.push_str("...");
16900            break;
16901        }
16902    }
16903
16904    (text_without_backticks.into(), code_ranges)
16905}
16906
16907fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16908    match severity {
16909        DiagnosticSeverity::ERROR => colors.error,
16910        DiagnosticSeverity::WARNING => colors.warning,
16911        DiagnosticSeverity::INFORMATION => colors.info,
16912        DiagnosticSeverity::HINT => colors.info,
16913        _ => colors.ignored,
16914    }
16915}
16916
16917pub fn styled_runs_for_code_label<'a>(
16918    label: &'a CodeLabel,
16919    syntax_theme: &'a theme::SyntaxTheme,
16920) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16921    let fade_out = HighlightStyle {
16922        fade_out: Some(0.35),
16923        ..Default::default()
16924    };
16925
16926    let mut prev_end = label.filter_range.end;
16927    label
16928        .runs
16929        .iter()
16930        .enumerate()
16931        .flat_map(move |(ix, (range, highlight_id))| {
16932            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16933                style
16934            } else {
16935                return Default::default();
16936            };
16937            let mut muted_style = style;
16938            muted_style.highlight(fade_out);
16939
16940            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16941            if range.start >= label.filter_range.end {
16942                if range.start > prev_end {
16943                    runs.push((prev_end..range.start, fade_out));
16944                }
16945                runs.push((range.clone(), muted_style));
16946            } else if range.end <= label.filter_range.end {
16947                runs.push((range.clone(), style));
16948            } else {
16949                runs.push((range.start..label.filter_range.end, style));
16950                runs.push((label.filter_range.end..range.end, muted_style));
16951            }
16952            prev_end = cmp::max(prev_end, range.end);
16953
16954            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16955                runs.push((prev_end..label.text.len(), fade_out));
16956            }
16957
16958            runs
16959        })
16960}
16961
16962pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16963    let mut prev_index = 0;
16964    let mut prev_codepoint: Option<char> = None;
16965    text.char_indices()
16966        .chain([(text.len(), '\0')])
16967        .filter_map(move |(index, codepoint)| {
16968            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16969            let is_boundary = index == text.len()
16970                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16971                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16972            if is_boundary {
16973                let chunk = &text[prev_index..index];
16974                prev_index = index;
16975                Some(chunk)
16976            } else {
16977                None
16978            }
16979        })
16980}
16981
16982pub trait RangeToAnchorExt: Sized {
16983    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16984
16985    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16986        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16987        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16988    }
16989}
16990
16991impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16992    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16993        let start_offset = self.start.to_offset(snapshot);
16994        let end_offset = self.end.to_offset(snapshot);
16995        if start_offset == end_offset {
16996            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16997        } else {
16998            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16999        }
17000    }
17001}
17002
17003pub trait RowExt {
17004    fn as_f32(&self) -> f32;
17005
17006    fn next_row(&self) -> Self;
17007
17008    fn previous_row(&self) -> Self;
17009
17010    fn minus(&self, other: Self) -> u32;
17011}
17012
17013impl RowExt for DisplayRow {
17014    fn as_f32(&self) -> f32 {
17015        self.0 as f32
17016    }
17017
17018    fn next_row(&self) -> Self {
17019        Self(self.0 + 1)
17020    }
17021
17022    fn previous_row(&self) -> Self {
17023        Self(self.0.saturating_sub(1))
17024    }
17025
17026    fn minus(&self, other: Self) -> u32 {
17027        self.0 - other.0
17028    }
17029}
17030
17031impl RowExt for MultiBufferRow {
17032    fn as_f32(&self) -> f32 {
17033        self.0 as f32
17034    }
17035
17036    fn next_row(&self) -> Self {
17037        Self(self.0 + 1)
17038    }
17039
17040    fn previous_row(&self) -> Self {
17041        Self(self.0.saturating_sub(1))
17042    }
17043
17044    fn minus(&self, other: Self) -> u32 {
17045        self.0 - other.0
17046    }
17047}
17048
17049trait RowRangeExt {
17050    type Row;
17051
17052    fn len(&self) -> usize;
17053
17054    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17055}
17056
17057impl RowRangeExt for Range<MultiBufferRow> {
17058    type Row = MultiBufferRow;
17059
17060    fn len(&self) -> usize {
17061        (self.end.0 - self.start.0) as usize
17062    }
17063
17064    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17065        (self.start.0..self.end.0).map(MultiBufferRow)
17066    }
17067}
17068
17069impl RowRangeExt for Range<DisplayRow> {
17070    type Row = DisplayRow;
17071
17072    fn len(&self) -> usize {
17073        (self.end.0 - self.start.0) as usize
17074    }
17075
17076    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17077        (self.start.0..self.end.0).map(DisplayRow)
17078    }
17079}
17080
17081/// If select range has more than one line, we
17082/// just point the cursor to range.start.
17083fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17084    if range.start.row == range.end.row {
17085        range
17086    } else {
17087        range.start..range.start
17088    }
17089}
17090pub struct KillRing(ClipboardItem);
17091impl Global for KillRing {}
17092
17093const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17094
17095fn all_edits_insertions_or_deletions(
17096    edits: &Vec<(Range<Anchor>, String)>,
17097    snapshot: &MultiBufferSnapshot,
17098) -> bool {
17099    let mut all_insertions = true;
17100    let mut all_deletions = true;
17101
17102    for (range, new_text) in edits.iter() {
17103        let range_is_empty = range.to_offset(&snapshot).is_empty();
17104        let text_is_empty = new_text.is_empty();
17105
17106        if range_is_empty != text_is_empty {
17107            if range_is_empty {
17108                all_deletions = false;
17109            } else {
17110                all_insertions = false;
17111            }
17112        } else {
17113            return false;
17114        }
17115
17116        if !all_insertions && !all_deletions {
17117            return false;
17118        }
17119    }
17120    all_insertions || all_deletions
17121}