editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use code_context_menus::{
   77    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   78    CompletionsMenu, ContextMenuOrigin,
   79};
   80use git::blame::GitBlame;
   81use gpui::{
   82    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   83    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   84    ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
   85    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   86    HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
   87    PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
   88    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   89    WeakEntity, WeakFocusHandle, Window,
   90};
   91use highlight_matching_bracket::refresh_matching_bracket_highlights;
   92use hover_popover::{hide_hover, HoverState};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CompletionDocumentation, CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview,
  103    HighlightedText, IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection,
  104    SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  105};
  106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  107use linked_editing_ranges::refresh_linked_ranges;
  108use mouse_context_menu::MouseContextMenu;
  109use persistence::DB;
  110pub use proposed_changes_editor::{
  111    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  112};
  113use similar::{ChangeTag, TextDiff};
  114use std::iter::Peekable;
  115use task::{ResolvedTask, TaskTemplate, TaskVariables};
  116
  117use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  118pub use lsp::CompletionContext;
  119use lsp::{
  120    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  121    LanguageServerId, LanguageServerName,
  122};
  123
  124use language::BufferSnapshot;
  125use movement::TextLayoutDetails;
  126pub use multi_buffer::{
  127    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  128    ToOffset, ToPoint,
  129};
  130use multi_buffer::{
  131    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  132    ToOffsetUtf16,
  133};
  134use project::{
  135    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  136    project_settings::{GitGutterSetting, ProjectSettings},
  137    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  138    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  139};
  140use rand::prelude::*;
  141use rpc::{proto::*, ErrorExt};
  142use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  143use selections_collection::{
  144    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  145};
  146use serde::{Deserialize, Serialize};
  147use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  148use smallvec::SmallVec;
  149use snippet::Snippet;
  150use std::{
  151    any::TypeId,
  152    borrow::Cow,
  153    cell::RefCell,
  154    cmp::{self, Ordering, Reverse},
  155    mem,
  156    num::NonZeroU32,
  157    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  158    path::{Path, PathBuf},
  159    rc::Rc,
  160    sync::Arc,
  161    time::{Duration, Instant},
  162};
  163pub use sum_tree::Bias;
  164use sum_tree::TreeMap;
  165use text::{BufferId, OffsetUtf16, Rope};
  166use theme::{
  167    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  168    ThemeColors, ThemeSettings,
  169};
  170use ui::{
  171    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  172    Tooltip,
  173};
  174use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  175use workspace::{
  176    item::{ItemHandle, PreviewTabsSettings},
  177    ItemId, RestoreOnStartupBehavior,
  178};
  179use workspace::{
  180    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  181    WorkspaceSettings,
  182};
  183use workspace::{
  184    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  185};
  186use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  187
  188use crate::hover_links::{find_url, find_url_from_range};
  189use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  190
  191pub const FILE_HEADER_HEIGHT: u32 = 2;
  192pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  193pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  194pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  195const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  196const MAX_LINE_LEN: usize = 1024;
  197const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  198const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  199pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  200#[doc(hidden)]
  201pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  202
  203pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  204pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  205
  206pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  207pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  208
  209const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  210    alt: true,
  211    shift: true,
  212    control: false,
  213    platform: false,
  214    function: false,
  215};
  216
  217pub fn render_parsed_markdown(
  218    element_id: impl Into<ElementId>,
  219    parsed: &language::ParsedMarkdown,
  220    editor_style: &EditorStyle,
  221    workspace: Option<WeakEntity<Workspace>>,
  222    cx: &mut App,
  223) -> InteractiveText {
  224    let code_span_background_color = cx
  225        .theme()
  226        .colors()
  227        .editor_document_highlight_read_background;
  228
  229    let highlights = gpui::combine_highlights(
  230        parsed.highlights.iter().filter_map(|(range, highlight)| {
  231            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  232            Some((range.clone(), highlight))
  233        }),
  234        parsed
  235            .regions
  236            .iter()
  237            .zip(&parsed.region_ranges)
  238            .filter_map(|(region, range)| {
  239                if region.code {
  240                    Some((
  241                        range.clone(),
  242                        HighlightStyle {
  243                            background_color: Some(code_span_background_color),
  244                            ..Default::default()
  245                        },
  246                    ))
  247                } else {
  248                    None
  249                }
  250            }),
  251    );
  252
  253    let mut links = Vec::new();
  254    let mut link_ranges = Vec::new();
  255    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  256        if let Some(link) = region.link.clone() {
  257            links.push(link);
  258            link_ranges.push(range.clone());
  259        }
  260    }
  261
  262    InteractiveText::new(
  263        element_id,
  264        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  265    )
  266    .on_click(
  267        link_ranges,
  268        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  269            markdown::Link::Web { url } => cx.open_url(url),
  270            markdown::Link::Path { path } => {
  271                if let Some(workspace) = &workspace {
  272                    _ = workspace.update(cx, |workspace, cx| {
  273                        workspace
  274                            .open_abs_path(path.clone(), false, window, cx)
  275                            .detach();
  276                    });
  277                }
  278            }
  279        },
  280    )
  281}
  282
  283#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  284pub enum InlayId {
  285    InlineCompletion(usize),
  286    Hint(usize),
  287}
  288
  289impl InlayId {
  290    fn id(&self) -> usize {
  291        match self {
  292            Self::InlineCompletion(id) => *id,
  293            Self::Hint(id) => *id,
  294        }
  295    }
  296}
  297
  298enum DocumentHighlightRead {}
  299enum DocumentHighlightWrite {}
  300enum InputComposition {}
  301enum SelectedTextHighlight {}
  302
  303#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  304pub enum Navigated {
  305    Yes,
  306    No,
  307}
  308
  309impl Navigated {
  310    pub fn from_bool(yes: bool) -> Navigated {
  311        if yes {
  312            Navigated::Yes
  313        } else {
  314            Navigated::No
  315        }
  316    }
  317}
  318
  319pub fn init_settings(cx: &mut App) {
  320    EditorSettings::register(cx);
  321}
  322
  323pub fn init(cx: &mut App) {
  324    init_settings(cx);
  325
  326    workspace::register_project_item::<Editor>(cx);
  327    workspace::FollowableViewRegistry::register::<Editor>(cx);
  328    workspace::register_serializable_item::<Editor>(cx);
  329
  330    cx.observe_new(
  331        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  332            workspace.register_action(Editor::new_file);
  333            workspace.register_action(Editor::new_file_vertical);
  334            workspace.register_action(Editor::new_file_horizontal);
  335            workspace.register_action(Editor::cancel_language_server_work);
  336        },
  337    )
  338    .detach();
  339
  340    cx.on_action(move |_: &workspace::NewFile, cx| {
  341        let app_state = workspace::AppState::global(cx);
  342        if let Some(app_state) = app_state.upgrade() {
  343            workspace::open_new(
  344                Default::default(),
  345                app_state,
  346                cx,
  347                |workspace, window, cx| {
  348                    Editor::new_file(workspace, &Default::default(), window, cx)
  349                },
  350            )
  351            .detach();
  352        }
  353    });
  354    cx.on_action(move |_: &workspace::NewWindow, cx| {
  355        let app_state = workspace::AppState::global(cx);
  356        if let Some(app_state) = app_state.upgrade() {
  357            workspace::open_new(
  358                Default::default(),
  359                app_state,
  360                cx,
  361                |workspace, window, cx| {
  362                    cx.activate(true);
  363                    Editor::new_file(workspace, &Default::default(), window, cx)
  364                },
  365            )
  366            .detach();
  367        }
  368    });
  369}
  370
  371pub struct SearchWithinRange;
  372
  373trait InvalidationRegion {
  374    fn ranges(&self) -> &[Range<Anchor>];
  375}
  376
  377#[derive(Clone, Debug, PartialEq)]
  378pub enum SelectPhase {
  379    Begin {
  380        position: DisplayPoint,
  381        add: bool,
  382        click_count: usize,
  383    },
  384    BeginColumnar {
  385        position: DisplayPoint,
  386        reset: bool,
  387        goal_column: u32,
  388    },
  389    Extend {
  390        position: DisplayPoint,
  391        click_count: usize,
  392    },
  393    Update {
  394        position: DisplayPoint,
  395        goal_column: u32,
  396        scroll_delta: gpui::Point<f32>,
  397    },
  398    End,
  399}
  400
  401#[derive(Clone, Debug)]
  402pub enum SelectMode {
  403    Character,
  404    Word(Range<Anchor>),
  405    Line(Range<Anchor>),
  406    All,
  407}
  408
  409#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  410pub enum EditorMode {
  411    SingleLine { auto_width: bool },
  412    AutoHeight { max_lines: usize },
  413    Full,
  414}
  415
  416#[derive(Copy, Clone, Debug)]
  417pub enum SoftWrap {
  418    /// Prefer not to wrap at all.
  419    ///
  420    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  421    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  422    GitDiff,
  423    /// Prefer a single line generally, unless an overly long line is encountered.
  424    None,
  425    /// Soft wrap lines that exceed the editor width.
  426    EditorWidth,
  427    /// Soft wrap lines at the preferred line length.
  428    Column(u32),
  429    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  430    Bounded(u32),
  431}
  432
  433#[derive(Clone)]
  434pub struct EditorStyle {
  435    pub background: Hsla,
  436    pub local_player: PlayerColor,
  437    pub text: TextStyle,
  438    pub scrollbar_width: Pixels,
  439    pub syntax: Arc<SyntaxTheme>,
  440    pub status: StatusColors,
  441    pub inlay_hints_style: HighlightStyle,
  442    pub inline_completion_styles: InlineCompletionStyles,
  443    pub unnecessary_code_fade: f32,
  444}
  445
  446impl Default for EditorStyle {
  447    fn default() -> Self {
  448        Self {
  449            background: Hsla::default(),
  450            local_player: PlayerColor::default(),
  451            text: TextStyle::default(),
  452            scrollbar_width: Pixels::default(),
  453            syntax: Default::default(),
  454            // HACK: Status colors don't have a real default.
  455            // We should look into removing the status colors from the editor
  456            // style and retrieve them directly from the theme.
  457            status: StatusColors::dark(),
  458            inlay_hints_style: HighlightStyle::default(),
  459            inline_completion_styles: InlineCompletionStyles {
  460                insertion: HighlightStyle::default(),
  461                whitespace: HighlightStyle::default(),
  462            },
  463            unnecessary_code_fade: Default::default(),
  464        }
  465    }
  466}
  467
  468pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  469    let show_background = language_settings::language_settings(None, None, cx)
  470        .inlay_hints
  471        .show_background;
  472
  473    HighlightStyle {
  474        color: Some(cx.theme().status().hint),
  475        background_color: show_background.then(|| cx.theme().status().hint_background),
  476        ..HighlightStyle::default()
  477    }
  478}
  479
  480pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  481    InlineCompletionStyles {
  482        insertion: HighlightStyle {
  483            color: Some(cx.theme().status().predictive),
  484            ..HighlightStyle::default()
  485        },
  486        whitespace: HighlightStyle {
  487            background_color: Some(cx.theme().status().created_background),
  488            ..HighlightStyle::default()
  489        },
  490    }
  491}
  492
  493type CompletionId = usize;
  494
  495pub(crate) enum EditDisplayMode {
  496    TabAccept,
  497    DiffPopover,
  498    Inline,
  499}
  500
  501enum InlineCompletion {
  502    Edit {
  503        edits: Vec<(Range<Anchor>, String)>,
  504        edit_preview: Option<EditPreview>,
  505        display_mode: EditDisplayMode,
  506        snapshot: BufferSnapshot,
  507    },
  508    Move {
  509        target: Anchor,
  510        snapshot: BufferSnapshot,
  511    },
  512}
  513
  514struct InlineCompletionState {
  515    inlay_ids: Vec<InlayId>,
  516    completion: InlineCompletion,
  517    completion_id: Option<SharedString>,
  518    invalidation_range: Range<Anchor>,
  519}
  520
  521enum EditPredictionSettings {
  522    Disabled,
  523    Enabled {
  524        show_in_menu: bool,
  525        preview_requires_modifier: bool,
  526    },
  527}
  528
  529enum InlineCompletionHighlight {}
  530
  531pub enum MenuInlineCompletionsPolicy {
  532    Never,
  533    ByProvider,
  534}
  535
  536pub enum EditPredictionPreview {
  537    /// Modifier is not pressed
  538    Inactive,
  539    /// Modifier pressed
  540    Active {
  541        previous_scroll_position: Option<ScrollAnchor>,
  542    },
  543}
  544
  545#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  546struct EditorActionId(usize);
  547
  548impl EditorActionId {
  549    pub fn post_inc(&mut self) -> Self {
  550        let answer = self.0;
  551
  552        *self = Self(answer + 1);
  553
  554        Self(answer)
  555    }
  556}
  557
  558// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  559// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  560
  561type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  562type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  563
  564#[derive(Default)]
  565struct ScrollbarMarkerState {
  566    scrollbar_size: Size<Pixels>,
  567    dirty: bool,
  568    markers: Arc<[PaintQuad]>,
  569    pending_refresh: Option<Task<Result<()>>>,
  570}
  571
  572impl ScrollbarMarkerState {
  573    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  574        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  575    }
  576}
  577
  578#[derive(Clone, Debug)]
  579struct RunnableTasks {
  580    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  581    offset: MultiBufferOffset,
  582    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  583    column: u32,
  584    // Values of all named captures, including those starting with '_'
  585    extra_variables: HashMap<String, String>,
  586    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  587    context_range: Range<BufferOffset>,
  588}
  589
  590impl RunnableTasks {
  591    fn resolve<'a>(
  592        &'a self,
  593        cx: &'a task::TaskContext,
  594    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  595        self.templates.iter().filter_map(|(kind, template)| {
  596            template
  597                .resolve_task(&kind.to_id_base(), cx)
  598                .map(|task| (kind.clone(), task))
  599        })
  600    }
  601}
  602
  603#[derive(Clone)]
  604struct ResolvedTasks {
  605    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  606    position: Anchor,
  607}
  608#[derive(Copy, Clone, Debug)]
  609struct MultiBufferOffset(usize);
  610#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  611struct BufferOffset(usize);
  612
  613// Addons allow storing per-editor state in other crates (e.g. Vim)
  614pub trait Addon: 'static {
  615    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  616
  617    fn render_buffer_header_controls(
  618        &self,
  619        _: &ExcerptInfo,
  620        _: &Window,
  621        _: &App,
  622    ) -> Option<AnyElement> {
  623        None
  624    }
  625
  626    fn to_any(&self) -> &dyn std::any::Any;
  627}
  628
  629#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  630pub enum IsVimMode {
  631    Yes,
  632    No,
  633}
  634
  635/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  636///
  637/// See the [module level documentation](self) for more information.
  638pub struct Editor {
  639    focus_handle: FocusHandle,
  640    last_focused_descendant: Option<WeakFocusHandle>,
  641    /// The text buffer being edited
  642    buffer: Entity<MultiBuffer>,
  643    /// Map of how text in the buffer should be displayed.
  644    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  645    pub display_map: Entity<DisplayMap>,
  646    pub selections: SelectionsCollection,
  647    pub scroll_manager: ScrollManager,
  648    /// When inline assist editors are linked, they all render cursors because
  649    /// typing enters text into each of them, even the ones that aren't focused.
  650    pub(crate) show_cursor_when_unfocused: bool,
  651    columnar_selection_tail: Option<Anchor>,
  652    add_selections_state: Option<AddSelectionsState>,
  653    select_next_state: Option<SelectNextState>,
  654    select_prev_state: Option<SelectNextState>,
  655    selection_history: SelectionHistory,
  656    autoclose_regions: Vec<AutocloseRegion>,
  657    snippet_stack: InvalidationStack<SnippetState>,
  658    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  659    ime_transaction: Option<TransactionId>,
  660    active_diagnostics: Option<ActiveDiagnosticGroup>,
  661    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  662
  663    // TODO: make this a access method
  664    pub project: Option<Entity<Project>>,
  665    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  666    completion_provider: Option<Box<dyn CompletionProvider>>,
  667    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  668    blink_manager: Entity<BlinkManager>,
  669    show_cursor_names: bool,
  670    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  671    pub show_local_selections: bool,
  672    mode: EditorMode,
  673    show_breadcrumbs: bool,
  674    show_gutter: bool,
  675    show_scrollbars: bool,
  676    show_line_numbers: Option<bool>,
  677    use_relative_line_numbers: Option<bool>,
  678    show_git_diff_gutter: Option<bool>,
  679    show_code_actions: Option<bool>,
  680    show_runnables: Option<bool>,
  681    show_wrap_guides: Option<bool>,
  682    show_indent_guides: Option<bool>,
  683    placeholder_text: Option<Arc<str>>,
  684    highlight_order: usize,
  685    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  686    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  687    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  688    scrollbar_marker_state: ScrollbarMarkerState,
  689    active_indent_guides_state: ActiveIndentGuidesState,
  690    nav_history: Option<ItemNavHistory>,
  691    context_menu: RefCell<Option<CodeContextMenu>>,
  692    mouse_context_menu: Option<MouseContextMenu>,
  693    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  694    signature_help_state: SignatureHelpState,
  695    auto_signature_help: Option<bool>,
  696    find_all_references_task_sources: Vec<Anchor>,
  697    next_completion_id: CompletionId,
  698    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  699    code_actions_task: Option<Task<Result<()>>>,
  700    selection_highlight_task: Option<Task<()>>,
  701    document_highlights_task: Option<Task<()>>,
  702    linked_editing_range_task: Option<Task<Option<()>>>,
  703    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  704    pending_rename: Option<RenameState>,
  705    searchable: bool,
  706    cursor_shape: CursorShape,
  707    current_line_highlight: Option<CurrentLineHighlight>,
  708    collapse_matches: bool,
  709    autoindent_mode: Option<AutoindentMode>,
  710    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  711    input_enabled: bool,
  712    use_modal_editing: bool,
  713    read_only: bool,
  714    leader_peer_id: Option<PeerId>,
  715    remote_id: Option<ViewId>,
  716    hover_state: HoverState,
  717    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  718    gutter_hovered: bool,
  719    hovered_link_state: Option<HoveredLinkState>,
  720    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  721    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  722    active_inline_completion: Option<InlineCompletionState>,
  723    /// Used to prevent flickering as the user types while the menu is open
  724    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  725    edit_prediction_settings: EditPredictionSettings,
  726    inline_completions_hidden_for_vim_mode: bool,
  727    show_inline_completions_override: Option<bool>,
  728    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  729    edit_prediction_preview: EditPredictionPreview,
  730    edit_prediction_cursor_on_leading_whitespace: bool,
  731    edit_prediction_requires_modifier_in_leading_space: bool,
  732    inlay_hint_cache: InlayHintCache,
  733    next_inlay_id: usize,
  734    _subscriptions: Vec<Subscription>,
  735    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  736    gutter_dimensions: GutterDimensions,
  737    style: Option<EditorStyle>,
  738    text_style_refinement: Option<TextStyleRefinement>,
  739    next_editor_action_id: EditorActionId,
  740    editor_actions:
  741        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  742    use_autoclose: bool,
  743    use_auto_surround: bool,
  744    auto_replace_emoji_shortcode: bool,
  745    show_git_blame_gutter: bool,
  746    show_git_blame_inline: bool,
  747    show_git_blame_inline_delay_task: Option<Task<()>>,
  748    distinguish_unstaged_diff_hunks: bool,
  749    git_blame_inline_enabled: bool,
  750    serialize_dirty_buffers: bool,
  751    show_selection_menu: Option<bool>,
  752    blame: Option<Entity<GitBlame>>,
  753    blame_subscription: Option<Subscription>,
  754    custom_context_menu: Option<
  755        Box<
  756            dyn 'static
  757                + Fn(
  758                    &mut Self,
  759                    DisplayPoint,
  760                    &mut Window,
  761                    &mut Context<Self>,
  762                ) -> Option<Entity<ui::ContextMenu>>,
  763        >,
  764    >,
  765    last_bounds: Option<Bounds<Pixels>>,
  766    last_position_map: Option<Rc<PositionMap>>,
  767    expect_bounds_change: Option<Bounds<Pixels>>,
  768    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  769    tasks_update_task: Option<Task<()>>,
  770    in_project_search: bool,
  771    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  772    breadcrumb_header: Option<String>,
  773    focused_block: Option<FocusedBlock>,
  774    next_scroll_position: NextScrollCursorCenterTopBottom,
  775    addons: HashMap<TypeId, Box<dyn Addon>>,
  776    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  777    load_diff_task: Option<Shared<Task<()>>>,
  778    selection_mark_mode: bool,
  779    toggle_fold_multiple_buffers: Task<()>,
  780    _scroll_cursor_center_top_bottom_task: Task<()>,
  781    serialize_selections: Task<()>,
  782}
  783
  784#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  785enum NextScrollCursorCenterTopBottom {
  786    #[default]
  787    Center,
  788    Top,
  789    Bottom,
  790}
  791
  792impl NextScrollCursorCenterTopBottom {
  793    fn next(&self) -> Self {
  794        match self {
  795            Self::Center => Self::Top,
  796            Self::Top => Self::Bottom,
  797            Self::Bottom => Self::Center,
  798        }
  799    }
  800}
  801
  802#[derive(Clone)]
  803pub struct EditorSnapshot {
  804    pub mode: EditorMode,
  805    show_gutter: bool,
  806    show_line_numbers: Option<bool>,
  807    show_git_diff_gutter: Option<bool>,
  808    show_code_actions: Option<bool>,
  809    show_runnables: Option<bool>,
  810    git_blame_gutter_max_author_length: Option<usize>,
  811    pub display_snapshot: DisplaySnapshot,
  812    pub placeholder_text: Option<Arc<str>>,
  813    is_focused: bool,
  814    scroll_anchor: ScrollAnchor,
  815    ongoing_scroll: OngoingScroll,
  816    current_line_highlight: CurrentLineHighlight,
  817    gutter_hovered: bool,
  818}
  819
  820const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  821
  822#[derive(Default, Debug, Clone, Copy)]
  823pub struct GutterDimensions {
  824    pub left_padding: Pixels,
  825    pub right_padding: Pixels,
  826    pub width: Pixels,
  827    pub margin: Pixels,
  828    pub git_blame_entries_width: Option<Pixels>,
  829}
  830
  831impl GutterDimensions {
  832    /// The full width of the space taken up by the gutter.
  833    pub fn full_width(&self) -> Pixels {
  834        self.margin + self.width
  835    }
  836
  837    /// The width of the space reserved for the fold indicators,
  838    /// use alongside 'justify_end' and `gutter_width` to
  839    /// right align content with the line numbers
  840    pub fn fold_area_width(&self) -> Pixels {
  841        self.margin + self.right_padding
  842    }
  843}
  844
  845#[derive(Debug)]
  846pub struct RemoteSelection {
  847    pub replica_id: ReplicaId,
  848    pub selection: Selection<Anchor>,
  849    pub cursor_shape: CursorShape,
  850    pub peer_id: PeerId,
  851    pub line_mode: bool,
  852    pub participant_index: Option<ParticipantIndex>,
  853    pub user_name: Option<SharedString>,
  854}
  855
  856#[derive(Clone, Debug)]
  857struct SelectionHistoryEntry {
  858    selections: Arc<[Selection<Anchor>]>,
  859    select_next_state: Option<SelectNextState>,
  860    select_prev_state: Option<SelectNextState>,
  861    add_selections_state: Option<AddSelectionsState>,
  862}
  863
  864enum SelectionHistoryMode {
  865    Normal,
  866    Undoing,
  867    Redoing,
  868}
  869
  870#[derive(Clone, PartialEq, Eq, Hash)]
  871struct HoveredCursor {
  872    replica_id: u16,
  873    selection_id: usize,
  874}
  875
  876impl Default for SelectionHistoryMode {
  877    fn default() -> Self {
  878        Self::Normal
  879    }
  880}
  881
  882#[derive(Default)]
  883struct SelectionHistory {
  884    #[allow(clippy::type_complexity)]
  885    selections_by_transaction:
  886        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  887    mode: SelectionHistoryMode,
  888    undo_stack: VecDeque<SelectionHistoryEntry>,
  889    redo_stack: VecDeque<SelectionHistoryEntry>,
  890}
  891
  892impl SelectionHistory {
  893    fn insert_transaction(
  894        &mut self,
  895        transaction_id: TransactionId,
  896        selections: Arc<[Selection<Anchor>]>,
  897    ) {
  898        self.selections_by_transaction
  899            .insert(transaction_id, (selections, None));
  900    }
  901
  902    #[allow(clippy::type_complexity)]
  903    fn transaction(
  904        &self,
  905        transaction_id: TransactionId,
  906    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  907        self.selections_by_transaction.get(&transaction_id)
  908    }
  909
  910    #[allow(clippy::type_complexity)]
  911    fn transaction_mut(
  912        &mut self,
  913        transaction_id: TransactionId,
  914    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  915        self.selections_by_transaction.get_mut(&transaction_id)
  916    }
  917
  918    fn push(&mut self, entry: SelectionHistoryEntry) {
  919        if !entry.selections.is_empty() {
  920            match self.mode {
  921                SelectionHistoryMode::Normal => {
  922                    self.push_undo(entry);
  923                    self.redo_stack.clear();
  924                }
  925                SelectionHistoryMode::Undoing => self.push_redo(entry),
  926                SelectionHistoryMode::Redoing => self.push_undo(entry),
  927            }
  928        }
  929    }
  930
  931    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  932        if self
  933            .undo_stack
  934            .back()
  935            .map_or(true, |e| e.selections != entry.selections)
  936        {
  937            self.undo_stack.push_back(entry);
  938            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  939                self.undo_stack.pop_front();
  940            }
  941        }
  942    }
  943
  944    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  945        if self
  946            .redo_stack
  947            .back()
  948            .map_or(true, |e| e.selections != entry.selections)
  949        {
  950            self.redo_stack.push_back(entry);
  951            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  952                self.redo_stack.pop_front();
  953            }
  954        }
  955    }
  956}
  957
  958struct RowHighlight {
  959    index: usize,
  960    range: Range<Anchor>,
  961    color: Hsla,
  962    should_autoscroll: bool,
  963}
  964
  965#[derive(Clone, Debug)]
  966struct AddSelectionsState {
  967    above: bool,
  968    stack: Vec<usize>,
  969}
  970
  971#[derive(Clone)]
  972struct SelectNextState {
  973    query: AhoCorasick,
  974    wordwise: bool,
  975    done: bool,
  976}
  977
  978impl std::fmt::Debug for SelectNextState {
  979    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  980        f.debug_struct(std::any::type_name::<Self>())
  981            .field("wordwise", &self.wordwise)
  982            .field("done", &self.done)
  983            .finish()
  984    }
  985}
  986
  987#[derive(Debug)]
  988struct AutocloseRegion {
  989    selection_id: usize,
  990    range: Range<Anchor>,
  991    pair: BracketPair,
  992}
  993
  994#[derive(Debug)]
  995struct SnippetState {
  996    ranges: Vec<Vec<Range<Anchor>>>,
  997    active_index: usize,
  998    choices: Vec<Option<Vec<String>>>,
  999}
 1000
 1001#[doc(hidden)]
 1002pub struct RenameState {
 1003    pub range: Range<Anchor>,
 1004    pub old_name: Arc<str>,
 1005    pub editor: Entity<Editor>,
 1006    block_id: CustomBlockId,
 1007}
 1008
 1009struct InvalidationStack<T>(Vec<T>);
 1010
 1011struct RegisteredInlineCompletionProvider {
 1012    provider: Arc<dyn InlineCompletionProviderHandle>,
 1013    _subscription: Subscription,
 1014}
 1015
 1016#[derive(Debug)]
 1017struct ActiveDiagnosticGroup {
 1018    primary_range: Range<Anchor>,
 1019    primary_message: String,
 1020    group_id: usize,
 1021    blocks: HashMap<CustomBlockId, Diagnostic>,
 1022    is_valid: bool,
 1023}
 1024
 1025#[derive(Serialize, Deserialize, Clone, Debug)]
 1026pub struct ClipboardSelection {
 1027    pub len: usize,
 1028    pub is_entire_line: bool,
 1029    pub first_line_indent: u32,
 1030}
 1031
 1032#[derive(Debug)]
 1033pub(crate) struct NavigationData {
 1034    cursor_anchor: Anchor,
 1035    cursor_position: Point,
 1036    scroll_anchor: ScrollAnchor,
 1037    scroll_top_row: u32,
 1038}
 1039
 1040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1041pub enum GotoDefinitionKind {
 1042    Symbol,
 1043    Declaration,
 1044    Type,
 1045    Implementation,
 1046}
 1047
 1048#[derive(Debug, Clone)]
 1049enum InlayHintRefreshReason {
 1050    Toggle(bool),
 1051    SettingsChange(InlayHintSettings),
 1052    NewLinesShown,
 1053    BufferEdited(HashSet<Arc<Language>>),
 1054    RefreshRequested,
 1055    ExcerptsRemoved(Vec<ExcerptId>),
 1056}
 1057
 1058impl InlayHintRefreshReason {
 1059    fn description(&self) -> &'static str {
 1060        match self {
 1061            Self::Toggle(_) => "toggle",
 1062            Self::SettingsChange(_) => "settings change",
 1063            Self::NewLinesShown => "new lines shown",
 1064            Self::BufferEdited(_) => "buffer edited",
 1065            Self::RefreshRequested => "refresh requested",
 1066            Self::ExcerptsRemoved(_) => "excerpts removed",
 1067        }
 1068    }
 1069}
 1070
 1071pub enum FormatTarget {
 1072    Buffers,
 1073    Ranges(Vec<Range<MultiBufferPoint>>),
 1074}
 1075
 1076pub(crate) struct FocusedBlock {
 1077    id: BlockId,
 1078    focus_handle: WeakFocusHandle,
 1079}
 1080
 1081#[derive(Clone)]
 1082enum JumpData {
 1083    MultiBufferRow {
 1084        row: MultiBufferRow,
 1085        line_offset_from_top: u32,
 1086    },
 1087    MultiBufferPoint {
 1088        excerpt_id: ExcerptId,
 1089        position: Point,
 1090        anchor: text::Anchor,
 1091        line_offset_from_top: u32,
 1092    },
 1093}
 1094
 1095pub enum MultibufferSelectionMode {
 1096    First,
 1097    All,
 1098}
 1099
 1100impl Editor {
 1101    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1102        let buffer = cx.new(|cx| Buffer::local("", cx));
 1103        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1104        Self::new(
 1105            EditorMode::SingleLine { auto_width: false },
 1106            buffer,
 1107            None,
 1108            false,
 1109            window,
 1110            cx,
 1111        )
 1112    }
 1113
 1114    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1115        let buffer = cx.new(|cx| Buffer::local("", cx));
 1116        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1117        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1118    }
 1119
 1120    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1121        let buffer = cx.new(|cx| Buffer::local("", cx));
 1122        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1123        Self::new(
 1124            EditorMode::SingleLine { auto_width: true },
 1125            buffer,
 1126            None,
 1127            false,
 1128            window,
 1129            cx,
 1130        )
 1131    }
 1132
 1133    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1134        let buffer = cx.new(|cx| Buffer::local("", cx));
 1135        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1136        Self::new(
 1137            EditorMode::AutoHeight { max_lines },
 1138            buffer,
 1139            None,
 1140            false,
 1141            window,
 1142            cx,
 1143        )
 1144    }
 1145
 1146    pub fn for_buffer(
 1147        buffer: Entity<Buffer>,
 1148        project: Option<Entity<Project>>,
 1149        window: &mut Window,
 1150        cx: &mut Context<Self>,
 1151    ) -> Self {
 1152        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1153        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1154    }
 1155
 1156    pub fn for_multibuffer(
 1157        buffer: Entity<MultiBuffer>,
 1158        project: Option<Entity<Project>>,
 1159        show_excerpt_controls: bool,
 1160        window: &mut Window,
 1161        cx: &mut Context<Self>,
 1162    ) -> Self {
 1163        Self::new(
 1164            EditorMode::Full,
 1165            buffer,
 1166            project,
 1167            show_excerpt_controls,
 1168            window,
 1169            cx,
 1170        )
 1171    }
 1172
 1173    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1174        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1175        let mut clone = Self::new(
 1176            self.mode,
 1177            self.buffer.clone(),
 1178            self.project.clone(),
 1179            show_excerpt_controls,
 1180            window,
 1181            cx,
 1182        );
 1183        self.display_map.update(cx, |display_map, cx| {
 1184            let snapshot = display_map.snapshot(cx);
 1185            clone.display_map.update(cx, |display_map, cx| {
 1186                display_map.set_state(&snapshot, cx);
 1187            });
 1188        });
 1189        clone.selections.clone_state(&self.selections);
 1190        clone.scroll_manager.clone_state(&self.scroll_manager);
 1191        clone.searchable = self.searchable;
 1192        clone
 1193    }
 1194
 1195    pub fn new(
 1196        mode: EditorMode,
 1197        buffer: Entity<MultiBuffer>,
 1198        project: Option<Entity<Project>>,
 1199        show_excerpt_controls: bool,
 1200        window: &mut Window,
 1201        cx: &mut Context<Self>,
 1202    ) -> Self {
 1203        let style = window.text_style();
 1204        let font_size = style.font_size.to_pixels(window.rem_size());
 1205        let editor = cx.entity().downgrade();
 1206        let fold_placeholder = FoldPlaceholder {
 1207            constrain_width: true,
 1208            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1209                let editor = editor.clone();
 1210                div()
 1211                    .id(fold_id)
 1212                    .bg(cx.theme().colors().ghost_element_background)
 1213                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1214                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1215                    .rounded_sm()
 1216                    .size_full()
 1217                    .cursor_pointer()
 1218                    .child("")
 1219                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1220                    .on_click(move |_, _window, cx| {
 1221                        editor
 1222                            .update(cx, |editor, cx| {
 1223                                editor.unfold_ranges(
 1224                                    &[fold_range.start..fold_range.end],
 1225                                    true,
 1226                                    false,
 1227                                    cx,
 1228                                );
 1229                                cx.stop_propagation();
 1230                            })
 1231                            .ok();
 1232                    })
 1233                    .into_any()
 1234            }),
 1235            merge_adjacent: true,
 1236            ..Default::default()
 1237        };
 1238        let display_map = cx.new(|cx| {
 1239            DisplayMap::new(
 1240                buffer.clone(),
 1241                style.font(),
 1242                font_size,
 1243                None,
 1244                show_excerpt_controls,
 1245                FILE_HEADER_HEIGHT,
 1246                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1247                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1248                fold_placeholder,
 1249                cx,
 1250            )
 1251        });
 1252
 1253        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1254
 1255        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1256
 1257        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1258            .then(|| language_settings::SoftWrap::None);
 1259
 1260        let mut project_subscriptions = Vec::new();
 1261        if mode == EditorMode::Full {
 1262            if let Some(project) = project.as_ref() {
 1263                if buffer.read(cx).is_singleton() {
 1264                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1265                        cx.emit(EditorEvent::TitleChanged);
 1266                    }));
 1267                }
 1268                project_subscriptions.push(cx.subscribe_in(
 1269                    project,
 1270                    window,
 1271                    |editor, _, event, window, cx| {
 1272                        if let project::Event::RefreshInlayHints = event {
 1273                            editor
 1274                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1275                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1276                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1277                                let focus_handle = editor.focus_handle(cx);
 1278                                if focus_handle.is_focused(window) {
 1279                                    let snapshot = buffer.read(cx).snapshot();
 1280                                    for (range, snippet) in snippet_edits {
 1281                                        let editor_range =
 1282                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1283                                        editor
 1284                                            .insert_snippet(
 1285                                                &[editor_range],
 1286                                                snippet.clone(),
 1287                                                window,
 1288                                                cx,
 1289                                            )
 1290                                            .ok();
 1291                                    }
 1292                                }
 1293                            }
 1294                        }
 1295                    },
 1296                ));
 1297                if let Some(task_inventory) = project
 1298                    .read(cx)
 1299                    .task_store()
 1300                    .read(cx)
 1301                    .task_inventory()
 1302                    .cloned()
 1303                {
 1304                    project_subscriptions.push(cx.observe_in(
 1305                        &task_inventory,
 1306                        window,
 1307                        |editor, _, window, cx| {
 1308                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1309                        },
 1310                    ));
 1311                }
 1312            }
 1313        }
 1314
 1315        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1316
 1317        let inlay_hint_settings =
 1318            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1319        let focus_handle = cx.focus_handle();
 1320        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1321            .detach();
 1322        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1323            .detach();
 1324        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1325            .detach();
 1326        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1327            .detach();
 1328
 1329        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1330            Some(false)
 1331        } else {
 1332            None
 1333        };
 1334
 1335        let mut code_action_providers = Vec::new();
 1336        let mut load_uncommitted_diff = None;
 1337        if let Some(project) = project.clone() {
 1338            load_uncommitted_diff = Some(
 1339                get_uncommitted_diff_for_buffer(
 1340                    &project,
 1341                    buffer.read(cx).all_buffers(),
 1342                    buffer.clone(),
 1343                    cx,
 1344                )
 1345                .shared(),
 1346            );
 1347            code_action_providers.push(Rc::new(project) as Rc<_>);
 1348        }
 1349
 1350        let mut this = Self {
 1351            focus_handle,
 1352            show_cursor_when_unfocused: false,
 1353            last_focused_descendant: None,
 1354            buffer: buffer.clone(),
 1355            display_map: display_map.clone(),
 1356            selections,
 1357            scroll_manager: ScrollManager::new(cx),
 1358            columnar_selection_tail: None,
 1359            add_selections_state: None,
 1360            select_next_state: None,
 1361            select_prev_state: None,
 1362            selection_history: Default::default(),
 1363            autoclose_regions: Default::default(),
 1364            snippet_stack: Default::default(),
 1365            select_larger_syntax_node_stack: Vec::new(),
 1366            ime_transaction: Default::default(),
 1367            active_diagnostics: None,
 1368            soft_wrap_mode_override,
 1369            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1370            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1371            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1372            project,
 1373            blink_manager: blink_manager.clone(),
 1374            show_local_selections: true,
 1375            show_scrollbars: true,
 1376            mode,
 1377            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1378            show_gutter: mode == EditorMode::Full,
 1379            show_line_numbers: None,
 1380            use_relative_line_numbers: None,
 1381            show_git_diff_gutter: None,
 1382            show_code_actions: None,
 1383            show_runnables: None,
 1384            show_wrap_guides: None,
 1385            show_indent_guides,
 1386            placeholder_text: None,
 1387            highlight_order: 0,
 1388            highlighted_rows: HashMap::default(),
 1389            background_highlights: Default::default(),
 1390            gutter_highlights: TreeMap::default(),
 1391            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1392            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1393            nav_history: None,
 1394            context_menu: RefCell::new(None),
 1395            mouse_context_menu: None,
 1396            completion_tasks: Default::default(),
 1397            signature_help_state: SignatureHelpState::default(),
 1398            auto_signature_help: None,
 1399            find_all_references_task_sources: Vec::new(),
 1400            next_completion_id: 0,
 1401            next_inlay_id: 0,
 1402            code_action_providers,
 1403            available_code_actions: Default::default(),
 1404            code_actions_task: Default::default(),
 1405            selection_highlight_task: Default::default(),
 1406            document_highlights_task: Default::default(),
 1407            linked_editing_range_task: Default::default(),
 1408            pending_rename: Default::default(),
 1409            searchable: true,
 1410            cursor_shape: EditorSettings::get_global(cx)
 1411                .cursor_shape
 1412                .unwrap_or_default(),
 1413            current_line_highlight: None,
 1414            autoindent_mode: Some(AutoindentMode::EachLine),
 1415            collapse_matches: false,
 1416            workspace: None,
 1417            input_enabled: true,
 1418            use_modal_editing: mode == EditorMode::Full,
 1419            read_only: false,
 1420            use_autoclose: true,
 1421            use_auto_surround: true,
 1422            auto_replace_emoji_shortcode: false,
 1423            leader_peer_id: None,
 1424            remote_id: None,
 1425            hover_state: Default::default(),
 1426            pending_mouse_down: None,
 1427            hovered_link_state: Default::default(),
 1428            edit_prediction_provider: None,
 1429            active_inline_completion: None,
 1430            stale_inline_completion_in_menu: None,
 1431            edit_prediction_preview: EditPredictionPreview::Inactive,
 1432            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1433
 1434            gutter_hovered: false,
 1435            pixel_position_of_newest_cursor: None,
 1436            last_bounds: None,
 1437            last_position_map: None,
 1438            expect_bounds_change: None,
 1439            gutter_dimensions: GutterDimensions::default(),
 1440            style: None,
 1441            show_cursor_names: false,
 1442            hovered_cursors: Default::default(),
 1443            next_editor_action_id: EditorActionId::default(),
 1444            editor_actions: Rc::default(),
 1445            inline_completions_hidden_for_vim_mode: false,
 1446            show_inline_completions_override: None,
 1447            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1448            edit_prediction_settings: EditPredictionSettings::Disabled,
 1449            edit_prediction_cursor_on_leading_whitespace: false,
 1450            edit_prediction_requires_modifier_in_leading_space: true,
 1451            custom_context_menu: None,
 1452            show_git_blame_gutter: false,
 1453            show_git_blame_inline: false,
 1454            distinguish_unstaged_diff_hunks: false,
 1455            show_selection_menu: None,
 1456            show_git_blame_inline_delay_task: None,
 1457            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1458            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1459                .session
 1460                .restore_unsaved_buffers,
 1461            blame: None,
 1462            blame_subscription: None,
 1463            tasks: Default::default(),
 1464            _subscriptions: vec![
 1465                cx.observe(&buffer, Self::on_buffer_changed),
 1466                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1467                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1468                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1469                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1470                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1471                cx.observe_window_activation(window, |editor, window, cx| {
 1472                    let active = window.is_window_active();
 1473                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1474                        if active {
 1475                            blink_manager.enable(cx);
 1476                        } else {
 1477                            blink_manager.disable(cx);
 1478                        }
 1479                    });
 1480                }),
 1481            ],
 1482            tasks_update_task: None,
 1483            linked_edit_ranges: Default::default(),
 1484            in_project_search: false,
 1485            previous_search_ranges: None,
 1486            breadcrumb_header: None,
 1487            focused_block: None,
 1488            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1489            addons: HashMap::default(),
 1490            registered_buffers: HashMap::default(),
 1491            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1492            selection_mark_mode: false,
 1493            toggle_fold_multiple_buffers: Task::ready(()),
 1494            serialize_selections: Task::ready(()),
 1495            text_style_refinement: None,
 1496            load_diff_task: load_uncommitted_diff,
 1497        };
 1498        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1499        this._subscriptions.extend(project_subscriptions);
 1500
 1501        this.end_selection(window, cx);
 1502        this.scroll_manager.show_scrollbar(window, cx);
 1503
 1504        if mode == EditorMode::Full {
 1505            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1506            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1507
 1508            if this.git_blame_inline_enabled {
 1509                this.git_blame_inline_enabled = true;
 1510                this.start_git_blame_inline(false, window, cx);
 1511            }
 1512
 1513            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1514                if let Some(project) = this.project.as_ref() {
 1515                    let handle = project.update(cx, |project, cx| {
 1516                        project.register_buffer_with_language_servers(&buffer, cx)
 1517                    });
 1518                    this.registered_buffers
 1519                        .insert(buffer.read(cx).remote_id(), handle);
 1520                }
 1521            }
 1522        }
 1523
 1524        this.report_editor_event("Editor Opened", None, cx);
 1525        this
 1526    }
 1527
 1528    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1529        self.mouse_context_menu
 1530            .as_ref()
 1531            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1532    }
 1533
 1534    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1535        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1536    }
 1537
 1538    fn key_context_internal(
 1539        &self,
 1540        has_active_edit_prediction: bool,
 1541        window: &Window,
 1542        cx: &App,
 1543    ) -> KeyContext {
 1544        let mut key_context = KeyContext::new_with_defaults();
 1545        key_context.add("Editor");
 1546        let mode = match self.mode {
 1547            EditorMode::SingleLine { .. } => "single_line",
 1548            EditorMode::AutoHeight { .. } => "auto_height",
 1549            EditorMode::Full => "full",
 1550        };
 1551
 1552        if EditorSettings::jupyter_enabled(cx) {
 1553            key_context.add("jupyter");
 1554        }
 1555
 1556        key_context.set("mode", mode);
 1557        if self.pending_rename.is_some() {
 1558            key_context.add("renaming");
 1559        }
 1560
 1561        match self.context_menu.borrow().as_ref() {
 1562            Some(CodeContextMenu::Completions(_)) => {
 1563                key_context.add("menu");
 1564                key_context.add("showing_completions");
 1565            }
 1566            Some(CodeContextMenu::CodeActions(_)) => {
 1567                key_context.add("menu");
 1568                key_context.add("showing_code_actions")
 1569            }
 1570            None => {}
 1571        }
 1572
 1573        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1574        if !self.focus_handle(cx).contains_focused(window, cx)
 1575            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1576        {
 1577            for addon in self.addons.values() {
 1578                addon.extend_key_context(&mut key_context, cx)
 1579            }
 1580        }
 1581
 1582        if let Some(extension) = self
 1583            .buffer
 1584            .read(cx)
 1585            .as_singleton()
 1586            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1587        {
 1588            key_context.set("extension", extension.to_string());
 1589        }
 1590
 1591        if has_active_edit_prediction {
 1592            if self.edit_prediction_in_conflict() {
 1593                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1594            } else {
 1595                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1596                key_context.add("copilot_suggestion");
 1597            }
 1598        }
 1599
 1600        if self.selection_mark_mode {
 1601            key_context.add("selection_mode");
 1602        }
 1603
 1604        key_context
 1605    }
 1606
 1607    pub fn edit_prediction_in_conflict(&self) -> bool {
 1608        if !self.show_edit_predictions_in_menu() {
 1609            return false;
 1610        }
 1611
 1612        let showing_completions = self
 1613            .context_menu
 1614            .borrow()
 1615            .as_ref()
 1616            .map_or(false, |context| {
 1617                matches!(context, CodeContextMenu::Completions(_))
 1618            });
 1619
 1620        showing_completions
 1621            || self.edit_prediction_requires_modifier()
 1622            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1623            // bindings to insert tab characters.
 1624            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1625    }
 1626
 1627    pub fn accept_edit_prediction_keybind(
 1628        &self,
 1629        window: &Window,
 1630        cx: &App,
 1631    ) -> AcceptEditPredictionBinding {
 1632        let key_context = self.key_context_internal(true, window, cx);
 1633        let in_conflict = self.edit_prediction_in_conflict();
 1634
 1635        AcceptEditPredictionBinding(
 1636            window
 1637                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1638                .into_iter()
 1639                .filter(|binding| {
 1640                    !in_conflict
 1641                        || binding
 1642                            .keystrokes()
 1643                            .first()
 1644                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1645                })
 1646                .rev()
 1647                .min_by_key(|binding| {
 1648                    binding
 1649                        .keystrokes()
 1650                        .first()
 1651                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1652                }),
 1653        )
 1654    }
 1655
 1656    pub fn new_file(
 1657        workspace: &mut Workspace,
 1658        _: &workspace::NewFile,
 1659        window: &mut Window,
 1660        cx: &mut Context<Workspace>,
 1661    ) {
 1662        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1663            "Failed to create buffer",
 1664            window,
 1665            cx,
 1666            |e, _, _| match e.error_code() {
 1667                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1668                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1669                e.error_tag("required").unwrap_or("the latest version")
 1670            )),
 1671                _ => None,
 1672            },
 1673        );
 1674    }
 1675
 1676    pub fn new_in_workspace(
 1677        workspace: &mut Workspace,
 1678        window: &mut Window,
 1679        cx: &mut Context<Workspace>,
 1680    ) -> Task<Result<Entity<Editor>>> {
 1681        let project = workspace.project().clone();
 1682        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1683
 1684        cx.spawn_in(window, |workspace, mut cx| async move {
 1685            let buffer = create.await?;
 1686            workspace.update_in(&mut cx, |workspace, window, cx| {
 1687                let editor =
 1688                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1689                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1690                editor
 1691            })
 1692        })
 1693    }
 1694
 1695    fn new_file_vertical(
 1696        workspace: &mut Workspace,
 1697        _: &workspace::NewFileSplitVertical,
 1698        window: &mut Window,
 1699        cx: &mut Context<Workspace>,
 1700    ) {
 1701        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1702    }
 1703
 1704    fn new_file_horizontal(
 1705        workspace: &mut Workspace,
 1706        _: &workspace::NewFileSplitHorizontal,
 1707        window: &mut Window,
 1708        cx: &mut Context<Workspace>,
 1709    ) {
 1710        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1711    }
 1712
 1713    fn new_file_in_direction(
 1714        workspace: &mut Workspace,
 1715        direction: SplitDirection,
 1716        window: &mut Window,
 1717        cx: &mut Context<Workspace>,
 1718    ) {
 1719        let project = workspace.project().clone();
 1720        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1721
 1722        cx.spawn_in(window, |workspace, mut cx| async move {
 1723            let buffer = create.await?;
 1724            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1725                workspace.split_item(
 1726                    direction,
 1727                    Box::new(
 1728                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1729                    ),
 1730                    window,
 1731                    cx,
 1732                )
 1733            })?;
 1734            anyhow::Ok(())
 1735        })
 1736        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1737            match e.error_code() {
 1738                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1739                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1740                e.error_tag("required").unwrap_or("the latest version")
 1741            )),
 1742                _ => None,
 1743            }
 1744        });
 1745    }
 1746
 1747    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1748        self.leader_peer_id
 1749    }
 1750
 1751    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1752        &self.buffer
 1753    }
 1754
 1755    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1756        self.workspace.as_ref()?.0.upgrade()
 1757    }
 1758
 1759    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1760        self.buffer().read(cx).title(cx)
 1761    }
 1762
 1763    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1764        let git_blame_gutter_max_author_length = self
 1765            .render_git_blame_gutter(cx)
 1766            .then(|| {
 1767                if let Some(blame) = self.blame.as_ref() {
 1768                    let max_author_length =
 1769                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1770                    Some(max_author_length)
 1771                } else {
 1772                    None
 1773                }
 1774            })
 1775            .flatten();
 1776
 1777        EditorSnapshot {
 1778            mode: self.mode,
 1779            show_gutter: self.show_gutter,
 1780            show_line_numbers: self.show_line_numbers,
 1781            show_git_diff_gutter: self.show_git_diff_gutter,
 1782            show_code_actions: self.show_code_actions,
 1783            show_runnables: self.show_runnables,
 1784            git_blame_gutter_max_author_length,
 1785            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1786            scroll_anchor: self.scroll_manager.anchor(),
 1787            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1788            placeholder_text: self.placeholder_text.clone(),
 1789            is_focused: self.focus_handle.is_focused(window),
 1790            current_line_highlight: self
 1791                .current_line_highlight
 1792                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1793            gutter_hovered: self.gutter_hovered,
 1794        }
 1795    }
 1796
 1797    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1798        self.buffer.read(cx).language_at(point, cx)
 1799    }
 1800
 1801    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1802        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1803    }
 1804
 1805    pub fn active_excerpt(
 1806        &self,
 1807        cx: &App,
 1808    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1809        self.buffer
 1810            .read(cx)
 1811            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1812    }
 1813
 1814    pub fn mode(&self) -> EditorMode {
 1815        self.mode
 1816    }
 1817
 1818    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1819        self.collaboration_hub.as_deref()
 1820    }
 1821
 1822    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1823        self.collaboration_hub = Some(hub);
 1824    }
 1825
 1826    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1827        self.in_project_search = in_project_search;
 1828    }
 1829
 1830    pub fn set_custom_context_menu(
 1831        &mut self,
 1832        f: impl 'static
 1833            + Fn(
 1834                &mut Self,
 1835                DisplayPoint,
 1836                &mut Window,
 1837                &mut Context<Self>,
 1838            ) -> Option<Entity<ui::ContextMenu>>,
 1839    ) {
 1840        self.custom_context_menu = Some(Box::new(f))
 1841    }
 1842
 1843    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1844        self.completion_provider = provider;
 1845    }
 1846
 1847    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1848        self.semantics_provider.clone()
 1849    }
 1850
 1851    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1852        self.semantics_provider = provider;
 1853    }
 1854
 1855    pub fn set_edit_prediction_provider<T>(
 1856        &mut self,
 1857        provider: Option<Entity<T>>,
 1858        window: &mut Window,
 1859        cx: &mut Context<Self>,
 1860    ) where
 1861        T: EditPredictionProvider,
 1862    {
 1863        self.edit_prediction_provider =
 1864            provider.map(|provider| RegisteredInlineCompletionProvider {
 1865                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1866                    if this.focus_handle.is_focused(window) {
 1867                        this.update_visible_inline_completion(window, cx);
 1868                    }
 1869                }),
 1870                provider: Arc::new(provider),
 1871            });
 1872        self.refresh_inline_completion(false, false, window, cx);
 1873    }
 1874
 1875    pub fn placeholder_text(&self) -> Option<&str> {
 1876        self.placeholder_text.as_deref()
 1877    }
 1878
 1879    pub fn set_placeholder_text(
 1880        &mut self,
 1881        placeholder_text: impl Into<Arc<str>>,
 1882        cx: &mut Context<Self>,
 1883    ) {
 1884        let placeholder_text = Some(placeholder_text.into());
 1885        if self.placeholder_text != placeholder_text {
 1886            self.placeholder_text = placeholder_text;
 1887            cx.notify();
 1888        }
 1889    }
 1890
 1891    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1892        self.cursor_shape = cursor_shape;
 1893
 1894        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1895        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1896
 1897        cx.notify();
 1898    }
 1899
 1900    pub fn set_current_line_highlight(
 1901        &mut self,
 1902        current_line_highlight: Option<CurrentLineHighlight>,
 1903    ) {
 1904        self.current_line_highlight = current_line_highlight;
 1905    }
 1906
 1907    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1908        self.collapse_matches = collapse_matches;
 1909    }
 1910
 1911    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1912        let buffers = self.buffer.read(cx).all_buffers();
 1913        let Some(project) = self.project.as_ref() else {
 1914            return;
 1915        };
 1916        project.update(cx, |project, cx| {
 1917            for buffer in buffers {
 1918                self.registered_buffers
 1919                    .entry(buffer.read(cx).remote_id())
 1920                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1921            }
 1922        })
 1923    }
 1924
 1925    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1926        if self.collapse_matches {
 1927            return range.start..range.start;
 1928        }
 1929        range.clone()
 1930    }
 1931
 1932    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1933        if self.display_map.read(cx).clip_at_line_ends != clip {
 1934            self.display_map
 1935                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1936        }
 1937    }
 1938
 1939    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1940        self.input_enabled = input_enabled;
 1941    }
 1942
 1943    pub fn set_inline_completions_hidden_for_vim_mode(
 1944        &mut self,
 1945        hidden: bool,
 1946        window: &mut Window,
 1947        cx: &mut Context<Self>,
 1948    ) {
 1949        if hidden != self.inline_completions_hidden_for_vim_mode {
 1950            self.inline_completions_hidden_for_vim_mode = hidden;
 1951            if hidden {
 1952                self.update_visible_inline_completion(window, cx);
 1953            } else {
 1954                self.refresh_inline_completion(true, false, window, cx);
 1955            }
 1956        }
 1957    }
 1958
 1959    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1960        self.menu_inline_completions_policy = value;
 1961    }
 1962
 1963    pub fn set_autoindent(&mut self, autoindent: bool) {
 1964        if autoindent {
 1965            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1966        } else {
 1967            self.autoindent_mode = None;
 1968        }
 1969    }
 1970
 1971    pub fn read_only(&self, cx: &App) -> bool {
 1972        self.read_only || self.buffer.read(cx).read_only()
 1973    }
 1974
 1975    pub fn set_read_only(&mut self, read_only: bool) {
 1976        self.read_only = read_only;
 1977    }
 1978
 1979    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1980        self.use_autoclose = autoclose;
 1981    }
 1982
 1983    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1984        self.use_auto_surround = auto_surround;
 1985    }
 1986
 1987    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1988        self.auto_replace_emoji_shortcode = auto_replace;
 1989    }
 1990
 1991    pub fn toggle_inline_completions(
 1992        &mut self,
 1993        _: &ToggleEditPrediction,
 1994        window: &mut Window,
 1995        cx: &mut Context<Self>,
 1996    ) {
 1997        if self.show_inline_completions_override.is_some() {
 1998            self.set_show_edit_predictions(None, window, cx);
 1999        } else {
 2000            let show_edit_predictions = !self.edit_predictions_enabled();
 2001            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2002        }
 2003    }
 2004
 2005    pub fn set_show_edit_predictions(
 2006        &mut self,
 2007        show_edit_predictions: Option<bool>,
 2008        window: &mut Window,
 2009        cx: &mut Context<Self>,
 2010    ) {
 2011        self.show_inline_completions_override = show_edit_predictions;
 2012        self.refresh_inline_completion(false, true, window, cx);
 2013    }
 2014
 2015    fn inline_completions_disabled_in_scope(
 2016        &self,
 2017        buffer: &Entity<Buffer>,
 2018        buffer_position: language::Anchor,
 2019        cx: &App,
 2020    ) -> bool {
 2021        let snapshot = buffer.read(cx).snapshot();
 2022        let settings = snapshot.settings_at(buffer_position, cx);
 2023
 2024        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2025            return false;
 2026        };
 2027
 2028        scope.override_name().map_or(false, |scope_name| {
 2029            settings
 2030                .edit_predictions_disabled_in
 2031                .iter()
 2032                .any(|s| s == scope_name)
 2033        })
 2034    }
 2035
 2036    pub fn set_use_modal_editing(&mut self, to: bool) {
 2037        self.use_modal_editing = to;
 2038    }
 2039
 2040    pub fn use_modal_editing(&self) -> bool {
 2041        self.use_modal_editing
 2042    }
 2043
 2044    fn selections_did_change(
 2045        &mut self,
 2046        local: bool,
 2047        old_cursor_position: &Anchor,
 2048        show_completions: bool,
 2049        window: &mut Window,
 2050        cx: &mut Context<Self>,
 2051    ) {
 2052        window.invalidate_character_coordinates();
 2053
 2054        // Copy selections to primary selection buffer
 2055        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2056        if local {
 2057            let selections = self.selections.all::<usize>(cx);
 2058            let buffer_handle = self.buffer.read(cx).read(cx);
 2059
 2060            let mut text = String::new();
 2061            for (index, selection) in selections.iter().enumerate() {
 2062                let text_for_selection = buffer_handle
 2063                    .text_for_range(selection.start..selection.end)
 2064                    .collect::<String>();
 2065
 2066                text.push_str(&text_for_selection);
 2067                if index != selections.len() - 1 {
 2068                    text.push('\n');
 2069                }
 2070            }
 2071
 2072            if !text.is_empty() {
 2073                cx.write_to_primary(ClipboardItem::new_string(text));
 2074            }
 2075        }
 2076
 2077        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2078            self.buffer.update(cx, |buffer, cx| {
 2079                buffer.set_active_selections(
 2080                    &self.selections.disjoint_anchors(),
 2081                    self.selections.line_mode,
 2082                    self.cursor_shape,
 2083                    cx,
 2084                )
 2085            });
 2086        }
 2087        let display_map = self
 2088            .display_map
 2089            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2090        let buffer = &display_map.buffer_snapshot;
 2091        self.add_selections_state = None;
 2092        self.select_next_state = None;
 2093        self.select_prev_state = None;
 2094        self.select_larger_syntax_node_stack.clear();
 2095        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2096        self.snippet_stack
 2097            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2098        self.take_rename(false, window, cx);
 2099
 2100        let new_cursor_position = self.selections.newest_anchor().head();
 2101
 2102        self.push_to_nav_history(
 2103            *old_cursor_position,
 2104            Some(new_cursor_position.to_point(buffer)),
 2105            cx,
 2106        );
 2107
 2108        if local {
 2109            let new_cursor_position = self.selections.newest_anchor().head();
 2110            let mut context_menu = self.context_menu.borrow_mut();
 2111            let completion_menu = match context_menu.as_ref() {
 2112                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2113                _ => {
 2114                    *context_menu = None;
 2115                    None
 2116                }
 2117            };
 2118            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2119                if !self.registered_buffers.contains_key(&buffer_id) {
 2120                    if let Some(project) = self.project.as_ref() {
 2121                        project.update(cx, |project, cx| {
 2122                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2123                                return;
 2124                            };
 2125                            self.registered_buffers.insert(
 2126                                buffer_id,
 2127                                project.register_buffer_with_language_servers(&buffer, cx),
 2128                            );
 2129                        })
 2130                    }
 2131                }
 2132            }
 2133
 2134            if let Some(completion_menu) = completion_menu {
 2135                let cursor_position = new_cursor_position.to_offset(buffer);
 2136                let (word_range, kind) =
 2137                    buffer.surrounding_word(completion_menu.initial_position, true);
 2138                if kind == Some(CharKind::Word)
 2139                    && word_range.to_inclusive().contains(&cursor_position)
 2140                {
 2141                    let mut completion_menu = completion_menu.clone();
 2142                    drop(context_menu);
 2143
 2144                    let query = Self::completion_query(buffer, cursor_position);
 2145                    cx.spawn(move |this, mut cx| async move {
 2146                        completion_menu
 2147                            .filter(query.as_deref(), cx.background_executor().clone())
 2148                            .await;
 2149
 2150                        this.update(&mut cx, |this, cx| {
 2151                            let mut context_menu = this.context_menu.borrow_mut();
 2152                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2153                            else {
 2154                                return;
 2155                            };
 2156
 2157                            if menu.id > completion_menu.id {
 2158                                return;
 2159                            }
 2160
 2161                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2162                            drop(context_menu);
 2163                            cx.notify();
 2164                        })
 2165                    })
 2166                    .detach();
 2167
 2168                    if show_completions {
 2169                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2170                    }
 2171                } else {
 2172                    drop(context_menu);
 2173                    self.hide_context_menu(window, cx);
 2174                }
 2175            } else {
 2176                drop(context_menu);
 2177            }
 2178
 2179            hide_hover(self, cx);
 2180
 2181            if old_cursor_position.to_display_point(&display_map).row()
 2182                != new_cursor_position.to_display_point(&display_map).row()
 2183            {
 2184                self.available_code_actions.take();
 2185            }
 2186            self.refresh_code_actions(window, cx);
 2187            self.refresh_document_highlights(cx);
 2188            self.refresh_selected_text_highlights(window, cx);
 2189            refresh_matching_bracket_highlights(self, window, cx);
 2190            self.update_visible_inline_completion(window, cx);
 2191            self.edit_prediction_requires_modifier_in_leading_space = true;
 2192            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2193            if self.git_blame_inline_enabled {
 2194                self.start_inline_blame_timer(window, cx);
 2195            }
 2196        }
 2197
 2198        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2199        cx.emit(EditorEvent::SelectionsChanged { local });
 2200
 2201        let selections = &self.selections.disjoint;
 2202        if selections.len() == 1 {
 2203            cx.emit(SearchEvent::ActiveMatchChanged)
 2204        }
 2205        if local
 2206            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2207        {
 2208            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2209                let background_executor = cx.background_executor().clone();
 2210                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2211                let snapshot = self.buffer().read(cx).snapshot(cx);
 2212                let selections = selections.clone();
 2213                self.serialize_selections = cx.background_spawn(async move {
 2214                    background_executor.timer(Duration::from_millis(100)).await;
 2215                    let selections = selections
 2216                        .iter()
 2217                        .map(|selection| {
 2218                            (
 2219                                selection.start.to_offset(&snapshot),
 2220                                selection.end.to_offset(&snapshot),
 2221                            )
 2222                        })
 2223                        .collect();
 2224                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2225                        .await
 2226                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2227                        .log_err();
 2228                });
 2229            }
 2230        }
 2231
 2232        cx.notify();
 2233    }
 2234
 2235    pub fn change_selections<R>(
 2236        &mut self,
 2237        autoscroll: Option<Autoscroll>,
 2238        window: &mut Window,
 2239        cx: &mut Context<Self>,
 2240        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2241    ) -> R {
 2242        self.change_selections_inner(autoscroll, true, window, cx, change)
 2243    }
 2244
 2245    fn change_selections_inner<R>(
 2246        &mut self,
 2247        autoscroll: Option<Autoscroll>,
 2248        request_completions: bool,
 2249        window: &mut Window,
 2250        cx: &mut Context<Self>,
 2251        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2252    ) -> R {
 2253        let old_cursor_position = self.selections.newest_anchor().head();
 2254        self.push_to_selection_history();
 2255
 2256        let (changed, result) = self.selections.change_with(cx, change);
 2257
 2258        if changed {
 2259            if let Some(autoscroll) = autoscroll {
 2260                self.request_autoscroll(autoscroll, cx);
 2261            }
 2262            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2263
 2264            if self.should_open_signature_help_automatically(
 2265                &old_cursor_position,
 2266                self.signature_help_state.backspace_pressed(),
 2267                cx,
 2268            ) {
 2269                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2270            }
 2271            self.signature_help_state.set_backspace_pressed(false);
 2272        }
 2273
 2274        result
 2275    }
 2276
 2277    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2278    where
 2279        I: IntoIterator<Item = (Range<S>, T)>,
 2280        S: ToOffset,
 2281        T: Into<Arc<str>>,
 2282    {
 2283        if self.read_only(cx) {
 2284            return;
 2285        }
 2286
 2287        self.buffer
 2288            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2289    }
 2290
 2291    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2292    where
 2293        I: IntoIterator<Item = (Range<S>, T)>,
 2294        S: ToOffset,
 2295        T: Into<Arc<str>>,
 2296    {
 2297        if self.read_only(cx) {
 2298            return;
 2299        }
 2300
 2301        self.buffer.update(cx, |buffer, cx| {
 2302            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2303        });
 2304    }
 2305
 2306    pub fn edit_with_block_indent<I, S, T>(
 2307        &mut self,
 2308        edits: I,
 2309        original_indent_columns: Vec<u32>,
 2310        cx: &mut Context<Self>,
 2311    ) where
 2312        I: IntoIterator<Item = (Range<S>, T)>,
 2313        S: ToOffset,
 2314        T: Into<Arc<str>>,
 2315    {
 2316        if self.read_only(cx) {
 2317            return;
 2318        }
 2319
 2320        self.buffer.update(cx, |buffer, cx| {
 2321            buffer.edit(
 2322                edits,
 2323                Some(AutoindentMode::Block {
 2324                    original_indent_columns,
 2325                }),
 2326                cx,
 2327            )
 2328        });
 2329    }
 2330
 2331    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2332        self.hide_context_menu(window, cx);
 2333
 2334        match phase {
 2335            SelectPhase::Begin {
 2336                position,
 2337                add,
 2338                click_count,
 2339            } => self.begin_selection(position, add, click_count, window, cx),
 2340            SelectPhase::BeginColumnar {
 2341                position,
 2342                goal_column,
 2343                reset,
 2344            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2345            SelectPhase::Extend {
 2346                position,
 2347                click_count,
 2348            } => self.extend_selection(position, click_count, window, cx),
 2349            SelectPhase::Update {
 2350                position,
 2351                goal_column,
 2352                scroll_delta,
 2353            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2354            SelectPhase::End => self.end_selection(window, cx),
 2355        }
 2356    }
 2357
 2358    fn extend_selection(
 2359        &mut self,
 2360        position: DisplayPoint,
 2361        click_count: usize,
 2362        window: &mut Window,
 2363        cx: &mut Context<Self>,
 2364    ) {
 2365        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2366        let tail = self.selections.newest::<usize>(cx).tail();
 2367        self.begin_selection(position, false, click_count, window, cx);
 2368
 2369        let position = position.to_offset(&display_map, Bias::Left);
 2370        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2371
 2372        let mut pending_selection = self
 2373            .selections
 2374            .pending_anchor()
 2375            .expect("extend_selection not called with pending selection");
 2376        if position >= tail {
 2377            pending_selection.start = tail_anchor;
 2378        } else {
 2379            pending_selection.end = tail_anchor;
 2380            pending_selection.reversed = true;
 2381        }
 2382
 2383        let mut pending_mode = self.selections.pending_mode().unwrap();
 2384        match &mut pending_mode {
 2385            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2386            _ => {}
 2387        }
 2388
 2389        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2390            s.set_pending(pending_selection, pending_mode)
 2391        });
 2392    }
 2393
 2394    fn begin_selection(
 2395        &mut self,
 2396        position: DisplayPoint,
 2397        add: bool,
 2398        click_count: usize,
 2399        window: &mut Window,
 2400        cx: &mut Context<Self>,
 2401    ) {
 2402        if !self.focus_handle.is_focused(window) {
 2403            self.last_focused_descendant = None;
 2404            window.focus(&self.focus_handle);
 2405        }
 2406
 2407        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2408        let buffer = &display_map.buffer_snapshot;
 2409        let newest_selection = self.selections.newest_anchor().clone();
 2410        let position = display_map.clip_point(position, Bias::Left);
 2411
 2412        let start;
 2413        let end;
 2414        let mode;
 2415        let mut auto_scroll;
 2416        match click_count {
 2417            1 => {
 2418                start = buffer.anchor_before(position.to_point(&display_map));
 2419                end = start;
 2420                mode = SelectMode::Character;
 2421                auto_scroll = true;
 2422            }
 2423            2 => {
 2424                let range = movement::surrounding_word(&display_map, position);
 2425                start = buffer.anchor_before(range.start.to_point(&display_map));
 2426                end = buffer.anchor_before(range.end.to_point(&display_map));
 2427                mode = SelectMode::Word(start..end);
 2428                auto_scroll = true;
 2429            }
 2430            3 => {
 2431                let position = display_map
 2432                    .clip_point(position, Bias::Left)
 2433                    .to_point(&display_map);
 2434                let line_start = display_map.prev_line_boundary(position).0;
 2435                let next_line_start = buffer.clip_point(
 2436                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2437                    Bias::Left,
 2438                );
 2439                start = buffer.anchor_before(line_start);
 2440                end = buffer.anchor_before(next_line_start);
 2441                mode = SelectMode::Line(start..end);
 2442                auto_scroll = true;
 2443            }
 2444            _ => {
 2445                start = buffer.anchor_before(0);
 2446                end = buffer.anchor_before(buffer.len());
 2447                mode = SelectMode::All;
 2448                auto_scroll = false;
 2449            }
 2450        }
 2451        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2452
 2453        let point_to_delete: Option<usize> = {
 2454            let selected_points: Vec<Selection<Point>> =
 2455                self.selections.disjoint_in_range(start..end, cx);
 2456
 2457            if !add || click_count > 1 {
 2458                None
 2459            } else if !selected_points.is_empty() {
 2460                Some(selected_points[0].id)
 2461            } else {
 2462                let clicked_point_already_selected =
 2463                    self.selections.disjoint.iter().find(|selection| {
 2464                        selection.start.to_point(buffer) == start.to_point(buffer)
 2465                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2466                    });
 2467
 2468                clicked_point_already_selected.map(|selection| selection.id)
 2469            }
 2470        };
 2471
 2472        let selections_count = self.selections.count();
 2473
 2474        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2475            if let Some(point_to_delete) = point_to_delete {
 2476                s.delete(point_to_delete);
 2477
 2478                if selections_count == 1 {
 2479                    s.set_pending_anchor_range(start..end, mode);
 2480                }
 2481            } else {
 2482                if !add {
 2483                    s.clear_disjoint();
 2484                } else if click_count > 1 {
 2485                    s.delete(newest_selection.id)
 2486                }
 2487
 2488                s.set_pending_anchor_range(start..end, mode);
 2489            }
 2490        });
 2491    }
 2492
 2493    fn begin_columnar_selection(
 2494        &mut self,
 2495        position: DisplayPoint,
 2496        goal_column: u32,
 2497        reset: bool,
 2498        window: &mut Window,
 2499        cx: &mut Context<Self>,
 2500    ) {
 2501        if !self.focus_handle.is_focused(window) {
 2502            self.last_focused_descendant = None;
 2503            window.focus(&self.focus_handle);
 2504        }
 2505
 2506        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2507
 2508        if reset {
 2509            let pointer_position = display_map
 2510                .buffer_snapshot
 2511                .anchor_before(position.to_point(&display_map));
 2512
 2513            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2514                s.clear_disjoint();
 2515                s.set_pending_anchor_range(
 2516                    pointer_position..pointer_position,
 2517                    SelectMode::Character,
 2518                );
 2519            });
 2520        }
 2521
 2522        let tail = self.selections.newest::<Point>(cx).tail();
 2523        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2524
 2525        if !reset {
 2526            self.select_columns(
 2527                tail.to_display_point(&display_map),
 2528                position,
 2529                goal_column,
 2530                &display_map,
 2531                window,
 2532                cx,
 2533            );
 2534        }
 2535    }
 2536
 2537    fn update_selection(
 2538        &mut self,
 2539        position: DisplayPoint,
 2540        goal_column: u32,
 2541        scroll_delta: gpui::Point<f32>,
 2542        window: &mut Window,
 2543        cx: &mut Context<Self>,
 2544    ) {
 2545        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2546
 2547        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2548            let tail = tail.to_display_point(&display_map);
 2549            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2550        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2551            let buffer = self.buffer.read(cx).snapshot(cx);
 2552            let head;
 2553            let tail;
 2554            let mode = self.selections.pending_mode().unwrap();
 2555            match &mode {
 2556                SelectMode::Character => {
 2557                    head = position.to_point(&display_map);
 2558                    tail = pending.tail().to_point(&buffer);
 2559                }
 2560                SelectMode::Word(original_range) => {
 2561                    let original_display_range = original_range.start.to_display_point(&display_map)
 2562                        ..original_range.end.to_display_point(&display_map);
 2563                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2564                        ..original_display_range.end.to_point(&display_map);
 2565                    if movement::is_inside_word(&display_map, position)
 2566                        || original_display_range.contains(&position)
 2567                    {
 2568                        let word_range = movement::surrounding_word(&display_map, position);
 2569                        if word_range.start < original_display_range.start {
 2570                            head = word_range.start.to_point(&display_map);
 2571                        } else {
 2572                            head = word_range.end.to_point(&display_map);
 2573                        }
 2574                    } else {
 2575                        head = position.to_point(&display_map);
 2576                    }
 2577
 2578                    if head <= original_buffer_range.start {
 2579                        tail = original_buffer_range.end;
 2580                    } else {
 2581                        tail = original_buffer_range.start;
 2582                    }
 2583                }
 2584                SelectMode::Line(original_range) => {
 2585                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2586
 2587                    let position = display_map
 2588                        .clip_point(position, Bias::Left)
 2589                        .to_point(&display_map);
 2590                    let line_start = display_map.prev_line_boundary(position).0;
 2591                    let next_line_start = buffer.clip_point(
 2592                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2593                        Bias::Left,
 2594                    );
 2595
 2596                    if line_start < original_range.start {
 2597                        head = line_start
 2598                    } else {
 2599                        head = next_line_start
 2600                    }
 2601
 2602                    if head <= original_range.start {
 2603                        tail = original_range.end;
 2604                    } else {
 2605                        tail = original_range.start;
 2606                    }
 2607                }
 2608                SelectMode::All => {
 2609                    return;
 2610                }
 2611            };
 2612
 2613            if head < tail {
 2614                pending.start = buffer.anchor_before(head);
 2615                pending.end = buffer.anchor_before(tail);
 2616                pending.reversed = true;
 2617            } else {
 2618                pending.start = buffer.anchor_before(tail);
 2619                pending.end = buffer.anchor_before(head);
 2620                pending.reversed = false;
 2621            }
 2622
 2623            self.change_selections(None, window, cx, |s| {
 2624                s.set_pending(pending, mode);
 2625            });
 2626        } else {
 2627            log::error!("update_selection dispatched with no pending selection");
 2628            return;
 2629        }
 2630
 2631        self.apply_scroll_delta(scroll_delta, window, cx);
 2632        cx.notify();
 2633    }
 2634
 2635    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2636        self.columnar_selection_tail.take();
 2637        if self.selections.pending_anchor().is_some() {
 2638            let selections = self.selections.all::<usize>(cx);
 2639            self.change_selections(None, window, cx, |s| {
 2640                s.select(selections);
 2641                s.clear_pending();
 2642            });
 2643        }
 2644    }
 2645
 2646    fn select_columns(
 2647        &mut self,
 2648        tail: DisplayPoint,
 2649        head: DisplayPoint,
 2650        goal_column: u32,
 2651        display_map: &DisplaySnapshot,
 2652        window: &mut Window,
 2653        cx: &mut Context<Self>,
 2654    ) {
 2655        let start_row = cmp::min(tail.row(), head.row());
 2656        let end_row = cmp::max(tail.row(), head.row());
 2657        let start_column = cmp::min(tail.column(), goal_column);
 2658        let end_column = cmp::max(tail.column(), goal_column);
 2659        let reversed = start_column < tail.column();
 2660
 2661        let selection_ranges = (start_row.0..=end_row.0)
 2662            .map(DisplayRow)
 2663            .filter_map(|row| {
 2664                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2665                    let start = display_map
 2666                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2667                        .to_point(display_map);
 2668                    let end = display_map
 2669                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2670                        .to_point(display_map);
 2671                    if reversed {
 2672                        Some(end..start)
 2673                    } else {
 2674                        Some(start..end)
 2675                    }
 2676                } else {
 2677                    None
 2678                }
 2679            })
 2680            .collect::<Vec<_>>();
 2681
 2682        self.change_selections(None, window, cx, |s| {
 2683            s.select_ranges(selection_ranges);
 2684        });
 2685        cx.notify();
 2686    }
 2687
 2688    pub fn has_pending_nonempty_selection(&self) -> bool {
 2689        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2690            Some(Selection { start, end, .. }) => start != end,
 2691            None => false,
 2692        };
 2693
 2694        pending_nonempty_selection
 2695            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2696    }
 2697
 2698    pub fn has_pending_selection(&self) -> bool {
 2699        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2700    }
 2701
 2702    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2703        self.selection_mark_mode = false;
 2704
 2705        if self.clear_expanded_diff_hunks(cx) {
 2706            cx.notify();
 2707            return;
 2708        }
 2709        if self.dismiss_menus_and_popups(true, window, cx) {
 2710            return;
 2711        }
 2712
 2713        if self.mode == EditorMode::Full
 2714            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2715        {
 2716            return;
 2717        }
 2718
 2719        cx.propagate();
 2720    }
 2721
 2722    pub fn dismiss_menus_and_popups(
 2723        &mut self,
 2724        is_user_requested: bool,
 2725        window: &mut Window,
 2726        cx: &mut Context<Self>,
 2727    ) -> bool {
 2728        if self.take_rename(false, window, cx).is_some() {
 2729            return true;
 2730        }
 2731
 2732        if hide_hover(self, cx) {
 2733            return true;
 2734        }
 2735
 2736        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2737            return true;
 2738        }
 2739
 2740        if self.hide_context_menu(window, cx).is_some() {
 2741            return true;
 2742        }
 2743
 2744        if self.mouse_context_menu.take().is_some() {
 2745            return true;
 2746        }
 2747
 2748        if is_user_requested && self.discard_inline_completion(true, cx) {
 2749            return true;
 2750        }
 2751
 2752        if self.snippet_stack.pop().is_some() {
 2753            return true;
 2754        }
 2755
 2756        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2757            self.dismiss_diagnostics(cx);
 2758            return true;
 2759        }
 2760
 2761        false
 2762    }
 2763
 2764    fn linked_editing_ranges_for(
 2765        &self,
 2766        selection: Range<text::Anchor>,
 2767        cx: &App,
 2768    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2769        if self.linked_edit_ranges.is_empty() {
 2770            return None;
 2771        }
 2772        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2773            selection.end.buffer_id.and_then(|end_buffer_id| {
 2774                if selection.start.buffer_id != Some(end_buffer_id) {
 2775                    return None;
 2776                }
 2777                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2778                let snapshot = buffer.read(cx).snapshot();
 2779                self.linked_edit_ranges
 2780                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2781                    .map(|ranges| (ranges, snapshot, buffer))
 2782            })?;
 2783        use text::ToOffset as TO;
 2784        // find offset from the start of current range to current cursor position
 2785        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2786
 2787        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2788        let start_difference = start_offset - start_byte_offset;
 2789        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2790        let end_difference = end_offset - start_byte_offset;
 2791        // Current range has associated linked ranges.
 2792        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2793        for range in linked_ranges.iter() {
 2794            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2795            let end_offset = start_offset + end_difference;
 2796            let start_offset = start_offset + start_difference;
 2797            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2798                continue;
 2799            }
 2800            if self.selections.disjoint_anchor_ranges().any(|s| {
 2801                if s.start.buffer_id != selection.start.buffer_id
 2802                    || s.end.buffer_id != selection.end.buffer_id
 2803                {
 2804                    return false;
 2805                }
 2806                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2807                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2808            }) {
 2809                continue;
 2810            }
 2811            let start = buffer_snapshot.anchor_after(start_offset);
 2812            let end = buffer_snapshot.anchor_after(end_offset);
 2813            linked_edits
 2814                .entry(buffer.clone())
 2815                .or_default()
 2816                .push(start..end);
 2817        }
 2818        Some(linked_edits)
 2819    }
 2820
 2821    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2822        let text: Arc<str> = text.into();
 2823
 2824        if self.read_only(cx) {
 2825            return;
 2826        }
 2827
 2828        let selections = self.selections.all_adjusted(cx);
 2829        let mut bracket_inserted = false;
 2830        let mut edits = Vec::new();
 2831        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2832        let mut new_selections = Vec::with_capacity(selections.len());
 2833        let mut new_autoclose_regions = Vec::new();
 2834        let snapshot = self.buffer.read(cx).read(cx);
 2835
 2836        for (selection, autoclose_region) in
 2837            self.selections_with_autoclose_regions(selections, &snapshot)
 2838        {
 2839            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2840                // Determine if the inserted text matches the opening or closing
 2841                // bracket of any of this language's bracket pairs.
 2842                let mut bracket_pair = None;
 2843                let mut is_bracket_pair_start = false;
 2844                let mut is_bracket_pair_end = false;
 2845                if !text.is_empty() {
 2846                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2847                    //  and they are removing the character that triggered IME popup.
 2848                    for (pair, enabled) in scope.brackets() {
 2849                        if !pair.close && !pair.surround {
 2850                            continue;
 2851                        }
 2852
 2853                        if enabled && pair.start.ends_with(text.as_ref()) {
 2854                            let prefix_len = pair.start.len() - text.len();
 2855                            let preceding_text_matches_prefix = prefix_len == 0
 2856                                || (selection.start.column >= (prefix_len as u32)
 2857                                    && snapshot.contains_str_at(
 2858                                        Point::new(
 2859                                            selection.start.row,
 2860                                            selection.start.column - (prefix_len as u32),
 2861                                        ),
 2862                                        &pair.start[..prefix_len],
 2863                                    ));
 2864                            if preceding_text_matches_prefix {
 2865                                bracket_pair = Some(pair.clone());
 2866                                is_bracket_pair_start = true;
 2867                                break;
 2868                            }
 2869                        }
 2870                        if pair.end.as_str() == text.as_ref() {
 2871                            bracket_pair = Some(pair.clone());
 2872                            is_bracket_pair_end = true;
 2873                            break;
 2874                        }
 2875                    }
 2876                }
 2877
 2878                if let Some(bracket_pair) = bracket_pair {
 2879                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2880                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2881                    let auto_surround =
 2882                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2883                    if selection.is_empty() {
 2884                        if is_bracket_pair_start {
 2885                            // If the inserted text is a suffix of an opening bracket and the
 2886                            // selection is preceded by the rest of the opening bracket, then
 2887                            // insert the closing bracket.
 2888                            let following_text_allows_autoclose = snapshot
 2889                                .chars_at(selection.start)
 2890                                .next()
 2891                                .map_or(true, |c| scope.should_autoclose_before(c));
 2892
 2893                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2894                                && bracket_pair.start.len() == 1
 2895                            {
 2896                                let target = bracket_pair.start.chars().next().unwrap();
 2897                                let current_line_count = snapshot
 2898                                    .reversed_chars_at(selection.start)
 2899                                    .take_while(|&c| c != '\n')
 2900                                    .filter(|&c| c == target)
 2901                                    .count();
 2902                                current_line_count % 2 == 1
 2903                            } else {
 2904                                false
 2905                            };
 2906
 2907                            if autoclose
 2908                                && bracket_pair.close
 2909                                && following_text_allows_autoclose
 2910                                && !is_closing_quote
 2911                            {
 2912                                let anchor = snapshot.anchor_before(selection.end);
 2913                                new_selections.push((selection.map(|_| anchor), text.len()));
 2914                                new_autoclose_regions.push((
 2915                                    anchor,
 2916                                    text.len(),
 2917                                    selection.id,
 2918                                    bracket_pair.clone(),
 2919                                ));
 2920                                edits.push((
 2921                                    selection.range(),
 2922                                    format!("{}{}", text, bracket_pair.end).into(),
 2923                                ));
 2924                                bracket_inserted = true;
 2925                                continue;
 2926                            }
 2927                        }
 2928
 2929                        if let Some(region) = autoclose_region {
 2930                            // If the selection is followed by an auto-inserted closing bracket,
 2931                            // then don't insert that closing bracket again; just move the selection
 2932                            // past the closing bracket.
 2933                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2934                                && text.as_ref() == region.pair.end.as_str();
 2935                            if should_skip {
 2936                                let anchor = snapshot.anchor_after(selection.end);
 2937                                new_selections
 2938                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2939                                continue;
 2940                            }
 2941                        }
 2942
 2943                        let always_treat_brackets_as_autoclosed = snapshot
 2944                            .settings_at(selection.start, cx)
 2945                            .always_treat_brackets_as_autoclosed;
 2946                        if always_treat_brackets_as_autoclosed
 2947                            && is_bracket_pair_end
 2948                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2949                        {
 2950                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2951                            // and the inserted text is a closing bracket and the selection is followed
 2952                            // by the closing bracket then move the selection past the closing bracket.
 2953                            let anchor = snapshot.anchor_after(selection.end);
 2954                            new_selections.push((selection.map(|_| anchor), text.len()));
 2955                            continue;
 2956                        }
 2957                    }
 2958                    // If an opening bracket is 1 character long and is typed while
 2959                    // text is selected, then surround that text with the bracket pair.
 2960                    else if auto_surround
 2961                        && bracket_pair.surround
 2962                        && is_bracket_pair_start
 2963                        && bracket_pair.start.chars().count() == 1
 2964                    {
 2965                        edits.push((selection.start..selection.start, text.clone()));
 2966                        edits.push((
 2967                            selection.end..selection.end,
 2968                            bracket_pair.end.as_str().into(),
 2969                        ));
 2970                        bracket_inserted = true;
 2971                        new_selections.push((
 2972                            Selection {
 2973                                id: selection.id,
 2974                                start: snapshot.anchor_after(selection.start),
 2975                                end: snapshot.anchor_before(selection.end),
 2976                                reversed: selection.reversed,
 2977                                goal: selection.goal,
 2978                            },
 2979                            0,
 2980                        ));
 2981                        continue;
 2982                    }
 2983                }
 2984            }
 2985
 2986            if self.auto_replace_emoji_shortcode
 2987                && selection.is_empty()
 2988                && text.as_ref().ends_with(':')
 2989            {
 2990                if let Some(possible_emoji_short_code) =
 2991                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2992                {
 2993                    if !possible_emoji_short_code.is_empty() {
 2994                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2995                            let emoji_shortcode_start = Point::new(
 2996                                selection.start.row,
 2997                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2998                            );
 2999
 3000                            // Remove shortcode from buffer
 3001                            edits.push((
 3002                                emoji_shortcode_start..selection.start,
 3003                                "".to_string().into(),
 3004                            ));
 3005                            new_selections.push((
 3006                                Selection {
 3007                                    id: selection.id,
 3008                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3009                                    end: snapshot.anchor_before(selection.start),
 3010                                    reversed: selection.reversed,
 3011                                    goal: selection.goal,
 3012                                },
 3013                                0,
 3014                            ));
 3015
 3016                            // Insert emoji
 3017                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3018                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3019                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3020
 3021                            continue;
 3022                        }
 3023                    }
 3024                }
 3025            }
 3026
 3027            // If not handling any auto-close operation, then just replace the selected
 3028            // text with the given input and move the selection to the end of the
 3029            // newly inserted text.
 3030            let anchor = snapshot.anchor_after(selection.end);
 3031            if !self.linked_edit_ranges.is_empty() {
 3032                let start_anchor = snapshot.anchor_before(selection.start);
 3033
 3034                let is_word_char = text.chars().next().map_or(true, |char| {
 3035                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3036                    classifier.is_word(char)
 3037                });
 3038
 3039                if is_word_char {
 3040                    if let Some(ranges) = self
 3041                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3042                    {
 3043                        for (buffer, edits) in ranges {
 3044                            linked_edits
 3045                                .entry(buffer.clone())
 3046                                .or_default()
 3047                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3048                        }
 3049                    }
 3050                }
 3051            }
 3052
 3053            new_selections.push((selection.map(|_| anchor), 0));
 3054            edits.push((selection.start..selection.end, text.clone()));
 3055        }
 3056
 3057        drop(snapshot);
 3058
 3059        self.transact(window, cx, |this, window, cx| {
 3060            this.buffer.update(cx, |buffer, cx| {
 3061                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3062            });
 3063            for (buffer, edits) in linked_edits {
 3064                buffer.update(cx, |buffer, cx| {
 3065                    let snapshot = buffer.snapshot();
 3066                    let edits = edits
 3067                        .into_iter()
 3068                        .map(|(range, text)| {
 3069                            use text::ToPoint as TP;
 3070                            let end_point = TP::to_point(&range.end, &snapshot);
 3071                            let start_point = TP::to_point(&range.start, &snapshot);
 3072                            (start_point..end_point, text)
 3073                        })
 3074                        .sorted_by_key(|(range, _)| range.start)
 3075                        .collect::<Vec<_>>();
 3076                    buffer.edit(edits, None, cx);
 3077                })
 3078            }
 3079            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3080            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3081            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3082            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3083                .zip(new_selection_deltas)
 3084                .map(|(selection, delta)| Selection {
 3085                    id: selection.id,
 3086                    start: selection.start + delta,
 3087                    end: selection.end + delta,
 3088                    reversed: selection.reversed,
 3089                    goal: SelectionGoal::None,
 3090                })
 3091                .collect::<Vec<_>>();
 3092
 3093            let mut i = 0;
 3094            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3095                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3096                let start = map.buffer_snapshot.anchor_before(position);
 3097                let end = map.buffer_snapshot.anchor_after(position);
 3098                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3099                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3100                        Ordering::Less => i += 1,
 3101                        Ordering::Greater => break,
 3102                        Ordering::Equal => {
 3103                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3104                                Ordering::Less => i += 1,
 3105                                Ordering::Equal => break,
 3106                                Ordering::Greater => break,
 3107                            }
 3108                        }
 3109                    }
 3110                }
 3111                this.autoclose_regions.insert(
 3112                    i,
 3113                    AutocloseRegion {
 3114                        selection_id,
 3115                        range: start..end,
 3116                        pair,
 3117                    },
 3118                );
 3119            }
 3120
 3121            let had_active_inline_completion = this.has_active_inline_completion();
 3122            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3123                s.select(new_selections)
 3124            });
 3125
 3126            if !bracket_inserted {
 3127                if let Some(on_type_format_task) =
 3128                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3129                {
 3130                    on_type_format_task.detach_and_log_err(cx);
 3131                }
 3132            }
 3133
 3134            let editor_settings = EditorSettings::get_global(cx);
 3135            if bracket_inserted
 3136                && (editor_settings.auto_signature_help
 3137                    || editor_settings.show_signature_help_after_edits)
 3138            {
 3139                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3140            }
 3141
 3142            let trigger_in_words =
 3143                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3144            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3145            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3146            this.refresh_inline_completion(true, false, window, cx);
 3147        });
 3148    }
 3149
 3150    fn find_possible_emoji_shortcode_at_position(
 3151        snapshot: &MultiBufferSnapshot,
 3152        position: Point,
 3153    ) -> Option<String> {
 3154        let mut chars = Vec::new();
 3155        let mut found_colon = false;
 3156        for char in snapshot.reversed_chars_at(position).take(100) {
 3157            // Found a possible emoji shortcode in the middle of the buffer
 3158            if found_colon {
 3159                if char.is_whitespace() {
 3160                    chars.reverse();
 3161                    return Some(chars.iter().collect());
 3162                }
 3163                // If the previous character is not a whitespace, we are in the middle of a word
 3164                // and we only want to complete the shortcode if the word is made up of other emojis
 3165                let mut containing_word = String::new();
 3166                for ch in snapshot
 3167                    .reversed_chars_at(position)
 3168                    .skip(chars.len() + 1)
 3169                    .take(100)
 3170                {
 3171                    if ch.is_whitespace() {
 3172                        break;
 3173                    }
 3174                    containing_word.push(ch);
 3175                }
 3176                let containing_word = containing_word.chars().rev().collect::<String>();
 3177                if util::word_consists_of_emojis(containing_word.as_str()) {
 3178                    chars.reverse();
 3179                    return Some(chars.iter().collect());
 3180                }
 3181            }
 3182
 3183            if char.is_whitespace() || !char.is_ascii() {
 3184                return None;
 3185            }
 3186            if char == ':' {
 3187                found_colon = true;
 3188            } else {
 3189                chars.push(char);
 3190            }
 3191        }
 3192        // Found a possible emoji shortcode at the beginning of the buffer
 3193        chars.reverse();
 3194        Some(chars.iter().collect())
 3195    }
 3196
 3197    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3198        self.transact(window, cx, |this, window, cx| {
 3199            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3200                let selections = this.selections.all::<usize>(cx);
 3201                let multi_buffer = this.buffer.read(cx);
 3202                let buffer = multi_buffer.snapshot(cx);
 3203                selections
 3204                    .iter()
 3205                    .map(|selection| {
 3206                        let start_point = selection.start.to_point(&buffer);
 3207                        let mut indent =
 3208                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3209                        indent.len = cmp::min(indent.len, start_point.column);
 3210                        let start = selection.start;
 3211                        let end = selection.end;
 3212                        let selection_is_empty = start == end;
 3213                        let language_scope = buffer.language_scope_at(start);
 3214                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3215                            &language_scope
 3216                        {
 3217                            let leading_whitespace_len = buffer
 3218                                .reversed_chars_at(start)
 3219                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3220                                .map(|c| c.len_utf8())
 3221                                .sum::<usize>();
 3222
 3223                            let trailing_whitespace_len = buffer
 3224                                .chars_at(end)
 3225                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3226                                .map(|c| c.len_utf8())
 3227                                .sum::<usize>();
 3228
 3229                            let insert_extra_newline =
 3230                                language.brackets().any(|(pair, enabled)| {
 3231                                    let pair_start = pair.start.trim_end();
 3232                                    let pair_end = pair.end.trim_start();
 3233
 3234                                    enabled
 3235                                        && pair.newline
 3236                                        && buffer.contains_str_at(
 3237                                            end + trailing_whitespace_len,
 3238                                            pair_end,
 3239                                        )
 3240                                        && buffer.contains_str_at(
 3241                                            (start - leading_whitespace_len)
 3242                                                .saturating_sub(pair_start.len()),
 3243                                            pair_start,
 3244                                        )
 3245                                });
 3246
 3247                            // Comment extension on newline is allowed only for cursor selections
 3248                            let comment_delimiter = maybe!({
 3249                                if !selection_is_empty {
 3250                                    return None;
 3251                                }
 3252
 3253                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3254                                    return None;
 3255                                }
 3256
 3257                                let delimiters = language.line_comment_prefixes();
 3258                                let max_len_of_delimiter =
 3259                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3260                                let (snapshot, range) =
 3261                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3262
 3263                                let mut index_of_first_non_whitespace = 0;
 3264                                let comment_candidate = snapshot
 3265                                    .chars_for_range(range)
 3266                                    .skip_while(|c| {
 3267                                        let should_skip = c.is_whitespace();
 3268                                        if should_skip {
 3269                                            index_of_first_non_whitespace += 1;
 3270                                        }
 3271                                        should_skip
 3272                                    })
 3273                                    .take(max_len_of_delimiter)
 3274                                    .collect::<String>();
 3275                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3276                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3277                                })?;
 3278                                let cursor_is_placed_after_comment_marker =
 3279                                    index_of_first_non_whitespace + comment_prefix.len()
 3280                                        <= start_point.column as usize;
 3281                                if cursor_is_placed_after_comment_marker {
 3282                                    Some(comment_prefix.clone())
 3283                                } else {
 3284                                    None
 3285                                }
 3286                            });
 3287                            (comment_delimiter, insert_extra_newline)
 3288                        } else {
 3289                            (None, false)
 3290                        };
 3291
 3292                        let capacity_for_delimiter = comment_delimiter
 3293                            .as_deref()
 3294                            .map(str::len)
 3295                            .unwrap_or_default();
 3296                        let mut new_text =
 3297                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3298                        new_text.push('\n');
 3299                        new_text.extend(indent.chars());
 3300                        if let Some(delimiter) = &comment_delimiter {
 3301                            new_text.push_str(delimiter);
 3302                        }
 3303                        if insert_extra_newline {
 3304                            new_text = new_text.repeat(2);
 3305                        }
 3306
 3307                        let anchor = buffer.anchor_after(end);
 3308                        let new_selection = selection.map(|_| anchor);
 3309                        (
 3310                            (start..end, new_text),
 3311                            (insert_extra_newline, new_selection),
 3312                        )
 3313                    })
 3314                    .unzip()
 3315            };
 3316
 3317            this.edit_with_autoindent(edits, cx);
 3318            let buffer = this.buffer.read(cx).snapshot(cx);
 3319            let new_selections = selection_fixup_info
 3320                .into_iter()
 3321                .map(|(extra_newline_inserted, new_selection)| {
 3322                    let mut cursor = new_selection.end.to_point(&buffer);
 3323                    if extra_newline_inserted {
 3324                        cursor.row -= 1;
 3325                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3326                    }
 3327                    new_selection.map(|_| cursor)
 3328                })
 3329                .collect();
 3330
 3331            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3332                s.select(new_selections)
 3333            });
 3334            this.refresh_inline_completion(true, false, window, cx);
 3335        });
 3336    }
 3337
 3338    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3339        let buffer = self.buffer.read(cx);
 3340        let snapshot = buffer.snapshot(cx);
 3341
 3342        let mut edits = Vec::new();
 3343        let mut rows = Vec::new();
 3344
 3345        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3346            let cursor = selection.head();
 3347            let row = cursor.row;
 3348
 3349            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3350
 3351            let newline = "\n".to_string();
 3352            edits.push((start_of_line..start_of_line, newline));
 3353
 3354            rows.push(row + rows_inserted as u32);
 3355        }
 3356
 3357        self.transact(window, cx, |editor, window, cx| {
 3358            editor.edit(edits, cx);
 3359
 3360            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3361                let mut index = 0;
 3362                s.move_cursors_with(|map, _, _| {
 3363                    let row = rows[index];
 3364                    index += 1;
 3365
 3366                    let point = Point::new(row, 0);
 3367                    let boundary = map.next_line_boundary(point).1;
 3368                    let clipped = map.clip_point(boundary, Bias::Left);
 3369
 3370                    (clipped, SelectionGoal::None)
 3371                });
 3372            });
 3373
 3374            let mut indent_edits = Vec::new();
 3375            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3376            for row in rows {
 3377                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3378                for (row, indent) in indents {
 3379                    if indent.len == 0 {
 3380                        continue;
 3381                    }
 3382
 3383                    let text = match indent.kind {
 3384                        IndentKind::Space => " ".repeat(indent.len as usize),
 3385                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3386                    };
 3387                    let point = Point::new(row.0, 0);
 3388                    indent_edits.push((point..point, text));
 3389                }
 3390            }
 3391            editor.edit(indent_edits, cx);
 3392        });
 3393    }
 3394
 3395    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3396        let buffer = self.buffer.read(cx);
 3397        let snapshot = buffer.snapshot(cx);
 3398
 3399        let mut edits = Vec::new();
 3400        let mut rows = Vec::new();
 3401        let mut rows_inserted = 0;
 3402
 3403        for selection in self.selections.all_adjusted(cx) {
 3404            let cursor = selection.head();
 3405            let row = cursor.row;
 3406
 3407            let point = Point::new(row + 1, 0);
 3408            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3409
 3410            let newline = "\n".to_string();
 3411            edits.push((start_of_line..start_of_line, newline));
 3412
 3413            rows_inserted += 1;
 3414            rows.push(row + rows_inserted);
 3415        }
 3416
 3417        self.transact(window, cx, |editor, window, cx| {
 3418            editor.edit(edits, cx);
 3419
 3420            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3421                let mut index = 0;
 3422                s.move_cursors_with(|map, _, _| {
 3423                    let row = rows[index];
 3424                    index += 1;
 3425
 3426                    let point = Point::new(row, 0);
 3427                    let boundary = map.next_line_boundary(point).1;
 3428                    let clipped = map.clip_point(boundary, Bias::Left);
 3429
 3430                    (clipped, SelectionGoal::None)
 3431                });
 3432            });
 3433
 3434            let mut indent_edits = Vec::new();
 3435            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3436            for row in rows {
 3437                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3438                for (row, indent) in indents {
 3439                    if indent.len == 0 {
 3440                        continue;
 3441                    }
 3442
 3443                    let text = match indent.kind {
 3444                        IndentKind::Space => " ".repeat(indent.len as usize),
 3445                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3446                    };
 3447                    let point = Point::new(row.0, 0);
 3448                    indent_edits.push((point..point, text));
 3449                }
 3450            }
 3451            editor.edit(indent_edits, cx);
 3452        });
 3453    }
 3454
 3455    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3456        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3457            original_indent_columns: Vec::new(),
 3458        });
 3459        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3460    }
 3461
 3462    fn insert_with_autoindent_mode(
 3463        &mut self,
 3464        text: &str,
 3465        autoindent_mode: Option<AutoindentMode>,
 3466        window: &mut Window,
 3467        cx: &mut Context<Self>,
 3468    ) {
 3469        if self.read_only(cx) {
 3470            return;
 3471        }
 3472
 3473        let text: Arc<str> = text.into();
 3474        self.transact(window, cx, |this, window, cx| {
 3475            let old_selections = this.selections.all_adjusted(cx);
 3476            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3477                let anchors = {
 3478                    let snapshot = buffer.read(cx);
 3479                    old_selections
 3480                        .iter()
 3481                        .map(|s| {
 3482                            let anchor = snapshot.anchor_after(s.head());
 3483                            s.map(|_| anchor)
 3484                        })
 3485                        .collect::<Vec<_>>()
 3486                };
 3487                buffer.edit(
 3488                    old_selections
 3489                        .iter()
 3490                        .map(|s| (s.start..s.end, text.clone())),
 3491                    autoindent_mode,
 3492                    cx,
 3493                );
 3494                anchors
 3495            });
 3496
 3497            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3498                s.select_anchors(selection_anchors);
 3499            });
 3500
 3501            cx.notify();
 3502        });
 3503    }
 3504
 3505    fn trigger_completion_on_input(
 3506        &mut self,
 3507        text: &str,
 3508        trigger_in_words: bool,
 3509        window: &mut Window,
 3510        cx: &mut Context<Self>,
 3511    ) {
 3512        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3513            self.show_completions(
 3514                &ShowCompletions {
 3515                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3516                },
 3517                window,
 3518                cx,
 3519            );
 3520        } else {
 3521            self.hide_context_menu(window, cx);
 3522        }
 3523    }
 3524
 3525    fn is_completion_trigger(
 3526        &self,
 3527        text: &str,
 3528        trigger_in_words: bool,
 3529        cx: &mut Context<Self>,
 3530    ) -> bool {
 3531        let position = self.selections.newest_anchor().head();
 3532        let multibuffer = self.buffer.read(cx);
 3533        let Some(buffer) = position
 3534            .buffer_id
 3535            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3536        else {
 3537            return false;
 3538        };
 3539
 3540        if let Some(completion_provider) = &self.completion_provider {
 3541            completion_provider.is_completion_trigger(
 3542                &buffer,
 3543                position.text_anchor,
 3544                text,
 3545                trigger_in_words,
 3546                cx,
 3547            )
 3548        } else {
 3549            false
 3550        }
 3551    }
 3552
 3553    /// If any empty selections is touching the start of its innermost containing autoclose
 3554    /// region, expand it to select the brackets.
 3555    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3556        let selections = self.selections.all::<usize>(cx);
 3557        let buffer = self.buffer.read(cx).read(cx);
 3558        let new_selections = self
 3559            .selections_with_autoclose_regions(selections, &buffer)
 3560            .map(|(mut selection, region)| {
 3561                if !selection.is_empty() {
 3562                    return selection;
 3563                }
 3564
 3565                if let Some(region) = region {
 3566                    let mut range = region.range.to_offset(&buffer);
 3567                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3568                        range.start -= region.pair.start.len();
 3569                        if buffer.contains_str_at(range.start, &region.pair.start)
 3570                            && buffer.contains_str_at(range.end, &region.pair.end)
 3571                        {
 3572                            range.end += region.pair.end.len();
 3573                            selection.start = range.start;
 3574                            selection.end = range.end;
 3575
 3576                            return selection;
 3577                        }
 3578                    }
 3579                }
 3580
 3581                let always_treat_brackets_as_autoclosed = buffer
 3582                    .settings_at(selection.start, cx)
 3583                    .always_treat_brackets_as_autoclosed;
 3584
 3585                if !always_treat_brackets_as_autoclosed {
 3586                    return selection;
 3587                }
 3588
 3589                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3590                    for (pair, enabled) in scope.brackets() {
 3591                        if !enabled || !pair.close {
 3592                            continue;
 3593                        }
 3594
 3595                        if buffer.contains_str_at(selection.start, &pair.end) {
 3596                            let pair_start_len = pair.start.len();
 3597                            if buffer.contains_str_at(
 3598                                selection.start.saturating_sub(pair_start_len),
 3599                                &pair.start,
 3600                            ) {
 3601                                selection.start -= pair_start_len;
 3602                                selection.end += pair.end.len();
 3603
 3604                                return selection;
 3605                            }
 3606                        }
 3607                    }
 3608                }
 3609
 3610                selection
 3611            })
 3612            .collect();
 3613
 3614        drop(buffer);
 3615        self.change_selections(None, window, cx, |selections| {
 3616            selections.select(new_selections)
 3617        });
 3618    }
 3619
 3620    /// Iterate the given selections, and for each one, find the smallest surrounding
 3621    /// autoclose region. This uses the ordering of the selections and the autoclose
 3622    /// regions to avoid repeated comparisons.
 3623    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3624        &'a self,
 3625        selections: impl IntoIterator<Item = Selection<D>>,
 3626        buffer: &'a MultiBufferSnapshot,
 3627    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3628        let mut i = 0;
 3629        let mut regions = self.autoclose_regions.as_slice();
 3630        selections.into_iter().map(move |selection| {
 3631            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3632
 3633            let mut enclosing = None;
 3634            while let Some(pair_state) = regions.get(i) {
 3635                if pair_state.range.end.to_offset(buffer) < range.start {
 3636                    regions = &regions[i + 1..];
 3637                    i = 0;
 3638                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3639                    break;
 3640                } else {
 3641                    if pair_state.selection_id == selection.id {
 3642                        enclosing = Some(pair_state);
 3643                    }
 3644                    i += 1;
 3645                }
 3646            }
 3647
 3648            (selection, enclosing)
 3649        })
 3650    }
 3651
 3652    /// Remove any autoclose regions that no longer contain their selection.
 3653    fn invalidate_autoclose_regions(
 3654        &mut self,
 3655        mut selections: &[Selection<Anchor>],
 3656        buffer: &MultiBufferSnapshot,
 3657    ) {
 3658        self.autoclose_regions.retain(|state| {
 3659            let mut i = 0;
 3660            while let Some(selection) = selections.get(i) {
 3661                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3662                    selections = &selections[1..];
 3663                    continue;
 3664                }
 3665                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3666                    break;
 3667                }
 3668                if selection.id == state.selection_id {
 3669                    return true;
 3670                } else {
 3671                    i += 1;
 3672                }
 3673            }
 3674            false
 3675        });
 3676    }
 3677
 3678    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3679        let offset = position.to_offset(buffer);
 3680        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3681        if offset > word_range.start && kind == Some(CharKind::Word) {
 3682            Some(
 3683                buffer
 3684                    .text_for_range(word_range.start..offset)
 3685                    .collect::<String>(),
 3686            )
 3687        } else {
 3688            None
 3689        }
 3690    }
 3691
 3692    pub fn toggle_inlay_hints(
 3693        &mut self,
 3694        _: &ToggleInlayHints,
 3695        _: &mut Window,
 3696        cx: &mut Context<Self>,
 3697    ) {
 3698        self.refresh_inlay_hints(
 3699            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3700            cx,
 3701        );
 3702    }
 3703
 3704    pub fn inlay_hints_enabled(&self) -> bool {
 3705        self.inlay_hint_cache.enabled
 3706    }
 3707
 3708    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3709        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3710            return;
 3711        }
 3712
 3713        let reason_description = reason.description();
 3714        let ignore_debounce = matches!(
 3715            reason,
 3716            InlayHintRefreshReason::SettingsChange(_)
 3717                | InlayHintRefreshReason::Toggle(_)
 3718                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3719        );
 3720        let (invalidate_cache, required_languages) = match reason {
 3721            InlayHintRefreshReason::Toggle(enabled) => {
 3722                self.inlay_hint_cache.enabled = enabled;
 3723                if enabled {
 3724                    (InvalidationStrategy::RefreshRequested, None)
 3725                } else {
 3726                    self.inlay_hint_cache.clear();
 3727                    self.splice_inlays(
 3728                        &self
 3729                            .visible_inlay_hints(cx)
 3730                            .iter()
 3731                            .map(|inlay| inlay.id)
 3732                            .collect::<Vec<InlayId>>(),
 3733                        Vec::new(),
 3734                        cx,
 3735                    );
 3736                    return;
 3737                }
 3738            }
 3739            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3740                match self.inlay_hint_cache.update_settings(
 3741                    &self.buffer,
 3742                    new_settings,
 3743                    self.visible_inlay_hints(cx),
 3744                    cx,
 3745                ) {
 3746                    ControlFlow::Break(Some(InlaySplice {
 3747                        to_remove,
 3748                        to_insert,
 3749                    })) => {
 3750                        self.splice_inlays(&to_remove, to_insert, cx);
 3751                        return;
 3752                    }
 3753                    ControlFlow::Break(None) => return,
 3754                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3755                }
 3756            }
 3757            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3758                if let Some(InlaySplice {
 3759                    to_remove,
 3760                    to_insert,
 3761                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3762                {
 3763                    self.splice_inlays(&to_remove, to_insert, cx);
 3764                }
 3765                return;
 3766            }
 3767            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3768            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3769                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3770            }
 3771            InlayHintRefreshReason::RefreshRequested => {
 3772                (InvalidationStrategy::RefreshRequested, None)
 3773            }
 3774        };
 3775
 3776        if let Some(InlaySplice {
 3777            to_remove,
 3778            to_insert,
 3779        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3780            reason_description,
 3781            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3782            invalidate_cache,
 3783            ignore_debounce,
 3784            cx,
 3785        ) {
 3786            self.splice_inlays(&to_remove, to_insert, cx);
 3787        }
 3788    }
 3789
 3790    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3791        self.display_map
 3792            .read(cx)
 3793            .current_inlays()
 3794            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3795            .cloned()
 3796            .collect()
 3797    }
 3798
 3799    pub fn excerpts_for_inlay_hints_query(
 3800        &self,
 3801        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3802        cx: &mut Context<Editor>,
 3803    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3804        let Some(project) = self.project.as_ref() else {
 3805            return HashMap::default();
 3806        };
 3807        let project = project.read(cx);
 3808        let multi_buffer = self.buffer().read(cx);
 3809        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3810        let multi_buffer_visible_start = self
 3811            .scroll_manager
 3812            .anchor()
 3813            .anchor
 3814            .to_point(&multi_buffer_snapshot);
 3815        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3816            multi_buffer_visible_start
 3817                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3818            Bias::Left,
 3819        );
 3820        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3821        multi_buffer_snapshot
 3822            .range_to_buffer_ranges(multi_buffer_visible_range)
 3823            .into_iter()
 3824            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3825            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3826                let buffer_file = project::File::from_dyn(buffer.file())?;
 3827                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3828                let worktree_entry = buffer_worktree
 3829                    .read(cx)
 3830                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3831                if worktree_entry.is_ignored {
 3832                    return None;
 3833                }
 3834
 3835                let language = buffer.language()?;
 3836                if let Some(restrict_to_languages) = restrict_to_languages {
 3837                    if !restrict_to_languages.contains(language) {
 3838                        return None;
 3839                    }
 3840                }
 3841                Some((
 3842                    excerpt_id,
 3843                    (
 3844                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3845                        buffer.version().clone(),
 3846                        excerpt_visible_range,
 3847                    ),
 3848                ))
 3849            })
 3850            .collect()
 3851    }
 3852
 3853    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3854        TextLayoutDetails {
 3855            text_system: window.text_system().clone(),
 3856            editor_style: self.style.clone().unwrap(),
 3857            rem_size: window.rem_size(),
 3858            scroll_anchor: self.scroll_manager.anchor(),
 3859            visible_rows: self.visible_line_count(),
 3860            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3861        }
 3862    }
 3863
 3864    pub fn splice_inlays(
 3865        &self,
 3866        to_remove: &[InlayId],
 3867        to_insert: Vec<Inlay>,
 3868        cx: &mut Context<Self>,
 3869    ) {
 3870        self.display_map.update(cx, |display_map, cx| {
 3871            display_map.splice_inlays(to_remove, to_insert, cx)
 3872        });
 3873        cx.notify();
 3874    }
 3875
 3876    fn trigger_on_type_formatting(
 3877        &self,
 3878        input: String,
 3879        window: &mut Window,
 3880        cx: &mut Context<Self>,
 3881    ) -> Option<Task<Result<()>>> {
 3882        if input.len() != 1 {
 3883            return None;
 3884        }
 3885
 3886        let project = self.project.as_ref()?;
 3887        let position = self.selections.newest_anchor().head();
 3888        let (buffer, buffer_position) = self
 3889            .buffer
 3890            .read(cx)
 3891            .text_anchor_for_position(position, cx)?;
 3892
 3893        let settings = language_settings::language_settings(
 3894            buffer
 3895                .read(cx)
 3896                .language_at(buffer_position)
 3897                .map(|l| l.name()),
 3898            buffer.read(cx).file(),
 3899            cx,
 3900        );
 3901        if !settings.use_on_type_format {
 3902            return None;
 3903        }
 3904
 3905        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3906        // hence we do LSP request & edit on host side only — add formats to host's history.
 3907        let push_to_lsp_host_history = true;
 3908        // If this is not the host, append its history with new edits.
 3909        let push_to_client_history = project.read(cx).is_via_collab();
 3910
 3911        let on_type_formatting = project.update(cx, |project, cx| {
 3912            project.on_type_format(
 3913                buffer.clone(),
 3914                buffer_position,
 3915                input,
 3916                push_to_lsp_host_history,
 3917                cx,
 3918            )
 3919        });
 3920        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3921            if let Some(transaction) = on_type_formatting.await? {
 3922                if push_to_client_history {
 3923                    buffer
 3924                        .update(&mut cx, |buffer, _| {
 3925                            buffer.push_transaction(transaction, Instant::now());
 3926                        })
 3927                        .ok();
 3928                }
 3929                editor.update(&mut cx, |editor, cx| {
 3930                    editor.refresh_document_highlights(cx);
 3931                })?;
 3932            }
 3933            Ok(())
 3934        }))
 3935    }
 3936
 3937    pub fn show_completions(
 3938        &mut self,
 3939        options: &ShowCompletions,
 3940        window: &mut Window,
 3941        cx: &mut Context<Self>,
 3942    ) {
 3943        if self.pending_rename.is_some() {
 3944            return;
 3945        }
 3946
 3947        let Some(provider) = self.completion_provider.as_ref() else {
 3948            return;
 3949        };
 3950
 3951        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3952            return;
 3953        }
 3954
 3955        let position = self.selections.newest_anchor().head();
 3956        if position.diff_base_anchor.is_some() {
 3957            return;
 3958        }
 3959        let (buffer, buffer_position) =
 3960            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3961                output
 3962            } else {
 3963                return;
 3964            };
 3965        let show_completion_documentation = buffer
 3966            .read(cx)
 3967            .snapshot()
 3968            .settings_at(buffer_position, cx)
 3969            .show_completion_documentation;
 3970
 3971        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3972
 3973        let trigger_kind = match &options.trigger {
 3974            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3975                CompletionTriggerKind::TRIGGER_CHARACTER
 3976            }
 3977            _ => CompletionTriggerKind::INVOKED,
 3978        };
 3979        let completion_context = CompletionContext {
 3980            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3981                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3982                    Some(String::from(trigger))
 3983                } else {
 3984                    None
 3985                }
 3986            }),
 3987            trigger_kind,
 3988        };
 3989        let completions =
 3990            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3991        let sort_completions = provider.sort_completions();
 3992
 3993        let id = post_inc(&mut self.next_completion_id);
 3994        let task = cx.spawn_in(window, |editor, mut cx| {
 3995            async move {
 3996                editor.update(&mut cx, |this, _| {
 3997                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3998                })?;
 3999                let completions = completions.await.log_err();
 4000                let menu = if let Some(completions) = completions {
 4001                    let mut menu = CompletionsMenu::new(
 4002                        id,
 4003                        sort_completions,
 4004                        show_completion_documentation,
 4005                        position,
 4006                        buffer.clone(),
 4007                        completions.into(),
 4008                    );
 4009
 4010                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4011                        .await;
 4012
 4013                    menu.visible().then_some(menu)
 4014                } else {
 4015                    None
 4016                };
 4017
 4018                editor.update_in(&mut cx, |editor, window, cx| {
 4019                    match editor.context_menu.borrow().as_ref() {
 4020                        None => {}
 4021                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4022                            if prev_menu.id > id {
 4023                                return;
 4024                            }
 4025                        }
 4026                        _ => return,
 4027                    }
 4028
 4029                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4030                        let mut menu = menu.unwrap();
 4031                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4032
 4033                        *editor.context_menu.borrow_mut() =
 4034                            Some(CodeContextMenu::Completions(menu));
 4035
 4036                        if editor.show_edit_predictions_in_menu() {
 4037                            editor.update_visible_inline_completion(window, cx);
 4038                        } else {
 4039                            editor.discard_inline_completion(false, cx);
 4040                        }
 4041
 4042                        cx.notify();
 4043                    } else if editor.completion_tasks.len() <= 1 {
 4044                        // If there are no more completion tasks and the last menu was
 4045                        // empty, we should hide it.
 4046                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4047                        // If it was already hidden and we don't show inline
 4048                        // completions in the menu, we should also show the
 4049                        // inline-completion when available.
 4050                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4051                            editor.update_visible_inline_completion(window, cx);
 4052                        }
 4053                    }
 4054                })?;
 4055
 4056                Ok::<_, anyhow::Error>(())
 4057            }
 4058            .log_err()
 4059        });
 4060
 4061        self.completion_tasks.push((id, task));
 4062    }
 4063
 4064    pub fn confirm_completion(
 4065        &mut self,
 4066        action: &ConfirmCompletion,
 4067        window: &mut Window,
 4068        cx: &mut Context<Self>,
 4069    ) -> Option<Task<Result<()>>> {
 4070        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4071    }
 4072
 4073    pub fn compose_completion(
 4074        &mut self,
 4075        action: &ComposeCompletion,
 4076        window: &mut Window,
 4077        cx: &mut Context<Self>,
 4078    ) -> Option<Task<Result<()>>> {
 4079        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4080    }
 4081
 4082    fn do_completion(
 4083        &mut self,
 4084        item_ix: Option<usize>,
 4085        intent: CompletionIntent,
 4086        window: &mut Window,
 4087        cx: &mut Context<Editor>,
 4088    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4089        use language::ToOffset as _;
 4090
 4091        let completions_menu =
 4092            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4093                menu
 4094            } else {
 4095                return None;
 4096            };
 4097
 4098        let entries = completions_menu.entries.borrow();
 4099        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4100        if self.show_edit_predictions_in_menu() {
 4101            self.discard_inline_completion(true, cx);
 4102        }
 4103        let candidate_id = mat.candidate_id;
 4104        drop(entries);
 4105
 4106        let buffer_handle = completions_menu.buffer;
 4107        let completion = completions_menu
 4108            .completions
 4109            .borrow()
 4110            .get(candidate_id)?
 4111            .clone();
 4112        cx.stop_propagation();
 4113
 4114        let snippet;
 4115        let text;
 4116
 4117        if completion.is_snippet() {
 4118            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4119            text = snippet.as_ref().unwrap().text.clone();
 4120        } else {
 4121            snippet = None;
 4122            text = completion.new_text.clone();
 4123        };
 4124        let selections = self.selections.all::<usize>(cx);
 4125        let buffer = buffer_handle.read(cx);
 4126        let old_range = completion.old_range.to_offset(buffer);
 4127        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4128
 4129        let newest_selection = self.selections.newest_anchor();
 4130        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4131            return None;
 4132        }
 4133
 4134        let lookbehind = newest_selection
 4135            .start
 4136            .text_anchor
 4137            .to_offset(buffer)
 4138            .saturating_sub(old_range.start);
 4139        let lookahead = old_range
 4140            .end
 4141            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4142        let mut common_prefix_len = old_text
 4143            .bytes()
 4144            .zip(text.bytes())
 4145            .take_while(|(a, b)| a == b)
 4146            .count();
 4147
 4148        let snapshot = self.buffer.read(cx).snapshot(cx);
 4149        let mut range_to_replace: Option<Range<isize>> = None;
 4150        let mut ranges = Vec::new();
 4151        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4152        for selection in &selections {
 4153            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4154                let start = selection.start.saturating_sub(lookbehind);
 4155                let end = selection.end + lookahead;
 4156                if selection.id == newest_selection.id {
 4157                    range_to_replace = Some(
 4158                        ((start + common_prefix_len) as isize - selection.start as isize)
 4159                            ..(end as isize - selection.start as isize),
 4160                    );
 4161                }
 4162                ranges.push(start + common_prefix_len..end);
 4163            } else {
 4164                common_prefix_len = 0;
 4165                ranges.clear();
 4166                ranges.extend(selections.iter().map(|s| {
 4167                    if s.id == newest_selection.id {
 4168                        range_to_replace = Some(
 4169                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4170                                - selection.start as isize
 4171                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4172                                    - selection.start as isize,
 4173                        );
 4174                        old_range.clone()
 4175                    } else {
 4176                        s.start..s.end
 4177                    }
 4178                }));
 4179                break;
 4180            }
 4181            if !self.linked_edit_ranges.is_empty() {
 4182                let start_anchor = snapshot.anchor_before(selection.head());
 4183                let end_anchor = snapshot.anchor_after(selection.tail());
 4184                if let Some(ranges) = self
 4185                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4186                {
 4187                    for (buffer, edits) in ranges {
 4188                        linked_edits.entry(buffer.clone()).or_default().extend(
 4189                            edits
 4190                                .into_iter()
 4191                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4192                        );
 4193                    }
 4194                }
 4195            }
 4196        }
 4197        let text = &text[common_prefix_len..];
 4198
 4199        cx.emit(EditorEvent::InputHandled {
 4200            utf16_range_to_replace: range_to_replace,
 4201            text: text.into(),
 4202        });
 4203
 4204        self.transact(window, cx, |this, window, cx| {
 4205            if let Some(mut snippet) = snippet {
 4206                snippet.text = text.to_string();
 4207                for tabstop in snippet
 4208                    .tabstops
 4209                    .iter_mut()
 4210                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4211                {
 4212                    tabstop.start -= common_prefix_len as isize;
 4213                    tabstop.end -= common_prefix_len as isize;
 4214                }
 4215
 4216                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4217            } else {
 4218                this.buffer.update(cx, |buffer, cx| {
 4219                    buffer.edit(
 4220                        ranges.iter().map(|range| (range.clone(), text)),
 4221                        this.autoindent_mode.clone(),
 4222                        cx,
 4223                    );
 4224                });
 4225            }
 4226            for (buffer, edits) in linked_edits {
 4227                buffer.update(cx, |buffer, cx| {
 4228                    let snapshot = buffer.snapshot();
 4229                    let edits = edits
 4230                        .into_iter()
 4231                        .map(|(range, text)| {
 4232                            use text::ToPoint as TP;
 4233                            let end_point = TP::to_point(&range.end, &snapshot);
 4234                            let start_point = TP::to_point(&range.start, &snapshot);
 4235                            (start_point..end_point, text)
 4236                        })
 4237                        .sorted_by_key(|(range, _)| range.start)
 4238                        .collect::<Vec<_>>();
 4239                    buffer.edit(edits, None, cx);
 4240                })
 4241            }
 4242
 4243            this.refresh_inline_completion(true, false, window, cx);
 4244        });
 4245
 4246        let show_new_completions_on_confirm = completion
 4247            .confirm
 4248            .as_ref()
 4249            .map_or(false, |confirm| confirm(intent, window, cx));
 4250        if show_new_completions_on_confirm {
 4251            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4252        }
 4253
 4254        let provider = self.completion_provider.as_ref()?;
 4255        drop(completion);
 4256        let apply_edits = provider.apply_additional_edits_for_completion(
 4257            buffer_handle,
 4258            completions_menu.completions.clone(),
 4259            candidate_id,
 4260            true,
 4261            cx,
 4262        );
 4263
 4264        let editor_settings = EditorSettings::get_global(cx);
 4265        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4266            // After the code completion is finished, users often want to know what signatures are needed.
 4267            // so we should automatically call signature_help
 4268            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4269        }
 4270
 4271        Some(cx.foreground_executor().spawn(async move {
 4272            apply_edits.await?;
 4273            Ok(())
 4274        }))
 4275    }
 4276
 4277    pub fn toggle_code_actions(
 4278        &mut self,
 4279        action: &ToggleCodeActions,
 4280        window: &mut Window,
 4281        cx: &mut Context<Self>,
 4282    ) {
 4283        let mut context_menu = self.context_menu.borrow_mut();
 4284        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4285            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4286                // Toggle if we're selecting the same one
 4287                *context_menu = None;
 4288                cx.notify();
 4289                return;
 4290            } else {
 4291                // Otherwise, clear it and start a new one
 4292                *context_menu = None;
 4293                cx.notify();
 4294            }
 4295        }
 4296        drop(context_menu);
 4297        let snapshot = self.snapshot(window, cx);
 4298        let deployed_from_indicator = action.deployed_from_indicator;
 4299        let mut task = self.code_actions_task.take();
 4300        let action = action.clone();
 4301        cx.spawn_in(window, |editor, mut cx| async move {
 4302            while let Some(prev_task) = task {
 4303                prev_task.await.log_err();
 4304                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4305            }
 4306
 4307            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4308                if editor.focus_handle.is_focused(window) {
 4309                    let multibuffer_point = action
 4310                        .deployed_from_indicator
 4311                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4312                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4313                    let (buffer, buffer_row) = snapshot
 4314                        .buffer_snapshot
 4315                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4316                        .and_then(|(buffer_snapshot, range)| {
 4317                            editor
 4318                                .buffer
 4319                                .read(cx)
 4320                                .buffer(buffer_snapshot.remote_id())
 4321                                .map(|buffer| (buffer, range.start.row))
 4322                        })?;
 4323                    let (_, code_actions) = editor
 4324                        .available_code_actions
 4325                        .clone()
 4326                        .and_then(|(location, code_actions)| {
 4327                            let snapshot = location.buffer.read(cx).snapshot();
 4328                            let point_range = location.range.to_point(&snapshot);
 4329                            let point_range = point_range.start.row..=point_range.end.row;
 4330                            if point_range.contains(&buffer_row) {
 4331                                Some((location, code_actions))
 4332                            } else {
 4333                                None
 4334                            }
 4335                        })
 4336                        .unzip();
 4337                    let buffer_id = buffer.read(cx).remote_id();
 4338                    let tasks = editor
 4339                        .tasks
 4340                        .get(&(buffer_id, buffer_row))
 4341                        .map(|t| Arc::new(t.to_owned()));
 4342                    if tasks.is_none() && code_actions.is_none() {
 4343                        return None;
 4344                    }
 4345
 4346                    editor.completion_tasks.clear();
 4347                    editor.discard_inline_completion(false, cx);
 4348                    let task_context =
 4349                        tasks
 4350                            .as_ref()
 4351                            .zip(editor.project.clone())
 4352                            .map(|(tasks, project)| {
 4353                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4354                            });
 4355
 4356                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4357                        let task_context = match task_context {
 4358                            Some(task_context) => task_context.await,
 4359                            None => None,
 4360                        };
 4361                        let resolved_tasks =
 4362                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4363                                Rc::new(ResolvedTasks {
 4364                                    templates: tasks.resolve(&task_context).collect(),
 4365                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4366                                        multibuffer_point.row,
 4367                                        tasks.column,
 4368                                    )),
 4369                                })
 4370                            });
 4371                        let spawn_straight_away = resolved_tasks
 4372                            .as_ref()
 4373                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4374                            && code_actions
 4375                                .as_ref()
 4376                                .map_or(true, |actions| actions.is_empty());
 4377                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4378                            *editor.context_menu.borrow_mut() =
 4379                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4380                                    buffer,
 4381                                    actions: CodeActionContents {
 4382                                        tasks: resolved_tasks,
 4383                                        actions: code_actions,
 4384                                    },
 4385                                    selected_item: Default::default(),
 4386                                    scroll_handle: UniformListScrollHandle::default(),
 4387                                    deployed_from_indicator,
 4388                                }));
 4389                            if spawn_straight_away {
 4390                                if let Some(task) = editor.confirm_code_action(
 4391                                    &ConfirmCodeAction { item_ix: Some(0) },
 4392                                    window,
 4393                                    cx,
 4394                                ) {
 4395                                    cx.notify();
 4396                                    return task;
 4397                                }
 4398                            }
 4399                            cx.notify();
 4400                            Task::ready(Ok(()))
 4401                        }) {
 4402                            task.await
 4403                        } else {
 4404                            Ok(())
 4405                        }
 4406                    }))
 4407                } else {
 4408                    Some(Task::ready(Ok(())))
 4409                }
 4410            })?;
 4411            if let Some(task) = spawned_test_task {
 4412                task.await?;
 4413            }
 4414
 4415            Ok::<_, anyhow::Error>(())
 4416        })
 4417        .detach_and_log_err(cx);
 4418    }
 4419
 4420    pub fn confirm_code_action(
 4421        &mut self,
 4422        action: &ConfirmCodeAction,
 4423        window: &mut Window,
 4424        cx: &mut Context<Self>,
 4425    ) -> Option<Task<Result<()>>> {
 4426        let actions_menu =
 4427            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4428                menu
 4429            } else {
 4430                return None;
 4431            };
 4432        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4433        let action = actions_menu.actions.get(action_ix)?;
 4434        let title = action.label();
 4435        let buffer = actions_menu.buffer;
 4436        let workspace = self.workspace()?;
 4437
 4438        match action {
 4439            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4440                workspace.update(cx, |workspace, cx| {
 4441                    workspace::tasks::schedule_resolved_task(
 4442                        workspace,
 4443                        task_source_kind,
 4444                        resolved_task,
 4445                        false,
 4446                        cx,
 4447                    );
 4448
 4449                    Some(Task::ready(Ok(())))
 4450                })
 4451            }
 4452            CodeActionsItem::CodeAction {
 4453                excerpt_id,
 4454                action,
 4455                provider,
 4456            } => {
 4457                let apply_code_action =
 4458                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4459                let workspace = workspace.downgrade();
 4460                Some(cx.spawn_in(window, |editor, cx| async move {
 4461                    let project_transaction = apply_code_action.await?;
 4462                    Self::open_project_transaction(
 4463                        &editor,
 4464                        workspace,
 4465                        project_transaction,
 4466                        title,
 4467                        cx,
 4468                    )
 4469                    .await
 4470                }))
 4471            }
 4472        }
 4473    }
 4474
 4475    pub async fn open_project_transaction(
 4476        this: &WeakEntity<Editor>,
 4477        workspace: WeakEntity<Workspace>,
 4478        transaction: ProjectTransaction,
 4479        title: String,
 4480        mut cx: AsyncWindowContext,
 4481    ) -> Result<()> {
 4482        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4483        cx.update(|_, cx| {
 4484            entries.sort_unstable_by_key(|(buffer, _)| {
 4485                buffer.read(cx).file().map(|f| f.path().clone())
 4486            });
 4487        })?;
 4488
 4489        // If the project transaction's edits are all contained within this editor, then
 4490        // avoid opening a new editor to display them.
 4491
 4492        if let Some((buffer, transaction)) = entries.first() {
 4493            if entries.len() == 1 {
 4494                let excerpt = this.update(&mut cx, |editor, cx| {
 4495                    editor
 4496                        .buffer()
 4497                        .read(cx)
 4498                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4499                })?;
 4500                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4501                    if excerpted_buffer == *buffer {
 4502                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4503                            let excerpt_range = excerpt_range.to_offset(buffer);
 4504                            buffer
 4505                                .edited_ranges_for_transaction::<usize>(transaction)
 4506                                .all(|range| {
 4507                                    excerpt_range.start <= range.start
 4508                                        && excerpt_range.end >= range.end
 4509                                })
 4510                        })?;
 4511
 4512                        if all_edits_within_excerpt {
 4513                            return Ok(());
 4514                        }
 4515                    }
 4516                }
 4517            }
 4518        } else {
 4519            return Ok(());
 4520        }
 4521
 4522        let mut ranges_to_highlight = Vec::new();
 4523        let excerpt_buffer = cx.new(|cx| {
 4524            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4525            for (buffer_handle, transaction) in &entries {
 4526                let buffer = buffer_handle.read(cx);
 4527                ranges_to_highlight.extend(
 4528                    multibuffer.push_excerpts_with_context_lines(
 4529                        buffer_handle.clone(),
 4530                        buffer
 4531                            .edited_ranges_for_transaction::<usize>(transaction)
 4532                            .collect(),
 4533                        DEFAULT_MULTIBUFFER_CONTEXT,
 4534                        cx,
 4535                    ),
 4536                );
 4537            }
 4538            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4539            multibuffer
 4540        })?;
 4541
 4542        workspace.update_in(&mut cx, |workspace, window, cx| {
 4543            let project = workspace.project().clone();
 4544            let editor = cx
 4545                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4546            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4547            editor.update(cx, |editor, cx| {
 4548                editor.highlight_background::<Self>(
 4549                    &ranges_to_highlight,
 4550                    |theme| theme.editor_highlighted_line_background,
 4551                    cx,
 4552                );
 4553            });
 4554        })?;
 4555
 4556        Ok(())
 4557    }
 4558
 4559    pub fn clear_code_action_providers(&mut self) {
 4560        self.code_action_providers.clear();
 4561        self.available_code_actions.take();
 4562    }
 4563
 4564    pub fn add_code_action_provider(
 4565        &mut self,
 4566        provider: Rc<dyn CodeActionProvider>,
 4567        window: &mut Window,
 4568        cx: &mut Context<Self>,
 4569    ) {
 4570        if self
 4571            .code_action_providers
 4572            .iter()
 4573            .any(|existing_provider| existing_provider.id() == provider.id())
 4574        {
 4575            return;
 4576        }
 4577
 4578        self.code_action_providers.push(provider);
 4579        self.refresh_code_actions(window, cx);
 4580    }
 4581
 4582    pub fn remove_code_action_provider(
 4583        &mut self,
 4584        id: Arc<str>,
 4585        window: &mut Window,
 4586        cx: &mut Context<Self>,
 4587    ) {
 4588        self.code_action_providers
 4589            .retain(|provider| provider.id() != id);
 4590        self.refresh_code_actions(window, cx);
 4591    }
 4592
 4593    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4594        let buffer = self.buffer.read(cx);
 4595        let newest_selection = self.selections.newest_anchor().clone();
 4596        if newest_selection.head().diff_base_anchor.is_some() {
 4597            return None;
 4598        }
 4599        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4600        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4601        if start_buffer != end_buffer {
 4602            return None;
 4603        }
 4604
 4605        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4606            cx.background_executor()
 4607                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4608                .await;
 4609
 4610            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4611                let providers = this.code_action_providers.clone();
 4612                let tasks = this
 4613                    .code_action_providers
 4614                    .iter()
 4615                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4616                    .collect::<Vec<_>>();
 4617                (providers, tasks)
 4618            })?;
 4619
 4620            let mut actions = Vec::new();
 4621            for (provider, provider_actions) in
 4622                providers.into_iter().zip(future::join_all(tasks).await)
 4623            {
 4624                if let Some(provider_actions) = provider_actions.log_err() {
 4625                    actions.extend(provider_actions.into_iter().map(|action| {
 4626                        AvailableCodeAction {
 4627                            excerpt_id: newest_selection.start.excerpt_id,
 4628                            action,
 4629                            provider: provider.clone(),
 4630                        }
 4631                    }));
 4632                }
 4633            }
 4634
 4635            this.update(&mut cx, |this, cx| {
 4636                this.available_code_actions = if actions.is_empty() {
 4637                    None
 4638                } else {
 4639                    Some((
 4640                        Location {
 4641                            buffer: start_buffer,
 4642                            range: start..end,
 4643                        },
 4644                        actions.into(),
 4645                    ))
 4646                };
 4647                cx.notify();
 4648            })
 4649        }));
 4650        None
 4651    }
 4652
 4653    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4654        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4655            self.show_git_blame_inline = false;
 4656
 4657            self.show_git_blame_inline_delay_task =
 4658                Some(cx.spawn_in(window, |this, mut cx| async move {
 4659                    cx.background_executor().timer(delay).await;
 4660
 4661                    this.update(&mut cx, |this, cx| {
 4662                        this.show_git_blame_inline = true;
 4663                        cx.notify();
 4664                    })
 4665                    .log_err();
 4666                }));
 4667        }
 4668    }
 4669
 4670    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4671        if self.pending_rename.is_some() {
 4672            return None;
 4673        }
 4674
 4675        let provider = self.semantics_provider.clone()?;
 4676        let buffer = self.buffer.read(cx);
 4677        let newest_selection = self.selections.newest_anchor().clone();
 4678        let cursor_position = newest_selection.head();
 4679        let (cursor_buffer, cursor_buffer_position) =
 4680            buffer.text_anchor_for_position(cursor_position, cx)?;
 4681        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4682        if cursor_buffer != tail_buffer {
 4683            return None;
 4684        }
 4685        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4686        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4687            cx.background_executor()
 4688                .timer(Duration::from_millis(debounce))
 4689                .await;
 4690
 4691            let highlights = if let Some(highlights) = cx
 4692                .update(|cx| {
 4693                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4694                })
 4695                .ok()
 4696                .flatten()
 4697            {
 4698                highlights.await.log_err()
 4699            } else {
 4700                None
 4701            };
 4702
 4703            if let Some(highlights) = highlights {
 4704                this.update(&mut cx, |this, cx| {
 4705                    if this.pending_rename.is_some() {
 4706                        return;
 4707                    }
 4708
 4709                    let buffer_id = cursor_position.buffer_id;
 4710                    let buffer = this.buffer.read(cx);
 4711                    if !buffer
 4712                        .text_anchor_for_position(cursor_position, cx)
 4713                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4714                    {
 4715                        return;
 4716                    }
 4717
 4718                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4719                    let mut write_ranges = Vec::new();
 4720                    let mut read_ranges = Vec::new();
 4721                    for highlight in highlights {
 4722                        for (excerpt_id, excerpt_range) in
 4723                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4724                        {
 4725                            let start = highlight
 4726                                .range
 4727                                .start
 4728                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4729                            let end = highlight
 4730                                .range
 4731                                .end
 4732                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4733                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4734                                continue;
 4735                            }
 4736
 4737                            let range = Anchor {
 4738                                buffer_id,
 4739                                excerpt_id,
 4740                                text_anchor: start,
 4741                                diff_base_anchor: None,
 4742                            }..Anchor {
 4743                                buffer_id,
 4744                                excerpt_id,
 4745                                text_anchor: end,
 4746                                diff_base_anchor: None,
 4747                            };
 4748                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4749                                write_ranges.push(range);
 4750                            } else {
 4751                                read_ranges.push(range);
 4752                            }
 4753                        }
 4754                    }
 4755
 4756                    this.highlight_background::<DocumentHighlightRead>(
 4757                        &read_ranges,
 4758                        |theme| theme.editor_document_highlight_read_background,
 4759                        cx,
 4760                    );
 4761                    this.highlight_background::<DocumentHighlightWrite>(
 4762                        &write_ranges,
 4763                        |theme| theme.editor_document_highlight_write_background,
 4764                        cx,
 4765                    );
 4766                    cx.notify();
 4767                })
 4768                .log_err();
 4769            }
 4770        }));
 4771        None
 4772    }
 4773
 4774    pub fn refresh_selected_text_highlights(
 4775        &mut self,
 4776        window: &mut Window,
 4777        cx: &mut Context<Editor>,
 4778    ) {
 4779        self.selection_highlight_task.take();
 4780        if !EditorSettings::get_global(cx).selection_highlight {
 4781            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4782            return;
 4783        }
 4784        if self.selections.count() != 1 || self.selections.line_mode {
 4785            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4786            return;
 4787        }
 4788        let selection = self.selections.newest::<Point>(cx);
 4789        if selection.is_empty() || selection.start.row != selection.end.row {
 4790            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4791            return;
 4792        }
 4793        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4794        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4795            cx.background_executor()
 4796                .timer(Duration::from_millis(debounce))
 4797                .await;
 4798            let Some(matches_task) = editor
 4799                .read_with(&mut cx, |editor, cx| {
 4800                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4801                    cx.background_spawn(async move {
 4802                        let mut ranges = Vec::new();
 4803                        let buffer_ranges =
 4804                            vec![buffer.anchor_before(0)..buffer.anchor_after(buffer.len())];
 4805                        let query = buffer.text_for_range(selection.range()).collect::<String>();
 4806                        for range in buffer_ranges {
 4807                            for (search_buffer, search_range, excerpt_id) in
 4808                                buffer.range_to_buffer_ranges(range)
 4809                            {
 4810                                ranges.extend(
 4811                                    project::search::SearchQuery::text(
 4812                                        query.clone(),
 4813                                        false,
 4814                                        false,
 4815                                        false,
 4816                                        Default::default(),
 4817                                        Default::default(),
 4818                                        None,
 4819                                    )
 4820                                    .unwrap()
 4821                                    .search(search_buffer, Some(search_range.clone()))
 4822                                    .await
 4823                                    .into_iter()
 4824                                    .map(|match_range| {
 4825                                        let start = search_buffer
 4826                                            .anchor_after(search_range.start + match_range.start);
 4827                                        let end = search_buffer
 4828                                            .anchor_before(search_range.start + match_range.end);
 4829                                        Anchor::range_in_buffer(
 4830                                            excerpt_id,
 4831                                            search_buffer.remote_id(),
 4832                                            start..end,
 4833                                        )
 4834                                    }),
 4835                                );
 4836                            }
 4837                        }
 4838                        ranges
 4839                    })
 4840                })
 4841                .log_err()
 4842            else {
 4843                return;
 4844            };
 4845            let matches = matches_task.await;
 4846            editor
 4847                .update_in(&mut cx, |editor, _, cx| {
 4848                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4849                    if !matches.is_empty() {
 4850                        editor.highlight_background::<SelectedTextHighlight>(
 4851                            &matches,
 4852                            |theme| theme.editor_document_highlight_bracket_background,
 4853                            cx,
 4854                        )
 4855                    }
 4856                })
 4857                .log_err();
 4858        }));
 4859    }
 4860
 4861    pub fn refresh_inline_completion(
 4862        &mut self,
 4863        debounce: bool,
 4864        user_requested: bool,
 4865        window: &mut Window,
 4866        cx: &mut Context<Self>,
 4867    ) -> Option<()> {
 4868        let provider = self.edit_prediction_provider()?;
 4869        let cursor = self.selections.newest_anchor().head();
 4870        let (buffer, cursor_buffer_position) =
 4871            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4872
 4873        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4874            self.discard_inline_completion(false, cx);
 4875            return None;
 4876        }
 4877
 4878        if !user_requested
 4879            && (!self.should_show_edit_predictions()
 4880                || !self.is_focused(window)
 4881                || buffer.read(cx).is_empty())
 4882        {
 4883            self.discard_inline_completion(false, cx);
 4884            return None;
 4885        }
 4886
 4887        self.update_visible_inline_completion(window, cx);
 4888        provider.refresh(
 4889            self.project.clone(),
 4890            buffer,
 4891            cursor_buffer_position,
 4892            debounce,
 4893            cx,
 4894        );
 4895        Some(())
 4896    }
 4897
 4898    fn show_edit_predictions_in_menu(&self) -> bool {
 4899        match self.edit_prediction_settings {
 4900            EditPredictionSettings::Disabled => false,
 4901            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4902        }
 4903    }
 4904
 4905    pub fn edit_predictions_enabled(&self) -> bool {
 4906        match self.edit_prediction_settings {
 4907            EditPredictionSettings::Disabled => false,
 4908            EditPredictionSettings::Enabled { .. } => true,
 4909        }
 4910    }
 4911
 4912    fn edit_prediction_requires_modifier(&self) -> bool {
 4913        match self.edit_prediction_settings {
 4914            EditPredictionSettings::Disabled => false,
 4915            EditPredictionSettings::Enabled {
 4916                preview_requires_modifier,
 4917                ..
 4918            } => preview_requires_modifier,
 4919        }
 4920    }
 4921
 4922    fn edit_prediction_settings_at_position(
 4923        &self,
 4924        buffer: &Entity<Buffer>,
 4925        buffer_position: language::Anchor,
 4926        cx: &App,
 4927    ) -> EditPredictionSettings {
 4928        if self.mode != EditorMode::Full
 4929            || !self.show_inline_completions_override.unwrap_or(true)
 4930            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4931        {
 4932            return EditPredictionSettings::Disabled;
 4933        }
 4934
 4935        let buffer = buffer.read(cx);
 4936
 4937        let file = buffer.file();
 4938
 4939        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4940            return EditPredictionSettings::Disabled;
 4941        };
 4942
 4943        let by_provider = matches!(
 4944            self.menu_inline_completions_policy,
 4945            MenuInlineCompletionsPolicy::ByProvider
 4946        );
 4947
 4948        let show_in_menu = by_provider
 4949            && self
 4950                .edit_prediction_provider
 4951                .as_ref()
 4952                .map_or(false, |provider| {
 4953                    provider.provider.show_completions_in_menu()
 4954                });
 4955
 4956        let preview_requires_modifier =
 4957            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4958
 4959        EditPredictionSettings::Enabled {
 4960            show_in_menu,
 4961            preview_requires_modifier,
 4962        }
 4963    }
 4964
 4965    fn should_show_edit_predictions(&self) -> bool {
 4966        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4967    }
 4968
 4969    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4970        matches!(
 4971            self.edit_prediction_preview,
 4972            EditPredictionPreview::Active { .. }
 4973        )
 4974    }
 4975
 4976    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4977        let cursor = self.selections.newest_anchor().head();
 4978        if let Some((buffer, cursor_position)) =
 4979            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4980        {
 4981            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4982        } else {
 4983            false
 4984        }
 4985    }
 4986
 4987    fn inline_completions_enabled_in_buffer(
 4988        &self,
 4989        buffer: &Entity<Buffer>,
 4990        buffer_position: language::Anchor,
 4991        cx: &App,
 4992    ) -> bool {
 4993        maybe!({
 4994            let provider = self.edit_prediction_provider()?;
 4995            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4996                return Some(false);
 4997            }
 4998            let buffer = buffer.read(cx);
 4999            let Some(file) = buffer.file() else {
 5000                return Some(true);
 5001            };
 5002            let settings = all_language_settings(Some(file), cx);
 5003            Some(settings.inline_completions_enabled_for_path(file.path()))
 5004        })
 5005        .unwrap_or(false)
 5006    }
 5007
 5008    fn cycle_inline_completion(
 5009        &mut self,
 5010        direction: Direction,
 5011        window: &mut Window,
 5012        cx: &mut Context<Self>,
 5013    ) -> Option<()> {
 5014        let provider = self.edit_prediction_provider()?;
 5015        let cursor = self.selections.newest_anchor().head();
 5016        let (buffer, cursor_buffer_position) =
 5017            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5018        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5019            return None;
 5020        }
 5021
 5022        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5023        self.update_visible_inline_completion(window, cx);
 5024
 5025        Some(())
 5026    }
 5027
 5028    pub fn show_inline_completion(
 5029        &mut self,
 5030        _: &ShowEditPrediction,
 5031        window: &mut Window,
 5032        cx: &mut Context<Self>,
 5033    ) {
 5034        if !self.has_active_inline_completion() {
 5035            self.refresh_inline_completion(false, true, window, cx);
 5036            return;
 5037        }
 5038
 5039        self.update_visible_inline_completion(window, cx);
 5040    }
 5041
 5042    pub fn display_cursor_names(
 5043        &mut self,
 5044        _: &DisplayCursorNames,
 5045        window: &mut Window,
 5046        cx: &mut Context<Self>,
 5047    ) {
 5048        self.show_cursor_names(window, cx);
 5049    }
 5050
 5051    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5052        self.show_cursor_names = true;
 5053        cx.notify();
 5054        cx.spawn_in(window, |this, mut cx| async move {
 5055            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5056            this.update(&mut cx, |this, cx| {
 5057                this.show_cursor_names = false;
 5058                cx.notify()
 5059            })
 5060            .ok()
 5061        })
 5062        .detach();
 5063    }
 5064
 5065    pub fn next_edit_prediction(
 5066        &mut self,
 5067        _: &NextEditPrediction,
 5068        window: &mut Window,
 5069        cx: &mut Context<Self>,
 5070    ) {
 5071        if self.has_active_inline_completion() {
 5072            self.cycle_inline_completion(Direction::Next, window, cx);
 5073        } else {
 5074            let is_copilot_disabled = self
 5075                .refresh_inline_completion(false, true, window, cx)
 5076                .is_none();
 5077            if is_copilot_disabled {
 5078                cx.propagate();
 5079            }
 5080        }
 5081    }
 5082
 5083    pub fn previous_edit_prediction(
 5084        &mut self,
 5085        _: &PreviousEditPrediction,
 5086        window: &mut Window,
 5087        cx: &mut Context<Self>,
 5088    ) {
 5089        if self.has_active_inline_completion() {
 5090            self.cycle_inline_completion(Direction::Prev, window, cx);
 5091        } else {
 5092            let is_copilot_disabled = self
 5093                .refresh_inline_completion(false, true, window, cx)
 5094                .is_none();
 5095            if is_copilot_disabled {
 5096                cx.propagate();
 5097            }
 5098        }
 5099    }
 5100
 5101    pub fn accept_edit_prediction(
 5102        &mut self,
 5103        _: &AcceptEditPrediction,
 5104        window: &mut Window,
 5105        cx: &mut Context<Self>,
 5106    ) {
 5107        if self.show_edit_predictions_in_menu() {
 5108            self.hide_context_menu(window, cx);
 5109        }
 5110
 5111        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5112            return;
 5113        };
 5114
 5115        self.report_inline_completion_event(
 5116            active_inline_completion.completion_id.clone(),
 5117            true,
 5118            cx,
 5119        );
 5120
 5121        match &active_inline_completion.completion {
 5122            InlineCompletion::Move { target, .. } => {
 5123                let target = *target;
 5124
 5125                if let Some(position_map) = &self.last_position_map {
 5126                    if position_map
 5127                        .visible_row_range
 5128                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5129                        || !self.edit_prediction_requires_modifier()
 5130                    {
 5131                        self.unfold_ranges(&[target..target], true, false, cx);
 5132                        // Note that this is also done in vim's handler of the Tab action.
 5133                        self.change_selections(
 5134                            Some(Autoscroll::newest()),
 5135                            window,
 5136                            cx,
 5137                            |selections| {
 5138                                selections.select_anchor_ranges([target..target]);
 5139                            },
 5140                        );
 5141                        self.clear_row_highlights::<EditPredictionPreview>();
 5142
 5143                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5144                            previous_scroll_position: None,
 5145                        };
 5146                    } else {
 5147                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5148                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5149                        };
 5150                        self.highlight_rows::<EditPredictionPreview>(
 5151                            target..target,
 5152                            cx.theme().colors().editor_highlighted_line_background,
 5153                            true,
 5154                            cx,
 5155                        );
 5156                        self.request_autoscroll(Autoscroll::fit(), cx);
 5157                    }
 5158                }
 5159            }
 5160            InlineCompletion::Edit { edits, .. } => {
 5161                if let Some(provider) = self.edit_prediction_provider() {
 5162                    provider.accept(cx);
 5163                }
 5164
 5165                let snapshot = self.buffer.read(cx).snapshot(cx);
 5166                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5167
 5168                self.buffer.update(cx, |buffer, cx| {
 5169                    buffer.edit(edits.iter().cloned(), None, cx)
 5170                });
 5171
 5172                self.change_selections(None, window, cx, |s| {
 5173                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5174                });
 5175
 5176                self.update_visible_inline_completion(window, cx);
 5177                if self.active_inline_completion.is_none() {
 5178                    self.refresh_inline_completion(true, true, window, cx);
 5179                }
 5180
 5181                cx.notify();
 5182            }
 5183        }
 5184
 5185        self.edit_prediction_requires_modifier_in_leading_space = false;
 5186    }
 5187
 5188    pub fn accept_partial_inline_completion(
 5189        &mut self,
 5190        _: &AcceptPartialEditPrediction,
 5191        window: &mut Window,
 5192        cx: &mut Context<Self>,
 5193    ) {
 5194        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5195            return;
 5196        };
 5197        if self.selections.count() != 1 {
 5198            return;
 5199        }
 5200
 5201        self.report_inline_completion_event(
 5202            active_inline_completion.completion_id.clone(),
 5203            true,
 5204            cx,
 5205        );
 5206
 5207        match &active_inline_completion.completion {
 5208            InlineCompletion::Move { target, .. } => {
 5209                let target = *target;
 5210                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5211                    selections.select_anchor_ranges([target..target]);
 5212                });
 5213            }
 5214            InlineCompletion::Edit { edits, .. } => {
 5215                // Find an insertion that starts at the cursor position.
 5216                let snapshot = self.buffer.read(cx).snapshot(cx);
 5217                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5218                let insertion = edits.iter().find_map(|(range, text)| {
 5219                    let range = range.to_offset(&snapshot);
 5220                    if range.is_empty() && range.start == cursor_offset {
 5221                        Some(text)
 5222                    } else {
 5223                        None
 5224                    }
 5225                });
 5226
 5227                if let Some(text) = insertion {
 5228                    let mut partial_completion = text
 5229                        .chars()
 5230                        .by_ref()
 5231                        .take_while(|c| c.is_alphabetic())
 5232                        .collect::<String>();
 5233                    if partial_completion.is_empty() {
 5234                        partial_completion = text
 5235                            .chars()
 5236                            .by_ref()
 5237                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5238                            .collect::<String>();
 5239                    }
 5240
 5241                    cx.emit(EditorEvent::InputHandled {
 5242                        utf16_range_to_replace: None,
 5243                        text: partial_completion.clone().into(),
 5244                    });
 5245
 5246                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5247
 5248                    self.refresh_inline_completion(true, true, window, cx);
 5249                    cx.notify();
 5250                } else {
 5251                    self.accept_edit_prediction(&Default::default(), window, cx);
 5252                }
 5253            }
 5254        }
 5255    }
 5256
 5257    fn discard_inline_completion(
 5258        &mut self,
 5259        should_report_inline_completion_event: bool,
 5260        cx: &mut Context<Self>,
 5261    ) -> bool {
 5262        if should_report_inline_completion_event {
 5263            let completion_id = self
 5264                .active_inline_completion
 5265                .as_ref()
 5266                .and_then(|active_completion| active_completion.completion_id.clone());
 5267
 5268            self.report_inline_completion_event(completion_id, false, cx);
 5269        }
 5270
 5271        if let Some(provider) = self.edit_prediction_provider() {
 5272            provider.discard(cx);
 5273        }
 5274
 5275        self.take_active_inline_completion(cx)
 5276    }
 5277
 5278    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5279        let Some(provider) = self.edit_prediction_provider() else {
 5280            return;
 5281        };
 5282
 5283        let Some((_, buffer, _)) = self
 5284            .buffer
 5285            .read(cx)
 5286            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5287        else {
 5288            return;
 5289        };
 5290
 5291        let extension = buffer
 5292            .read(cx)
 5293            .file()
 5294            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5295
 5296        let event_type = match accepted {
 5297            true => "Edit Prediction Accepted",
 5298            false => "Edit Prediction Discarded",
 5299        };
 5300        telemetry::event!(
 5301            event_type,
 5302            provider = provider.name(),
 5303            prediction_id = id,
 5304            suggestion_accepted = accepted,
 5305            file_extension = extension,
 5306        );
 5307    }
 5308
 5309    pub fn has_active_inline_completion(&self) -> bool {
 5310        self.active_inline_completion.is_some()
 5311    }
 5312
 5313    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5314        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5315            return false;
 5316        };
 5317
 5318        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5319        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5320        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5321        true
 5322    }
 5323
 5324    /// Returns true when we're displaying the edit prediction popover below the cursor
 5325    /// like we are not previewing and the LSP autocomplete menu is visible
 5326    /// or we are in `when_holding_modifier` mode.
 5327    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5328        if self.edit_prediction_preview_is_active()
 5329            || !self.show_edit_predictions_in_menu()
 5330            || !self.edit_predictions_enabled()
 5331        {
 5332            return false;
 5333        }
 5334
 5335        if self.has_visible_completions_menu() {
 5336            return true;
 5337        }
 5338
 5339        has_completion && self.edit_prediction_requires_modifier()
 5340    }
 5341
 5342    fn handle_modifiers_changed(
 5343        &mut self,
 5344        modifiers: Modifiers,
 5345        position_map: &PositionMap,
 5346        window: &mut Window,
 5347        cx: &mut Context<Self>,
 5348    ) {
 5349        if self.show_edit_predictions_in_menu() {
 5350            self.update_edit_prediction_preview(&modifiers, window, cx);
 5351        }
 5352
 5353        self.update_selection_mode(&modifiers, position_map, window, cx);
 5354
 5355        let mouse_position = window.mouse_position();
 5356        if !position_map.text_hitbox.is_hovered(window) {
 5357            return;
 5358        }
 5359
 5360        self.update_hovered_link(
 5361            position_map.point_for_position(mouse_position),
 5362            &position_map.snapshot,
 5363            modifiers,
 5364            window,
 5365            cx,
 5366        )
 5367    }
 5368
 5369    fn update_selection_mode(
 5370        &mut self,
 5371        modifiers: &Modifiers,
 5372        position_map: &PositionMap,
 5373        window: &mut Window,
 5374        cx: &mut Context<Self>,
 5375    ) {
 5376        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5377            return;
 5378        }
 5379
 5380        let mouse_position = window.mouse_position();
 5381        let point_for_position = position_map.point_for_position(mouse_position);
 5382        let position = point_for_position.previous_valid;
 5383
 5384        self.select(
 5385            SelectPhase::BeginColumnar {
 5386                position,
 5387                reset: false,
 5388                goal_column: point_for_position.exact_unclipped.column(),
 5389            },
 5390            window,
 5391            cx,
 5392        );
 5393    }
 5394
 5395    fn update_edit_prediction_preview(
 5396        &mut self,
 5397        modifiers: &Modifiers,
 5398        window: &mut Window,
 5399        cx: &mut Context<Self>,
 5400    ) {
 5401        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5402        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5403            return;
 5404        };
 5405
 5406        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5407            if matches!(
 5408                self.edit_prediction_preview,
 5409                EditPredictionPreview::Inactive
 5410            ) {
 5411                self.edit_prediction_preview = EditPredictionPreview::Active {
 5412                    previous_scroll_position: None,
 5413                };
 5414
 5415                self.update_visible_inline_completion(window, cx);
 5416                cx.notify();
 5417            }
 5418        } else if let EditPredictionPreview::Active {
 5419            previous_scroll_position,
 5420        } = self.edit_prediction_preview
 5421        {
 5422            if let (Some(previous_scroll_position), Some(position_map)) =
 5423                (previous_scroll_position, self.last_position_map.as_ref())
 5424            {
 5425                self.set_scroll_position(
 5426                    previous_scroll_position
 5427                        .scroll_position(&position_map.snapshot.display_snapshot),
 5428                    window,
 5429                    cx,
 5430                );
 5431            }
 5432
 5433            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5434            self.clear_row_highlights::<EditPredictionPreview>();
 5435            self.update_visible_inline_completion(window, cx);
 5436            cx.notify();
 5437        }
 5438    }
 5439
 5440    fn update_visible_inline_completion(
 5441        &mut self,
 5442        _window: &mut Window,
 5443        cx: &mut Context<Self>,
 5444    ) -> Option<()> {
 5445        let selection = self.selections.newest_anchor();
 5446        let cursor = selection.head();
 5447        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5448        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5449        let excerpt_id = cursor.excerpt_id;
 5450
 5451        let show_in_menu = self.show_edit_predictions_in_menu();
 5452        let completions_menu_has_precedence = !show_in_menu
 5453            && (self.context_menu.borrow().is_some()
 5454                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5455
 5456        if completions_menu_has_precedence
 5457            || !offset_selection.is_empty()
 5458            || self
 5459                .active_inline_completion
 5460                .as_ref()
 5461                .map_or(false, |completion| {
 5462                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5463                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5464                    !invalidation_range.contains(&offset_selection.head())
 5465                })
 5466        {
 5467            self.discard_inline_completion(false, cx);
 5468            return None;
 5469        }
 5470
 5471        self.take_active_inline_completion(cx);
 5472        let Some(provider) = self.edit_prediction_provider() else {
 5473            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5474            return None;
 5475        };
 5476
 5477        let (buffer, cursor_buffer_position) =
 5478            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5479
 5480        self.edit_prediction_settings =
 5481            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5482
 5483        self.edit_prediction_cursor_on_leading_whitespace =
 5484            multibuffer.is_line_whitespace_upto(cursor);
 5485
 5486        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5487        let edits = inline_completion
 5488            .edits
 5489            .into_iter()
 5490            .flat_map(|(range, new_text)| {
 5491                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5492                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5493                Some((start..end, new_text))
 5494            })
 5495            .collect::<Vec<_>>();
 5496        if edits.is_empty() {
 5497            return None;
 5498        }
 5499
 5500        let first_edit_start = edits.first().unwrap().0.start;
 5501        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5502        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5503
 5504        let last_edit_end = edits.last().unwrap().0.end;
 5505        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5506        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5507
 5508        let cursor_row = cursor.to_point(&multibuffer).row;
 5509
 5510        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5511
 5512        let mut inlay_ids = Vec::new();
 5513        let invalidation_row_range;
 5514        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5515            Some(cursor_row..edit_end_row)
 5516        } else if cursor_row > edit_end_row {
 5517            Some(edit_start_row..cursor_row)
 5518        } else {
 5519            None
 5520        };
 5521        let is_move =
 5522            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5523        let completion = if is_move {
 5524            invalidation_row_range =
 5525                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5526            let target = first_edit_start;
 5527            InlineCompletion::Move { target, snapshot }
 5528        } else {
 5529            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5530                && !self.inline_completions_hidden_for_vim_mode;
 5531
 5532            if show_completions_in_buffer {
 5533                if edits
 5534                    .iter()
 5535                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5536                {
 5537                    let mut inlays = Vec::new();
 5538                    for (range, new_text) in &edits {
 5539                        let inlay = Inlay::inline_completion(
 5540                            post_inc(&mut self.next_inlay_id),
 5541                            range.start,
 5542                            new_text.as_str(),
 5543                        );
 5544                        inlay_ids.push(inlay.id);
 5545                        inlays.push(inlay);
 5546                    }
 5547
 5548                    self.splice_inlays(&[], inlays, cx);
 5549                } else {
 5550                    let background_color = cx.theme().status().deleted_background;
 5551                    self.highlight_text::<InlineCompletionHighlight>(
 5552                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5553                        HighlightStyle {
 5554                            background_color: Some(background_color),
 5555                            ..Default::default()
 5556                        },
 5557                        cx,
 5558                    );
 5559                }
 5560            }
 5561
 5562            invalidation_row_range = edit_start_row..edit_end_row;
 5563
 5564            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5565                if provider.show_tab_accept_marker() {
 5566                    EditDisplayMode::TabAccept
 5567                } else {
 5568                    EditDisplayMode::Inline
 5569                }
 5570            } else {
 5571                EditDisplayMode::DiffPopover
 5572            };
 5573
 5574            InlineCompletion::Edit {
 5575                edits,
 5576                edit_preview: inline_completion.edit_preview,
 5577                display_mode,
 5578                snapshot,
 5579            }
 5580        };
 5581
 5582        let invalidation_range = multibuffer
 5583            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5584            ..multibuffer.anchor_after(Point::new(
 5585                invalidation_row_range.end,
 5586                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5587            ));
 5588
 5589        self.stale_inline_completion_in_menu = None;
 5590        self.active_inline_completion = Some(InlineCompletionState {
 5591            inlay_ids,
 5592            completion,
 5593            completion_id: inline_completion.id,
 5594            invalidation_range,
 5595        });
 5596
 5597        cx.notify();
 5598
 5599        Some(())
 5600    }
 5601
 5602    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5603        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5604    }
 5605
 5606    fn render_code_actions_indicator(
 5607        &self,
 5608        _style: &EditorStyle,
 5609        row: DisplayRow,
 5610        is_active: bool,
 5611        cx: &mut Context<Self>,
 5612    ) -> Option<IconButton> {
 5613        if self.available_code_actions.is_some() {
 5614            Some(
 5615                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5616                    .shape(ui::IconButtonShape::Square)
 5617                    .icon_size(IconSize::XSmall)
 5618                    .icon_color(Color::Muted)
 5619                    .toggle_state(is_active)
 5620                    .tooltip({
 5621                        let focus_handle = self.focus_handle.clone();
 5622                        move |window, cx| {
 5623                            Tooltip::for_action_in(
 5624                                "Toggle Code Actions",
 5625                                &ToggleCodeActions {
 5626                                    deployed_from_indicator: None,
 5627                                },
 5628                                &focus_handle,
 5629                                window,
 5630                                cx,
 5631                            )
 5632                        }
 5633                    })
 5634                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5635                        window.focus(&editor.focus_handle(cx));
 5636                        editor.toggle_code_actions(
 5637                            &ToggleCodeActions {
 5638                                deployed_from_indicator: Some(row),
 5639                            },
 5640                            window,
 5641                            cx,
 5642                        );
 5643                    })),
 5644            )
 5645        } else {
 5646            None
 5647        }
 5648    }
 5649
 5650    fn clear_tasks(&mut self) {
 5651        self.tasks.clear()
 5652    }
 5653
 5654    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5655        if self.tasks.insert(key, value).is_some() {
 5656            // This case should hopefully be rare, but just in case...
 5657            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5658        }
 5659    }
 5660
 5661    fn build_tasks_context(
 5662        project: &Entity<Project>,
 5663        buffer: &Entity<Buffer>,
 5664        buffer_row: u32,
 5665        tasks: &Arc<RunnableTasks>,
 5666        cx: &mut Context<Self>,
 5667    ) -> Task<Option<task::TaskContext>> {
 5668        let position = Point::new(buffer_row, tasks.column);
 5669        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5670        let location = Location {
 5671            buffer: buffer.clone(),
 5672            range: range_start..range_start,
 5673        };
 5674        // Fill in the environmental variables from the tree-sitter captures
 5675        let mut captured_task_variables = TaskVariables::default();
 5676        for (capture_name, value) in tasks.extra_variables.clone() {
 5677            captured_task_variables.insert(
 5678                task::VariableName::Custom(capture_name.into()),
 5679                value.clone(),
 5680            );
 5681        }
 5682        project.update(cx, |project, cx| {
 5683            project.task_store().update(cx, |task_store, cx| {
 5684                task_store.task_context_for_location(captured_task_variables, location, cx)
 5685            })
 5686        })
 5687    }
 5688
 5689    pub fn spawn_nearest_task(
 5690        &mut self,
 5691        action: &SpawnNearestTask,
 5692        window: &mut Window,
 5693        cx: &mut Context<Self>,
 5694    ) {
 5695        let Some((workspace, _)) = self.workspace.clone() else {
 5696            return;
 5697        };
 5698        let Some(project) = self.project.clone() else {
 5699            return;
 5700        };
 5701
 5702        // Try to find a closest, enclosing node using tree-sitter that has a
 5703        // task
 5704        let Some((buffer, buffer_row, tasks)) = self
 5705            .find_enclosing_node_task(cx)
 5706            // Or find the task that's closest in row-distance.
 5707            .or_else(|| self.find_closest_task(cx))
 5708        else {
 5709            return;
 5710        };
 5711
 5712        let reveal_strategy = action.reveal;
 5713        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5714        cx.spawn_in(window, |_, mut cx| async move {
 5715            let context = task_context.await?;
 5716            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5717
 5718            let resolved = resolved_task.resolved.as_mut()?;
 5719            resolved.reveal = reveal_strategy;
 5720
 5721            workspace
 5722                .update(&mut cx, |workspace, cx| {
 5723                    workspace::tasks::schedule_resolved_task(
 5724                        workspace,
 5725                        task_source_kind,
 5726                        resolved_task,
 5727                        false,
 5728                        cx,
 5729                    );
 5730                })
 5731                .ok()
 5732        })
 5733        .detach();
 5734    }
 5735
 5736    fn find_closest_task(
 5737        &mut self,
 5738        cx: &mut Context<Self>,
 5739    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5740        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5741
 5742        let ((buffer_id, row), tasks) = self
 5743            .tasks
 5744            .iter()
 5745            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5746
 5747        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5748        let tasks = Arc::new(tasks.to_owned());
 5749        Some((buffer, *row, tasks))
 5750    }
 5751
 5752    fn find_enclosing_node_task(
 5753        &mut self,
 5754        cx: &mut Context<Self>,
 5755    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5756        let snapshot = self.buffer.read(cx).snapshot(cx);
 5757        let offset = self.selections.newest::<usize>(cx).head();
 5758        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5759        let buffer_id = excerpt.buffer().remote_id();
 5760
 5761        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5762        let mut cursor = layer.node().walk();
 5763
 5764        while cursor.goto_first_child_for_byte(offset).is_some() {
 5765            if cursor.node().end_byte() == offset {
 5766                cursor.goto_next_sibling();
 5767            }
 5768        }
 5769
 5770        // Ascend to the smallest ancestor that contains the range and has a task.
 5771        loop {
 5772            let node = cursor.node();
 5773            let node_range = node.byte_range();
 5774            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5775
 5776            // Check if this node contains our offset
 5777            if node_range.start <= offset && node_range.end >= offset {
 5778                // If it contains offset, check for task
 5779                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5780                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5781                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5782                }
 5783            }
 5784
 5785            if !cursor.goto_parent() {
 5786                break;
 5787            }
 5788        }
 5789        None
 5790    }
 5791
 5792    fn render_run_indicator(
 5793        &self,
 5794        _style: &EditorStyle,
 5795        is_active: bool,
 5796        row: DisplayRow,
 5797        cx: &mut Context<Self>,
 5798    ) -> IconButton {
 5799        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5800            .shape(ui::IconButtonShape::Square)
 5801            .icon_size(IconSize::XSmall)
 5802            .icon_color(Color::Muted)
 5803            .toggle_state(is_active)
 5804            .on_click(cx.listener(move |editor, _e, window, cx| {
 5805                window.focus(&editor.focus_handle(cx));
 5806                editor.toggle_code_actions(
 5807                    &ToggleCodeActions {
 5808                        deployed_from_indicator: Some(row),
 5809                    },
 5810                    window,
 5811                    cx,
 5812                );
 5813            }))
 5814    }
 5815
 5816    pub fn context_menu_visible(&self) -> bool {
 5817        !self.edit_prediction_preview_is_active()
 5818            && self
 5819                .context_menu
 5820                .borrow()
 5821                .as_ref()
 5822                .map_or(false, |menu| menu.visible())
 5823    }
 5824
 5825    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5826        self.context_menu
 5827            .borrow()
 5828            .as_ref()
 5829            .map(|menu| menu.origin())
 5830    }
 5831
 5832    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5833        px(30.)
 5834    }
 5835
 5836    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5837        if self.read_only(cx) {
 5838            cx.theme().players().read_only()
 5839        } else {
 5840            self.style.as_ref().unwrap().local_player
 5841        }
 5842    }
 5843
 5844    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5845        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5846        let accept_keystroke = accept_binding.keystroke()?;
 5847
 5848        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5849
 5850        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5851            Color::Accent
 5852        } else {
 5853            Color::Muted
 5854        };
 5855
 5856        h_flex()
 5857            .px_0p5()
 5858            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5859            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5860            .text_size(TextSize::XSmall.rems(cx))
 5861            .child(h_flex().children(ui::render_modifiers(
 5862                &accept_keystroke.modifiers,
 5863                PlatformStyle::platform(),
 5864                Some(modifiers_color),
 5865                Some(IconSize::XSmall.rems().into()),
 5866                true,
 5867            )))
 5868            .when(is_platform_style_mac, |parent| {
 5869                parent.child(accept_keystroke.key.clone())
 5870            })
 5871            .when(!is_platform_style_mac, |parent| {
 5872                parent.child(
 5873                    Key::new(
 5874                        util::capitalize(&accept_keystroke.key),
 5875                        Some(Color::Default),
 5876                    )
 5877                    .size(Some(IconSize::XSmall.rems().into())),
 5878                )
 5879            })
 5880            .into()
 5881    }
 5882
 5883    fn render_edit_prediction_line_popover(
 5884        &self,
 5885        label: impl Into<SharedString>,
 5886        icon: Option<IconName>,
 5887        window: &mut Window,
 5888        cx: &App,
 5889    ) -> Option<Div> {
 5890        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5891
 5892        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5893
 5894        let result = h_flex()
 5895            .gap_1()
 5896            .border_1()
 5897            .rounded_lg()
 5898            .shadow_sm()
 5899            .bg(bg_color)
 5900            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5901            .py_0p5()
 5902            .pl_1()
 5903            .pr(padding_right)
 5904            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5905            .child(Label::new(label).size(LabelSize::Small))
 5906            .when_some(icon, |element, icon| {
 5907                element.child(
 5908                    div()
 5909                        .mt(px(1.5))
 5910                        .child(Icon::new(icon).size(IconSize::Small)),
 5911                )
 5912            });
 5913
 5914        Some(result)
 5915    }
 5916
 5917    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5918        let accent_color = cx.theme().colors().text_accent;
 5919        let editor_bg_color = cx.theme().colors().editor_background;
 5920        editor_bg_color.blend(accent_color.opacity(0.1))
 5921    }
 5922
 5923    fn render_edit_prediction_cursor_popover(
 5924        &self,
 5925        min_width: Pixels,
 5926        max_width: Pixels,
 5927        cursor_point: Point,
 5928        style: &EditorStyle,
 5929        accept_keystroke: Option<&gpui::Keystroke>,
 5930        _window: &Window,
 5931        cx: &mut Context<Editor>,
 5932    ) -> Option<AnyElement> {
 5933        let provider = self.edit_prediction_provider.as_ref()?;
 5934
 5935        if provider.provider.needs_terms_acceptance(cx) {
 5936            return Some(
 5937                h_flex()
 5938                    .min_w(min_width)
 5939                    .flex_1()
 5940                    .px_2()
 5941                    .py_1()
 5942                    .gap_3()
 5943                    .elevation_2(cx)
 5944                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5945                    .id("accept-terms")
 5946                    .cursor_pointer()
 5947                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5948                    .on_click(cx.listener(|this, _event, window, cx| {
 5949                        cx.stop_propagation();
 5950                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5951                        window.dispatch_action(
 5952                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5953                            cx,
 5954                        );
 5955                    }))
 5956                    .child(
 5957                        h_flex()
 5958                            .flex_1()
 5959                            .gap_2()
 5960                            .child(Icon::new(IconName::ZedPredict))
 5961                            .child(Label::new("Accept Terms of Service"))
 5962                            .child(div().w_full())
 5963                            .child(
 5964                                Icon::new(IconName::ArrowUpRight)
 5965                                    .color(Color::Muted)
 5966                                    .size(IconSize::Small),
 5967                            )
 5968                            .into_any_element(),
 5969                    )
 5970                    .into_any(),
 5971            );
 5972        }
 5973
 5974        let is_refreshing = provider.provider.is_refreshing(cx);
 5975
 5976        fn pending_completion_container() -> Div {
 5977            h_flex()
 5978                .h_full()
 5979                .flex_1()
 5980                .gap_2()
 5981                .child(Icon::new(IconName::ZedPredict))
 5982        }
 5983
 5984        let completion = match &self.active_inline_completion {
 5985            Some(completion) => match &completion.completion {
 5986                InlineCompletion::Move {
 5987                    target, snapshot, ..
 5988                } if !self.has_visible_completions_menu() => {
 5989                    use text::ToPoint as _;
 5990
 5991                    return Some(
 5992                        h_flex()
 5993                            .px_2()
 5994                            .py_1()
 5995                            .elevation_2(cx)
 5996                            .border_color(cx.theme().colors().border)
 5997                            .rounded_tl(px(0.))
 5998                            .gap_2()
 5999                            .child(
 6000                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6001                                    Icon::new(IconName::ZedPredictDown)
 6002                                } else {
 6003                                    Icon::new(IconName::ZedPredictUp)
 6004                                },
 6005                            )
 6006                            .child(Label::new("Hold").size(LabelSize::Small))
 6007                            .child(h_flex().children(ui::render_modifiers(
 6008                                &accept_keystroke?.modifiers,
 6009                                PlatformStyle::platform(),
 6010                                Some(Color::Default),
 6011                                Some(IconSize::Small.rems().into()),
 6012                                false,
 6013                            )))
 6014                            .into_any(),
 6015                    );
 6016                }
 6017                _ => self.render_edit_prediction_cursor_popover_preview(
 6018                    completion,
 6019                    cursor_point,
 6020                    style,
 6021                    cx,
 6022                )?,
 6023            },
 6024
 6025            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6026                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6027                    stale_completion,
 6028                    cursor_point,
 6029                    style,
 6030                    cx,
 6031                )?,
 6032
 6033                None => {
 6034                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6035                }
 6036            },
 6037
 6038            None => pending_completion_container().child(Label::new("No Prediction")),
 6039        };
 6040
 6041        let completion = if is_refreshing {
 6042            completion
 6043                .with_animation(
 6044                    "loading-completion",
 6045                    Animation::new(Duration::from_secs(2))
 6046                        .repeat()
 6047                        .with_easing(pulsating_between(0.4, 0.8)),
 6048                    |label, delta| label.opacity(delta),
 6049                )
 6050                .into_any_element()
 6051        } else {
 6052            completion.into_any_element()
 6053        };
 6054
 6055        let has_completion = self.active_inline_completion.is_some();
 6056
 6057        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6058        Some(
 6059            h_flex()
 6060                .min_w(min_width)
 6061                .max_w(max_width)
 6062                .flex_1()
 6063                .elevation_2(cx)
 6064                .border_color(cx.theme().colors().border)
 6065                .child(
 6066                    div()
 6067                        .flex_1()
 6068                        .py_1()
 6069                        .px_2()
 6070                        .overflow_hidden()
 6071                        .child(completion),
 6072                )
 6073                .when_some(accept_keystroke, |el, accept_keystroke| {
 6074                    if !accept_keystroke.modifiers.modified() {
 6075                        return el;
 6076                    }
 6077
 6078                    el.child(
 6079                        h_flex()
 6080                            .h_full()
 6081                            .border_l_1()
 6082                            .rounded_r_lg()
 6083                            .border_color(cx.theme().colors().border)
 6084                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6085                            .gap_1()
 6086                            .py_1()
 6087                            .px_2()
 6088                            .child(
 6089                                h_flex()
 6090                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6091                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6092                                    .child(h_flex().children(ui::render_modifiers(
 6093                                        &accept_keystroke.modifiers,
 6094                                        PlatformStyle::platform(),
 6095                                        Some(if !has_completion {
 6096                                            Color::Muted
 6097                                        } else {
 6098                                            Color::Default
 6099                                        }),
 6100                                        None,
 6101                                        false,
 6102                                    ))),
 6103                            )
 6104                            .child(Label::new("Preview").into_any_element())
 6105                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6106                    )
 6107                })
 6108                .into_any(),
 6109        )
 6110    }
 6111
 6112    fn render_edit_prediction_cursor_popover_preview(
 6113        &self,
 6114        completion: &InlineCompletionState,
 6115        cursor_point: Point,
 6116        style: &EditorStyle,
 6117        cx: &mut Context<Editor>,
 6118    ) -> Option<Div> {
 6119        use text::ToPoint as _;
 6120
 6121        fn render_relative_row_jump(
 6122            prefix: impl Into<String>,
 6123            current_row: u32,
 6124            target_row: u32,
 6125        ) -> Div {
 6126            let (row_diff, arrow) = if target_row < current_row {
 6127                (current_row - target_row, IconName::ArrowUp)
 6128            } else {
 6129                (target_row - current_row, IconName::ArrowDown)
 6130            };
 6131
 6132            h_flex()
 6133                .child(
 6134                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6135                        .color(Color::Muted)
 6136                        .size(LabelSize::Small),
 6137                )
 6138                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6139        }
 6140
 6141        match &completion.completion {
 6142            InlineCompletion::Move {
 6143                target, snapshot, ..
 6144            } => Some(
 6145                h_flex()
 6146                    .px_2()
 6147                    .gap_2()
 6148                    .flex_1()
 6149                    .child(
 6150                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6151                            Icon::new(IconName::ZedPredictDown)
 6152                        } else {
 6153                            Icon::new(IconName::ZedPredictUp)
 6154                        },
 6155                    )
 6156                    .child(Label::new("Jump to Edit")),
 6157            ),
 6158
 6159            InlineCompletion::Edit {
 6160                edits,
 6161                edit_preview,
 6162                snapshot,
 6163                display_mode: _,
 6164            } => {
 6165                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6166
 6167                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6168                    &snapshot,
 6169                    &edits,
 6170                    edit_preview.as_ref()?,
 6171                    true,
 6172                    cx,
 6173                )
 6174                .first_line_preview();
 6175
 6176                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6177                    .with_highlights(&style.text, highlighted_edits.highlights);
 6178
 6179                let preview = h_flex()
 6180                    .gap_1()
 6181                    .min_w_16()
 6182                    .child(styled_text)
 6183                    .when(has_more_lines, |parent| parent.child(""));
 6184
 6185                let left = if first_edit_row != cursor_point.row {
 6186                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6187                        .into_any_element()
 6188                } else {
 6189                    Icon::new(IconName::ZedPredict).into_any_element()
 6190                };
 6191
 6192                Some(
 6193                    h_flex()
 6194                        .h_full()
 6195                        .flex_1()
 6196                        .gap_2()
 6197                        .pr_1()
 6198                        .overflow_x_hidden()
 6199                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6200                        .child(left)
 6201                        .child(preview),
 6202                )
 6203            }
 6204        }
 6205    }
 6206
 6207    fn render_context_menu(
 6208        &self,
 6209        style: &EditorStyle,
 6210        max_height_in_lines: u32,
 6211        y_flipped: bool,
 6212        window: &mut Window,
 6213        cx: &mut Context<Editor>,
 6214    ) -> Option<AnyElement> {
 6215        let menu = self.context_menu.borrow();
 6216        let menu = menu.as_ref()?;
 6217        if !menu.visible() {
 6218            return None;
 6219        };
 6220        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6221    }
 6222
 6223    fn render_context_menu_aside(
 6224        &self,
 6225        style: &EditorStyle,
 6226        max_size: Size<Pixels>,
 6227        cx: &mut Context<Editor>,
 6228    ) -> Option<AnyElement> {
 6229        self.context_menu.borrow().as_ref().and_then(|menu| {
 6230            if menu.visible() {
 6231                menu.render_aside(
 6232                    style,
 6233                    max_size,
 6234                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 6235                    cx,
 6236                )
 6237            } else {
 6238                None
 6239            }
 6240        })
 6241    }
 6242
 6243    fn hide_context_menu(
 6244        &mut self,
 6245        window: &mut Window,
 6246        cx: &mut Context<Self>,
 6247    ) -> Option<CodeContextMenu> {
 6248        cx.notify();
 6249        self.completion_tasks.clear();
 6250        let context_menu = self.context_menu.borrow_mut().take();
 6251        self.stale_inline_completion_in_menu.take();
 6252        self.update_visible_inline_completion(window, cx);
 6253        context_menu
 6254    }
 6255
 6256    fn show_snippet_choices(
 6257        &mut self,
 6258        choices: &Vec<String>,
 6259        selection: Range<Anchor>,
 6260        cx: &mut Context<Self>,
 6261    ) {
 6262        if selection.start.buffer_id.is_none() {
 6263            return;
 6264        }
 6265        let buffer_id = selection.start.buffer_id.unwrap();
 6266        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6267        let id = post_inc(&mut self.next_completion_id);
 6268
 6269        if let Some(buffer) = buffer {
 6270            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6271                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6272            ));
 6273        }
 6274    }
 6275
 6276    pub fn insert_snippet(
 6277        &mut self,
 6278        insertion_ranges: &[Range<usize>],
 6279        snippet: Snippet,
 6280        window: &mut Window,
 6281        cx: &mut Context<Self>,
 6282    ) -> Result<()> {
 6283        struct Tabstop<T> {
 6284            is_end_tabstop: bool,
 6285            ranges: Vec<Range<T>>,
 6286            choices: Option<Vec<String>>,
 6287        }
 6288
 6289        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6290            let snippet_text: Arc<str> = snippet.text.clone().into();
 6291            buffer.edit(
 6292                insertion_ranges
 6293                    .iter()
 6294                    .cloned()
 6295                    .map(|range| (range, snippet_text.clone())),
 6296                Some(AutoindentMode::EachLine),
 6297                cx,
 6298            );
 6299
 6300            let snapshot = &*buffer.read(cx);
 6301            let snippet = &snippet;
 6302            snippet
 6303                .tabstops
 6304                .iter()
 6305                .map(|tabstop| {
 6306                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6307                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6308                    });
 6309                    let mut tabstop_ranges = tabstop
 6310                        .ranges
 6311                        .iter()
 6312                        .flat_map(|tabstop_range| {
 6313                            let mut delta = 0_isize;
 6314                            insertion_ranges.iter().map(move |insertion_range| {
 6315                                let insertion_start = insertion_range.start as isize + delta;
 6316                                delta +=
 6317                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6318
 6319                                let start = ((insertion_start + tabstop_range.start) as usize)
 6320                                    .min(snapshot.len());
 6321                                let end = ((insertion_start + tabstop_range.end) as usize)
 6322                                    .min(snapshot.len());
 6323                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6324                            })
 6325                        })
 6326                        .collect::<Vec<_>>();
 6327                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6328
 6329                    Tabstop {
 6330                        is_end_tabstop,
 6331                        ranges: tabstop_ranges,
 6332                        choices: tabstop.choices.clone(),
 6333                    }
 6334                })
 6335                .collect::<Vec<_>>()
 6336        });
 6337        if let Some(tabstop) = tabstops.first() {
 6338            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6339                s.select_ranges(tabstop.ranges.iter().cloned());
 6340            });
 6341
 6342            if let Some(choices) = &tabstop.choices {
 6343                if let Some(selection) = tabstop.ranges.first() {
 6344                    self.show_snippet_choices(choices, selection.clone(), cx)
 6345                }
 6346            }
 6347
 6348            // If we're already at the last tabstop and it's at the end of the snippet,
 6349            // we're done, we don't need to keep the state around.
 6350            if !tabstop.is_end_tabstop {
 6351                let choices = tabstops
 6352                    .iter()
 6353                    .map(|tabstop| tabstop.choices.clone())
 6354                    .collect();
 6355
 6356                let ranges = tabstops
 6357                    .into_iter()
 6358                    .map(|tabstop| tabstop.ranges)
 6359                    .collect::<Vec<_>>();
 6360
 6361                self.snippet_stack.push(SnippetState {
 6362                    active_index: 0,
 6363                    ranges,
 6364                    choices,
 6365                });
 6366            }
 6367
 6368            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6369            if self.autoclose_regions.is_empty() {
 6370                let snapshot = self.buffer.read(cx).snapshot(cx);
 6371                for selection in &mut self.selections.all::<Point>(cx) {
 6372                    let selection_head = selection.head();
 6373                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6374                        continue;
 6375                    };
 6376
 6377                    let mut bracket_pair = None;
 6378                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6379                    let prev_chars = snapshot
 6380                        .reversed_chars_at(selection_head)
 6381                        .collect::<String>();
 6382                    for (pair, enabled) in scope.brackets() {
 6383                        if enabled
 6384                            && pair.close
 6385                            && prev_chars.starts_with(pair.start.as_str())
 6386                            && next_chars.starts_with(pair.end.as_str())
 6387                        {
 6388                            bracket_pair = Some(pair.clone());
 6389                            break;
 6390                        }
 6391                    }
 6392                    if let Some(pair) = bracket_pair {
 6393                        let start = snapshot.anchor_after(selection_head);
 6394                        let end = snapshot.anchor_after(selection_head);
 6395                        self.autoclose_regions.push(AutocloseRegion {
 6396                            selection_id: selection.id,
 6397                            range: start..end,
 6398                            pair,
 6399                        });
 6400                    }
 6401                }
 6402            }
 6403        }
 6404        Ok(())
 6405    }
 6406
 6407    pub fn move_to_next_snippet_tabstop(
 6408        &mut self,
 6409        window: &mut Window,
 6410        cx: &mut Context<Self>,
 6411    ) -> bool {
 6412        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6413    }
 6414
 6415    pub fn move_to_prev_snippet_tabstop(
 6416        &mut self,
 6417        window: &mut Window,
 6418        cx: &mut Context<Self>,
 6419    ) -> bool {
 6420        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6421    }
 6422
 6423    pub fn move_to_snippet_tabstop(
 6424        &mut self,
 6425        bias: Bias,
 6426        window: &mut Window,
 6427        cx: &mut Context<Self>,
 6428    ) -> bool {
 6429        if let Some(mut snippet) = self.snippet_stack.pop() {
 6430            match bias {
 6431                Bias::Left => {
 6432                    if snippet.active_index > 0 {
 6433                        snippet.active_index -= 1;
 6434                    } else {
 6435                        self.snippet_stack.push(snippet);
 6436                        return false;
 6437                    }
 6438                }
 6439                Bias::Right => {
 6440                    if snippet.active_index + 1 < snippet.ranges.len() {
 6441                        snippet.active_index += 1;
 6442                    } else {
 6443                        self.snippet_stack.push(snippet);
 6444                        return false;
 6445                    }
 6446                }
 6447            }
 6448            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6449                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6450                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6451                });
 6452
 6453                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6454                    if let Some(selection) = current_ranges.first() {
 6455                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6456                    }
 6457                }
 6458
 6459                // If snippet state is not at the last tabstop, push it back on the stack
 6460                if snippet.active_index + 1 < snippet.ranges.len() {
 6461                    self.snippet_stack.push(snippet);
 6462                }
 6463                return true;
 6464            }
 6465        }
 6466
 6467        false
 6468    }
 6469
 6470    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6471        self.transact(window, cx, |this, window, cx| {
 6472            this.select_all(&SelectAll, window, cx);
 6473            this.insert("", window, cx);
 6474        });
 6475    }
 6476
 6477    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6478        self.transact(window, cx, |this, window, cx| {
 6479            this.select_autoclose_pair(window, cx);
 6480            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6481            if !this.linked_edit_ranges.is_empty() {
 6482                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6483                let snapshot = this.buffer.read(cx).snapshot(cx);
 6484
 6485                for selection in selections.iter() {
 6486                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6487                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6488                    if selection_start.buffer_id != selection_end.buffer_id {
 6489                        continue;
 6490                    }
 6491                    if let Some(ranges) =
 6492                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6493                    {
 6494                        for (buffer, entries) in ranges {
 6495                            linked_ranges.entry(buffer).or_default().extend(entries);
 6496                        }
 6497                    }
 6498                }
 6499            }
 6500
 6501            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6502            if !this.selections.line_mode {
 6503                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6504                for selection in &mut selections {
 6505                    if selection.is_empty() {
 6506                        let old_head = selection.head();
 6507                        let mut new_head =
 6508                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6509                                .to_point(&display_map);
 6510                        if let Some((buffer, line_buffer_range)) = display_map
 6511                            .buffer_snapshot
 6512                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6513                        {
 6514                            let indent_size =
 6515                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6516                            let indent_len = match indent_size.kind {
 6517                                IndentKind::Space => {
 6518                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6519                                }
 6520                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6521                            };
 6522                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6523                                let indent_len = indent_len.get();
 6524                                new_head = cmp::min(
 6525                                    new_head,
 6526                                    MultiBufferPoint::new(
 6527                                        old_head.row,
 6528                                        ((old_head.column - 1) / indent_len) * indent_len,
 6529                                    ),
 6530                                );
 6531                            }
 6532                        }
 6533
 6534                        selection.set_head(new_head, SelectionGoal::None);
 6535                    }
 6536                }
 6537            }
 6538
 6539            this.signature_help_state.set_backspace_pressed(true);
 6540            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6541                s.select(selections)
 6542            });
 6543            this.insert("", window, cx);
 6544            let empty_str: Arc<str> = Arc::from("");
 6545            for (buffer, edits) in linked_ranges {
 6546                let snapshot = buffer.read(cx).snapshot();
 6547                use text::ToPoint as TP;
 6548
 6549                let edits = edits
 6550                    .into_iter()
 6551                    .map(|range| {
 6552                        let end_point = TP::to_point(&range.end, &snapshot);
 6553                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6554
 6555                        if end_point == start_point {
 6556                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6557                                .saturating_sub(1);
 6558                            start_point =
 6559                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6560                        };
 6561
 6562                        (start_point..end_point, empty_str.clone())
 6563                    })
 6564                    .sorted_by_key(|(range, _)| range.start)
 6565                    .collect::<Vec<_>>();
 6566                buffer.update(cx, |this, cx| {
 6567                    this.edit(edits, None, cx);
 6568                })
 6569            }
 6570            this.refresh_inline_completion(true, false, window, cx);
 6571            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6572        });
 6573    }
 6574
 6575    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6576        self.transact(window, cx, |this, window, cx| {
 6577            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6578                let line_mode = s.line_mode;
 6579                s.move_with(|map, selection| {
 6580                    if selection.is_empty() && !line_mode {
 6581                        let cursor = movement::right(map, selection.head());
 6582                        selection.end = cursor;
 6583                        selection.reversed = true;
 6584                        selection.goal = SelectionGoal::None;
 6585                    }
 6586                })
 6587            });
 6588            this.insert("", window, cx);
 6589            this.refresh_inline_completion(true, false, window, cx);
 6590        });
 6591    }
 6592
 6593    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6594        if self.move_to_prev_snippet_tabstop(window, cx) {
 6595            return;
 6596        }
 6597
 6598        self.outdent(&Outdent, window, cx);
 6599    }
 6600
 6601    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6602        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6603            return;
 6604        }
 6605
 6606        let mut selections = self.selections.all_adjusted(cx);
 6607        let buffer = self.buffer.read(cx);
 6608        let snapshot = buffer.snapshot(cx);
 6609        let rows_iter = selections.iter().map(|s| s.head().row);
 6610        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6611
 6612        let mut edits = Vec::new();
 6613        let mut prev_edited_row = 0;
 6614        let mut row_delta = 0;
 6615        for selection in &mut selections {
 6616            if selection.start.row != prev_edited_row {
 6617                row_delta = 0;
 6618            }
 6619            prev_edited_row = selection.end.row;
 6620
 6621            // If the selection is non-empty, then increase the indentation of the selected lines.
 6622            if !selection.is_empty() {
 6623                row_delta =
 6624                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6625                continue;
 6626            }
 6627
 6628            // If the selection is empty and the cursor is in the leading whitespace before the
 6629            // suggested indentation, then auto-indent the line.
 6630            let cursor = selection.head();
 6631            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6632            if let Some(suggested_indent) =
 6633                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6634            {
 6635                if cursor.column < suggested_indent.len
 6636                    && cursor.column <= current_indent.len
 6637                    && current_indent.len <= suggested_indent.len
 6638                {
 6639                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6640                    selection.end = selection.start;
 6641                    if row_delta == 0 {
 6642                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6643                            cursor.row,
 6644                            current_indent,
 6645                            suggested_indent,
 6646                        ));
 6647                        row_delta = suggested_indent.len - current_indent.len;
 6648                    }
 6649                    continue;
 6650                }
 6651            }
 6652
 6653            // Otherwise, insert a hard or soft tab.
 6654            let settings = buffer.settings_at(cursor, cx);
 6655            let tab_size = if settings.hard_tabs {
 6656                IndentSize::tab()
 6657            } else {
 6658                let tab_size = settings.tab_size.get();
 6659                let char_column = snapshot
 6660                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6661                    .flat_map(str::chars)
 6662                    .count()
 6663                    + row_delta as usize;
 6664                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6665                IndentSize::spaces(chars_to_next_tab_stop)
 6666            };
 6667            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6668            selection.end = selection.start;
 6669            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6670            row_delta += tab_size.len;
 6671        }
 6672
 6673        self.transact(window, cx, |this, window, cx| {
 6674            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6675            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6676                s.select(selections)
 6677            });
 6678            this.refresh_inline_completion(true, false, window, cx);
 6679        });
 6680    }
 6681
 6682    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6683        if self.read_only(cx) {
 6684            return;
 6685        }
 6686        let mut selections = self.selections.all::<Point>(cx);
 6687        let mut prev_edited_row = 0;
 6688        let mut row_delta = 0;
 6689        let mut edits = Vec::new();
 6690        let buffer = self.buffer.read(cx);
 6691        let snapshot = buffer.snapshot(cx);
 6692        for selection in &mut selections {
 6693            if selection.start.row != prev_edited_row {
 6694                row_delta = 0;
 6695            }
 6696            prev_edited_row = selection.end.row;
 6697
 6698            row_delta =
 6699                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6700        }
 6701
 6702        self.transact(window, cx, |this, window, cx| {
 6703            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6704            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6705                s.select(selections)
 6706            });
 6707        });
 6708    }
 6709
 6710    fn indent_selection(
 6711        buffer: &MultiBuffer,
 6712        snapshot: &MultiBufferSnapshot,
 6713        selection: &mut Selection<Point>,
 6714        edits: &mut Vec<(Range<Point>, String)>,
 6715        delta_for_start_row: u32,
 6716        cx: &App,
 6717    ) -> u32 {
 6718        let settings = buffer.settings_at(selection.start, cx);
 6719        let tab_size = settings.tab_size.get();
 6720        let indent_kind = if settings.hard_tabs {
 6721            IndentKind::Tab
 6722        } else {
 6723            IndentKind::Space
 6724        };
 6725        let mut start_row = selection.start.row;
 6726        let mut end_row = selection.end.row + 1;
 6727
 6728        // If a selection ends at the beginning of a line, don't indent
 6729        // that last line.
 6730        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6731            end_row -= 1;
 6732        }
 6733
 6734        // Avoid re-indenting a row that has already been indented by a
 6735        // previous selection, but still update this selection's column
 6736        // to reflect that indentation.
 6737        if delta_for_start_row > 0 {
 6738            start_row += 1;
 6739            selection.start.column += delta_for_start_row;
 6740            if selection.end.row == selection.start.row {
 6741                selection.end.column += delta_for_start_row;
 6742            }
 6743        }
 6744
 6745        let mut delta_for_end_row = 0;
 6746        let has_multiple_rows = start_row + 1 != end_row;
 6747        for row in start_row..end_row {
 6748            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6749            let indent_delta = match (current_indent.kind, indent_kind) {
 6750                (IndentKind::Space, IndentKind::Space) => {
 6751                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6752                    IndentSize::spaces(columns_to_next_tab_stop)
 6753                }
 6754                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6755                (_, IndentKind::Tab) => IndentSize::tab(),
 6756            };
 6757
 6758            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6759                0
 6760            } else {
 6761                selection.start.column
 6762            };
 6763            let row_start = Point::new(row, start);
 6764            edits.push((
 6765                row_start..row_start,
 6766                indent_delta.chars().collect::<String>(),
 6767            ));
 6768
 6769            // Update this selection's endpoints to reflect the indentation.
 6770            if row == selection.start.row {
 6771                selection.start.column += indent_delta.len;
 6772            }
 6773            if row == selection.end.row {
 6774                selection.end.column += indent_delta.len;
 6775                delta_for_end_row = indent_delta.len;
 6776            }
 6777        }
 6778
 6779        if selection.start.row == selection.end.row {
 6780            delta_for_start_row + delta_for_end_row
 6781        } else {
 6782            delta_for_end_row
 6783        }
 6784    }
 6785
 6786    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6787        if self.read_only(cx) {
 6788            return;
 6789        }
 6790        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6791        let selections = self.selections.all::<Point>(cx);
 6792        let mut deletion_ranges = Vec::new();
 6793        let mut last_outdent = None;
 6794        {
 6795            let buffer = self.buffer.read(cx);
 6796            let snapshot = buffer.snapshot(cx);
 6797            for selection in &selections {
 6798                let settings = buffer.settings_at(selection.start, cx);
 6799                let tab_size = settings.tab_size.get();
 6800                let mut rows = selection.spanned_rows(false, &display_map);
 6801
 6802                // Avoid re-outdenting a row that has already been outdented by a
 6803                // previous selection.
 6804                if let Some(last_row) = last_outdent {
 6805                    if last_row == rows.start {
 6806                        rows.start = rows.start.next_row();
 6807                    }
 6808                }
 6809                let has_multiple_rows = rows.len() > 1;
 6810                for row in rows.iter_rows() {
 6811                    let indent_size = snapshot.indent_size_for_line(row);
 6812                    if indent_size.len > 0 {
 6813                        let deletion_len = match indent_size.kind {
 6814                            IndentKind::Space => {
 6815                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6816                                if columns_to_prev_tab_stop == 0 {
 6817                                    tab_size
 6818                                } else {
 6819                                    columns_to_prev_tab_stop
 6820                                }
 6821                            }
 6822                            IndentKind::Tab => 1,
 6823                        };
 6824                        let start = if has_multiple_rows
 6825                            || deletion_len > selection.start.column
 6826                            || indent_size.len < selection.start.column
 6827                        {
 6828                            0
 6829                        } else {
 6830                            selection.start.column - deletion_len
 6831                        };
 6832                        deletion_ranges.push(
 6833                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6834                        );
 6835                        last_outdent = Some(row);
 6836                    }
 6837                }
 6838            }
 6839        }
 6840
 6841        self.transact(window, cx, |this, window, cx| {
 6842            this.buffer.update(cx, |buffer, cx| {
 6843                let empty_str: Arc<str> = Arc::default();
 6844                buffer.edit(
 6845                    deletion_ranges
 6846                        .into_iter()
 6847                        .map(|range| (range, empty_str.clone())),
 6848                    None,
 6849                    cx,
 6850                );
 6851            });
 6852            let selections = this.selections.all::<usize>(cx);
 6853            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6854                s.select(selections)
 6855            });
 6856        });
 6857    }
 6858
 6859    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6860        if self.read_only(cx) {
 6861            return;
 6862        }
 6863        let selections = self
 6864            .selections
 6865            .all::<usize>(cx)
 6866            .into_iter()
 6867            .map(|s| s.range());
 6868
 6869        self.transact(window, cx, |this, window, cx| {
 6870            this.buffer.update(cx, |buffer, cx| {
 6871                buffer.autoindent_ranges(selections, cx);
 6872            });
 6873            let selections = this.selections.all::<usize>(cx);
 6874            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6875                s.select(selections)
 6876            });
 6877        });
 6878    }
 6879
 6880    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6881        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6882        let selections = self.selections.all::<Point>(cx);
 6883
 6884        let mut new_cursors = Vec::new();
 6885        let mut edit_ranges = Vec::new();
 6886        let mut selections = selections.iter().peekable();
 6887        while let Some(selection) = selections.next() {
 6888            let mut rows = selection.spanned_rows(false, &display_map);
 6889            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6890
 6891            // Accumulate contiguous regions of rows that we want to delete.
 6892            while let Some(next_selection) = selections.peek() {
 6893                let next_rows = next_selection.spanned_rows(false, &display_map);
 6894                if next_rows.start <= rows.end {
 6895                    rows.end = next_rows.end;
 6896                    selections.next().unwrap();
 6897                } else {
 6898                    break;
 6899                }
 6900            }
 6901
 6902            let buffer = &display_map.buffer_snapshot;
 6903            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6904            let edit_end;
 6905            let cursor_buffer_row;
 6906            if buffer.max_point().row >= rows.end.0 {
 6907                // If there's a line after the range, delete the \n from the end of the row range
 6908                // and position the cursor on the next line.
 6909                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6910                cursor_buffer_row = rows.end;
 6911            } else {
 6912                // If there isn't a line after the range, delete the \n from the line before the
 6913                // start of the row range and position the cursor there.
 6914                edit_start = edit_start.saturating_sub(1);
 6915                edit_end = buffer.len();
 6916                cursor_buffer_row = rows.start.previous_row();
 6917            }
 6918
 6919            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6920            *cursor.column_mut() =
 6921                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6922
 6923            new_cursors.push((
 6924                selection.id,
 6925                buffer.anchor_after(cursor.to_point(&display_map)),
 6926            ));
 6927            edit_ranges.push(edit_start..edit_end);
 6928        }
 6929
 6930        self.transact(window, cx, |this, window, cx| {
 6931            let buffer = this.buffer.update(cx, |buffer, cx| {
 6932                let empty_str: Arc<str> = Arc::default();
 6933                buffer.edit(
 6934                    edit_ranges
 6935                        .into_iter()
 6936                        .map(|range| (range, empty_str.clone())),
 6937                    None,
 6938                    cx,
 6939                );
 6940                buffer.snapshot(cx)
 6941            });
 6942            let new_selections = new_cursors
 6943                .into_iter()
 6944                .map(|(id, cursor)| {
 6945                    let cursor = cursor.to_point(&buffer);
 6946                    Selection {
 6947                        id,
 6948                        start: cursor,
 6949                        end: cursor,
 6950                        reversed: false,
 6951                        goal: SelectionGoal::None,
 6952                    }
 6953                })
 6954                .collect();
 6955
 6956            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6957                s.select(new_selections);
 6958            });
 6959        });
 6960    }
 6961
 6962    pub fn join_lines_impl(
 6963        &mut self,
 6964        insert_whitespace: bool,
 6965        window: &mut Window,
 6966        cx: &mut Context<Self>,
 6967    ) {
 6968        if self.read_only(cx) {
 6969            return;
 6970        }
 6971        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6972        for selection in self.selections.all::<Point>(cx) {
 6973            let start = MultiBufferRow(selection.start.row);
 6974            // Treat single line selections as if they include the next line. Otherwise this action
 6975            // would do nothing for single line selections individual cursors.
 6976            let end = if selection.start.row == selection.end.row {
 6977                MultiBufferRow(selection.start.row + 1)
 6978            } else {
 6979                MultiBufferRow(selection.end.row)
 6980            };
 6981
 6982            if let Some(last_row_range) = row_ranges.last_mut() {
 6983                if start <= last_row_range.end {
 6984                    last_row_range.end = end;
 6985                    continue;
 6986                }
 6987            }
 6988            row_ranges.push(start..end);
 6989        }
 6990
 6991        let snapshot = self.buffer.read(cx).snapshot(cx);
 6992        let mut cursor_positions = Vec::new();
 6993        for row_range in &row_ranges {
 6994            let anchor = snapshot.anchor_before(Point::new(
 6995                row_range.end.previous_row().0,
 6996                snapshot.line_len(row_range.end.previous_row()),
 6997            ));
 6998            cursor_positions.push(anchor..anchor);
 6999        }
 7000
 7001        self.transact(window, cx, |this, window, cx| {
 7002            for row_range in row_ranges.into_iter().rev() {
 7003                for row in row_range.iter_rows().rev() {
 7004                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7005                    let next_line_row = row.next_row();
 7006                    let indent = snapshot.indent_size_for_line(next_line_row);
 7007                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7008
 7009                    let replace =
 7010                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7011                            " "
 7012                        } else {
 7013                            ""
 7014                        };
 7015
 7016                    this.buffer.update(cx, |buffer, cx| {
 7017                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7018                    });
 7019                }
 7020            }
 7021
 7022            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7023                s.select_anchor_ranges(cursor_positions)
 7024            });
 7025        });
 7026    }
 7027
 7028    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7029        self.join_lines_impl(true, window, cx);
 7030    }
 7031
 7032    pub fn sort_lines_case_sensitive(
 7033        &mut self,
 7034        _: &SortLinesCaseSensitive,
 7035        window: &mut Window,
 7036        cx: &mut Context<Self>,
 7037    ) {
 7038        self.manipulate_lines(window, cx, |lines| lines.sort())
 7039    }
 7040
 7041    pub fn sort_lines_case_insensitive(
 7042        &mut self,
 7043        _: &SortLinesCaseInsensitive,
 7044        window: &mut Window,
 7045        cx: &mut Context<Self>,
 7046    ) {
 7047        self.manipulate_lines(window, cx, |lines| {
 7048            lines.sort_by_key(|line| line.to_lowercase())
 7049        })
 7050    }
 7051
 7052    pub fn unique_lines_case_insensitive(
 7053        &mut self,
 7054        _: &UniqueLinesCaseInsensitive,
 7055        window: &mut Window,
 7056        cx: &mut Context<Self>,
 7057    ) {
 7058        self.manipulate_lines(window, cx, |lines| {
 7059            let mut seen = HashSet::default();
 7060            lines.retain(|line| seen.insert(line.to_lowercase()));
 7061        })
 7062    }
 7063
 7064    pub fn unique_lines_case_sensitive(
 7065        &mut self,
 7066        _: &UniqueLinesCaseSensitive,
 7067        window: &mut Window,
 7068        cx: &mut Context<Self>,
 7069    ) {
 7070        self.manipulate_lines(window, cx, |lines| {
 7071            let mut seen = HashSet::default();
 7072            lines.retain(|line| seen.insert(*line));
 7073        })
 7074    }
 7075
 7076    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 7077        let mut revert_changes = HashMap::default();
 7078        let snapshot = self.snapshot(window, cx);
 7079        for hunk in snapshot
 7080            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 7081        {
 7082            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7083        }
 7084        if !revert_changes.is_empty() {
 7085            self.transact(window, cx, |editor, window, cx| {
 7086                editor.revert(revert_changes, window, cx);
 7087            });
 7088        }
 7089    }
 7090
 7091    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7092        let Some(project) = self.project.clone() else {
 7093            return;
 7094        };
 7095        self.reload(project, window, cx)
 7096            .detach_and_notify_err(window, cx);
 7097    }
 7098
 7099    pub fn revert_selected_hunks(
 7100        &mut self,
 7101        _: &RevertSelectedHunks,
 7102        window: &mut Window,
 7103        cx: &mut Context<Self>,
 7104    ) {
 7105        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 7106        self.discard_hunks_in_ranges(selections, window, cx);
 7107    }
 7108
 7109    fn discard_hunks_in_ranges(
 7110        &mut self,
 7111        ranges: impl Iterator<Item = Range<Point>>,
 7112        window: &mut Window,
 7113        cx: &mut Context<Editor>,
 7114    ) {
 7115        let mut revert_changes = HashMap::default();
 7116        let snapshot = self.snapshot(window, cx);
 7117        for hunk in &snapshot.hunks_for_ranges(ranges) {
 7118            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7119        }
 7120        if !revert_changes.is_empty() {
 7121            self.transact(window, cx, |editor, window, cx| {
 7122                editor.revert(revert_changes, window, cx);
 7123            });
 7124        }
 7125    }
 7126
 7127    pub fn open_active_item_in_terminal(
 7128        &mut self,
 7129        _: &OpenInTerminal,
 7130        window: &mut Window,
 7131        cx: &mut Context<Self>,
 7132    ) {
 7133        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7134            let project_path = buffer.read(cx).project_path(cx)?;
 7135            let project = self.project.as_ref()?.read(cx);
 7136            let entry = project.entry_for_path(&project_path, cx)?;
 7137            let parent = match &entry.canonical_path {
 7138                Some(canonical_path) => canonical_path.to_path_buf(),
 7139                None => project.absolute_path(&project_path, cx)?,
 7140            }
 7141            .parent()?
 7142            .to_path_buf();
 7143            Some(parent)
 7144        }) {
 7145            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7146        }
 7147    }
 7148
 7149    pub fn prepare_revert_change(
 7150        &self,
 7151        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7152        hunk: &MultiBufferDiffHunk,
 7153        cx: &mut App,
 7154    ) -> Option<()> {
 7155        let buffer = self.buffer.read(cx);
 7156        let diff = buffer.diff_for(hunk.buffer_id)?;
 7157        let buffer = buffer.buffer(hunk.buffer_id)?;
 7158        let buffer = buffer.read(cx);
 7159        let original_text = diff
 7160            .read(cx)
 7161            .base_text()
 7162            .as_ref()?
 7163            .as_rope()
 7164            .slice(hunk.diff_base_byte_range.clone());
 7165        let buffer_snapshot = buffer.snapshot();
 7166        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7167        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7168            probe
 7169                .0
 7170                .start
 7171                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7172                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7173        }) {
 7174            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7175            Some(())
 7176        } else {
 7177            None
 7178        }
 7179    }
 7180
 7181    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7182        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7183    }
 7184
 7185    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7186        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7187    }
 7188
 7189    fn manipulate_lines<Fn>(
 7190        &mut self,
 7191        window: &mut Window,
 7192        cx: &mut Context<Self>,
 7193        mut callback: Fn,
 7194    ) where
 7195        Fn: FnMut(&mut Vec<&str>),
 7196    {
 7197        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7198        let buffer = self.buffer.read(cx).snapshot(cx);
 7199
 7200        let mut edits = Vec::new();
 7201
 7202        let selections = self.selections.all::<Point>(cx);
 7203        let mut selections = selections.iter().peekable();
 7204        let mut contiguous_row_selections = Vec::new();
 7205        let mut new_selections = Vec::new();
 7206        let mut added_lines = 0;
 7207        let mut removed_lines = 0;
 7208
 7209        while let Some(selection) = selections.next() {
 7210            let (start_row, end_row) = consume_contiguous_rows(
 7211                &mut contiguous_row_selections,
 7212                selection,
 7213                &display_map,
 7214                &mut selections,
 7215            );
 7216
 7217            let start_point = Point::new(start_row.0, 0);
 7218            let end_point = Point::new(
 7219                end_row.previous_row().0,
 7220                buffer.line_len(end_row.previous_row()),
 7221            );
 7222            let text = buffer
 7223                .text_for_range(start_point..end_point)
 7224                .collect::<String>();
 7225
 7226            let mut lines = text.split('\n').collect_vec();
 7227
 7228            let lines_before = lines.len();
 7229            callback(&mut lines);
 7230            let lines_after = lines.len();
 7231
 7232            edits.push((start_point..end_point, lines.join("\n")));
 7233
 7234            // Selections must change based on added and removed line count
 7235            let start_row =
 7236                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7237            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7238            new_selections.push(Selection {
 7239                id: selection.id,
 7240                start: start_row,
 7241                end: end_row,
 7242                goal: SelectionGoal::None,
 7243                reversed: selection.reversed,
 7244            });
 7245
 7246            if lines_after > lines_before {
 7247                added_lines += lines_after - lines_before;
 7248            } else if lines_before > lines_after {
 7249                removed_lines += lines_before - lines_after;
 7250            }
 7251        }
 7252
 7253        self.transact(window, cx, |this, window, cx| {
 7254            let buffer = this.buffer.update(cx, |buffer, cx| {
 7255                buffer.edit(edits, None, cx);
 7256                buffer.snapshot(cx)
 7257            });
 7258
 7259            // Recalculate offsets on newly edited buffer
 7260            let new_selections = new_selections
 7261                .iter()
 7262                .map(|s| {
 7263                    let start_point = Point::new(s.start.0, 0);
 7264                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7265                    Selection {
 7266                        id: s.id,
 7267                        start: buffer.point_to_offset(start_point),
 7268                        end: buffer.point_to_offset(end_point),
 7269                        goal: s.goal,
 7270                        reversed: s.reversed,
 7271                    }
 7272                })
 7273                .collect();
 7274
 7275            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7276                s.select(new_selections);
 7277            });
 7278
 7279            this.request_autoscroll(Autoscroll::fit(), cx);
 7280        });
 7281    }
 7282
 7283    pub fn convert_to_upper_case(
 7284        &mut self,
 7285        _: &ConvertToUpperCase,
 7286        window: &mut Window,
 7287        cx: &mut Context<Self>,
 7288    ) {
 7289        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7290    }
 7291
 7292    pub fn convert_to_lower_case(
 7293        &mut self,
 7294        _: &ConvertToLowerCase,
 7295        window: &mut Window,
 7296        cx: &mut Context<Self>,
 7297    ) {
 7298        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7299    }
 7300
 7301    pub fn convert_to_title_case(
 7302        &mut self,
 7303        _: &ConvertToTitleCase,
 7304        window: &mut Window,
 7305        cx: &mut Context<Self>,
 7306    ) {
 7307        self.manipulate_text(window, cx, |text| {
 7308            text.split('\n')
 7309                .map(|line| line.to_case(Case::Title))
 7310                .join("\n")
 7311        })
 7312    }
 7313
 7314    pub fn convert_to_snake_case(
 7315        &mut self,
 7316        _: &ConvertToSnakeCase,
 7317        window: &mut Window,
 7318        cx: &mut Context<Self>,
 7319    ) {
 7320        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7321    }
 7322
 7323    pub fn convert_to_kebab_case(
 7324        &mut self,
 7325        _: &ConvertToKebabCase,
 7326        window: &mut Window,
 7327        cx: &mut Context<Self>,
 7328    ) {
 7329        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7330    }
 7331
 7332    pub fn convert_to_upper_camel_case(
 7333        &mut self,
 7334        _: &ConvertToUpperCamelCase,
 7335        window: &mut Window,
 7336        cx: &mut Context<Self>,
 7337    ) {
 7338        self.manipulate_text(window, cx, |text| {
 7339            text.split('\n')
 7340                .map(|line| line.to_case(Case::UpperCamel))
 7341                .join("\n")
 7342        })
 7343    }
 7344
 7345    pub fn convert_to_lower_camel_case(
 7346        &mut self,
 7347        _: &ConvertToLowerCamelCase,
 7348        window: &mut Window,
 7349        cx: &mut Context<Self>,
 7350    ) {
 7351        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7352    }
 7353
 7354    pub fn convert_to_opposite_case(
 7355        &mut self,
 7356        _: &ConvertToOppositeCase,
 7357        window: &mut Window,
 7358        cx: &mut Context<Self>,
 7359    ) {
 7360        self.manipulate_text(window, cx, |text| {
 7361            text.chars()
 7362                .fold(String::with_capacity(text.len()), |mut t, c| {
 7363                    if c.is_uppercase() {
 7364                        t.extend(c.to_lowercase());
 7365                    } else {
 7366                        t.extend(c.to_uppercase());
 7367                    }
 7368                    t
 7369                })
 7370        })
 7371    }
 7372
 7373    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7374    where
 7375        Fn: FnMut(&str) -> String,
 7376    {
 7377        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7378        let buffer = self.buffer.read(cx).snapshot(cx);
 7379
 7380        let mut new_selections = Vec::new();
 7381        let mut edits = Vec::new();
 7382        let mut selection_adjustment = 0i32;
 7383
 7384        for selection in self.selections.all::<usize>(cx) {
 7385            let selection_is_empty = selection.is_empty();
 7386
 7387            let (start, end) = if selection_is_empty {
 7388                let word_range = movement::surrounding_word(
 7389                    &display_map,
 7390                    selection.start.to_display_point(&display_map),
 7391                );
 7392                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7393                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7394                (start, end)
 7395            } else {
 7396                (selection.start, selection.end)
 7397            };
 7398
 7399            let text = buffer.text_for_range(start..end).collect::<String>();
 7400            let old_length = text.len() as i32;
 7401            let text = callback(&text);
 7402
 7403            new_selections.push(Selection {
 7404                start: (start as i32 - selection_adjustment) as usize,
 7405                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7406                goal: SelectionGoal::None,
 7407                ..selection
 7408            });
 7409
 7410            selection_adjustment += old_length - text.len() as i32;
 7411
 7412            edits.push((start..end, text));
 7413        }
 7414
 7415        self.transact(window, cx, |this, window, cx| {
 7416            this.buffer.update(cx, |buffer, cx| {
 7417                buffer.edit(edits, None, cx);
 7418            });
 7419
 7420            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7421                s.select(new_selections);
 7422            });
 7423
 7424            this.request_autoscroll(Autoscroll::fit(), cx);
 7425        });
 7426    }
 7427
 7428    pub fn duplicate(
 7429        &mut self,
 7430        upwards: bool,
 7431        whole_lines: bool,
 7432        window: &mut Window,
 7433        cx: &mut Context<Self>,
 7434    ) {
 7435        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7436        let buffer = &display_map.buffer_snapshot;
 7437        let selections = self.selections.all::<Point>(cx);
 7438
 7439        let mut edits = Vec::new();
 7440        let mut selections_iter = selections.iter().peekable();
 7441        while let Some(selection) = selections_iter.next() {
 7442            let mut rows = selection.spanned_rows(false, &display_map);
 7443            // duplicate line-wise
 7444            if whole_lines || selection.start == selection.end {
 7445                // Avoid duplicating the same lines twice.
 7446                while let Some(next_selection) = selections_iter.peek() {
 7447                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7448                    if next_rows.start < rows.end {
 7449                        rows.end = next_rows.end;
 7450                        selections_iter.next().unwrap();
 7451                    } else {
 7452                        break;
 7453                    }
 7454                }
 7455
 7456                // Copy the text from the selected row region and splice it either at the start
 7457                // or end of the region.
 7458                let start = Point::new(rows.start.0, 0);
 7459                let end = Point::new(
 7460                    rows.end.previous_row().0,
 7461                    buffer.line_len(rows.end.previous_row()),
 7462                );
 7463                let text = buffer
 7464                    .text_for_range(start..end)
 7465                    .chain(Some("\n"))
 7466                    .collect::<String>();
 7467                let insert_location = if upwards {
 7468                    Point::new(rows.end.0, 0)
 7469                } else {
 7470                    start
 7471                };
 7472                edits.push((insert_location..insert_location, text));
 7473            } else {
 7474                // duplicate character-wise
 7475                let start = selection.start;
 7476                let end = selection.end;
 7477                let text = buffer.text_for_range(start..end).collect::<String>();
 7478                edits.push((selection.end..selection.end, text));
 7479            }
 7480        }
 7481
 7482        self.transact(window, cx, |this, _, cx| {
 7483            this.buffer.update(cx, |buffer, cx| {
 7484                buffer.edit(edits, None, cx);
 7485            });
 7486
 7487            this.request_autoscroll(Autoscroll::fit(), cx);
 7488        });
 7489    }
 7490
 7491    pub fn duplicate_line_up(
 7492        &mut self,
 7493        _: &DuplicateLineUp,
 7494        window: &mut Window,
 7495        cx: &mut Context<Self>,
 7496    ) {
 7497        self.duplicate(true, true, window, cx);
 7498    }
 7499
 7500    pub fn duplicate_line_down(
 7501        &mut self,
 7502        _: &DuplicateLineDown,
 7503        window: &mut Window,
 7504        cx: &mut Context<Self>,
 7505    ) {
 7506        self.duplicate(false, true, window, cx);
 7507    }
 7508
 7509    pub fn duplicate_selection(
 7510        &mut self,
 7511        _: &DuplicateSelection,
 7512        window: &mut Window,
 7513        cx: &mut Context<Self>,
 7514    ) {
 7515        self.duplicate(false, false, window, cx);
 7516    }
 7517
 7518    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7519        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7520        let buffer = self.buffer.read(cx).snapshot(cx);
 7521
 7522        let mut edits = Vec::new();
 7523        let mut unfold_ranges = Vec::new();
 7524        let mut refold_creases = Vec::new();
 7525
 7526        let selections = self.selections.all::<Point>(cx);
 7527        let mut selections = selections.iter().peekable();
 7528        let mut contiguous_row_selections = Vec::new();
 7529        let mut new_selections = Vec::new();
 7530
 7531        while let Some(selection) = selections.next() {
 7532            // Find all the selections that span a contiguous row range
 7533            let (start_row, end_row) = consume_contiguous_rows(
 7534                &mut contiguous_row_selections,
 7535                selection,
 7536                &display_map,
 7537                &mut selections,
 7538            );
 7539
 7540            // Move the text spanned by the row range to be before the line preceding the row range
 7541            if start_row.0 > 0 {
 7542                let range_to_move = Point::new(
 7543                    start_row.previous_row().0,
 7544                    buffer.line_len(start_row.previous_row()),
 7545                )
 7546                    ..Point::new(
 7547                        end_row.previous_row().0,
 7548                        buffer.line_len(end_row.previous_row()),
 7549                    );
 7550                let insertion_point = display_map
 7551                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7552                    .0;
 7553
 7554                // Don't move lines across excerpts
 7555                if buffer
 7556                    .excerpt_containing(insertion_point..range_to_move.end)
 7557                    .is_some()
 7558                {
 7559                    let text = buffer
 7560                        .text_for_range(range_to_move.clone())
 7561                        .flat_map(|s| s.chars())
 7562                        .skip(1)
 7563                        .chain(['\n'])
 7564                        .collect::<String>();
 7565
 7566                    edits.push((
 7567                        buffer.anchor_after(range_to_move.start)
 7568                            ..buffer.anchor_before(range_to_move.end),
 7569                        String::new(),
 7570                    ));
 7571                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7572                    edits.push((insertion_anchor..insertion_anchor, text));
 7573
 7574                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7575
 7576                    // Move selections up
 7577                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7578                        |mut selection| {
 7579                            selection.start.row -= row_delta;
 7580                            selection.end.row -= row_delta;
 7581                            selection
 7582                        },
 7583                    ));
 7584
 7585                    // Move folds up
 7586                    unfold_ranges.push(range_to_move.clone());
 7587                    for fold in display_map.folds_in_range(
 7588                        buffer.anchor_before(range_to_move.start)
 7589                            ..buffer.anchor_after(range_to_move.end),
 7590                    ) {
 7591                        let mut start = fold.range.start.to_point(&buffer);
 7592                        let mut end = fold.range.end.to_point(&buffer);
 7593                        start.row -= row_delta;
 7594                        end.row -= row_delta;
 7595                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7596                    }
 7597                }
 7598            }
 7599
 7600            // If we didn't move line(s), preserve the existing selections
 7601            new_selections.append(&mut contiguous_row_selections);
 7602        }
 7603
 7604        self.transact(window, cx, |this, window, cx| {
 7605            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7606            this.buffer.update(cx, |buffer, cx| {
 7607                for (range, text) in edits {
 7608                    buffer.edit([(range, text)], None, cx);
 7609                }
 7610            });
 7611            this.fold_creases(refold_creases, true, window, cx);
 7612            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7613                s.select(new_selections);
 7614            })
 7615        });
 7616    }
 7617
 7618    pub fn move_line_down(
 7619        &mut self,
 7620        _: &MoveLineDown,
 7621        window: &mut Window,
 7622        cx: &mut Context<Self>,
 7623    ) {
 7624        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7625        let buffer = self.buffer.read(cx).snapshot(cx);
 7626
 7627        let mut edits = Vec::new();
 7628        let mut unfold_ranges = Vec::new();
 7629        let mut refold_creases = Vec::new();
 7630
 7631        let selections = self.selections.all::<Point>(cx);
 7632        let mut selections = selections.iter().peekable();
 7633        let mut contiguous_row_selections = Vec::new();
 7634        let mut new_selections = Vec::new();
 7635
 7636        while let Some(selection) = selections.next() {
 7637            // Find all the selections that span a contiguous row range
 7638            let (start_row, end_row) = consume_contiguous_rows(
 7639                &mut contiguous_row_selections,
 7640                selection,
 7641                &display_map,
 7642                &mut selections,
 7643            );
 7644
 7645            // Move the text spanned by the row range to be after the last line of the row range
 7646            if end_row.0 <= buffer.max_point().row {
 7647                let range_to_move =
 7648                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7649                let insertion_point = display_map
 7650                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7651                    .0;
 7652
 7653                // Don't move lines across excerpt boundaries
 7654                if buffer
 7655                    .excerpt_containing(range_to_move.start..insertion_point)
 7656                    .is_some()
 7657                {
 7658                    let mut text = String::from("\n");
 7659                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7660                    text.pop(); // Drop trailing newline
 7661                    edits.push((
 7662                        buffer.anchor_after(range_to_move.start)
 7663                            ..buffer.anchor_before(range_to_move.end),
 7664                        String::new(),
 7665                    ));
 7666                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7667                    edits.push((insertion_anchor..insertion_anchor, text));
 7668
 7669                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7670
 7671                    // Move selections down
 7672                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7673                        |mut selection| {
 7674                            selection.start.row += row_delta;
 7675                            selection.end.row += row_delta;
 7676                            selection
 7677                        },
 7678                    ));
 7679
 7680                    // Move folds down
 7681                    unfold_ranges.push(range_to_move.clone());
 7682                    for fold in display_map.folds_in_range(
 7683                        buffer.anchor_before(range_to_move.start)
 7684                            ..buffer.anchor_after(range_to_move.end),
 7685                    ) {
 7686                        let mut start = fold.range.start.to_point(&buffer);
 7687                        let mut end = fold.range.end.to_point(&buffer);
 7688                        start.row += row_delta;
 7689                        end.row += row_delta;
 7690                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7691                    }
 7692                }
 7693            }
 7694
 7695            // If we didn't move line(s), preserve the existing selections
 7696            new_selections.append(&mut contiguous_row_selections);
 7697        }
 7698
 7699        self.transact(window, cx, |this, window, cx| {
 7700            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7701            this.buffer.update(cx, |buffer, cx| {
 7702                for (range, text) in edits {
 7703                    buffer.edit([(range, text)], None, cx);
 7704                }
 7705            });
 7706            this.fold_creases(refold_creases, true, window, cx);
 7707            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7708                s.select(new_selections)
 7709            });
 7710        });
 7711    }
 7712
 7713    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7714        let text_layout_details = &self.text_layout_details(window);
 7715        self.transact(window, cx, |this, window, cx| {
 7716            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7717                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7718                let line_mode = s.line_mode;
 7719                s.move_with(|display_map, selection| {
 7720                    if !selection.is_empty() || line_mode {
 7721                        return;
 7722                    }
 7723
 7724                    let mut head = selection.head();
 7725                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7726                    if head.column() == display_map.line_len(head.row()) {
 7727                        transpose_offset = display_map
 7728                            .buffer_snapshot
 7729                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7730                    }
 7731
 7732                    if transpose_offset == 0 {
 7733                        return;
 7734                    }
 7735
 7736                    *head.column_mut() += 1;
 7737                    head = display_map.clip_point(head, Bias::Right);
 7738                    let goal = SelectionGoal::HorizontalPosition(
 7739                        display_map
 7740                            .x_for_display_point(head, text_layout_details)
 7741                            .into(),
 7742                    );
 7743                    selection.collapse_to(head, goal);
 7744
 7745                    let transpose_start = display_map
 7746                        .buffer_snapshot
 7747                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7748                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7749                        let transpose_end = display_map
 7750                            .buffer_snapshot
 7751                            .clip_offset(transpose_offset + 1, Bias::Right);
 7752                        if let Some(ch) =
 7753                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7754                        {
 7755                            edits.push((transpose_start..transpose_offset, String::new()));
 7756                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7757                        }
 7758                    }
 7759                });
 7760                edits
 7761            });
 7762            this.buffer
 7763                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7764            let selections = this.selections.all::<usize>(cx);
 7765            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7766                s.select(selections);
 7767            });
 7768        });
 7769    }
 7770
 7771    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7772        self.rewrap_impl(IsVimMode::No, cx)
 7773    }
 7774
 7775    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7776        let buffer = self.buffer.read(cx).snapshot(cx);
 7777        let selections = self.selections.all::<Point>(cx);
 7778        let mut selections = selections.iter().peekable();
 7779
 7780        let mut edits = Vec::new();
 7781        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7782
 7783        while let Some(selection) = selections.next() {
 7784            let mut start_row = selection.start.row;
 7785            let mut end_row = selection.end.row;
 7786
 7787            // Skip selections that overlap with a range that has already been rewrapped.
 7788            let selection_range = start_row..end_row;
 7789            if rewrapped_row_ranges
 7790                .iter()
 7791                .any(|range| range.overlaps(&selection_range))
 7792            {
 7793                continue;
 7794            }
 7795
 7796            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7797
 7798            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7799                match language_scope.language_name().as_ref() {
 7800                    "Markdown" | "Plain Text" => {
 7801                        should_rewrap = true;
 7802                    }
 7803                    _ => {}
 7804                }
 7805            }
 7806
 7807            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7808
 7809            // Since not all lines in the selection may be at the same indent
 7810            // level, choose the indent size that is the most common between all
 7811            // of the lines.
 7812            //
 7813            // If there is a tie, we use the deepest indent.
 7814            let (indent_size, indent_end) = {
 7815                let mut indent_size_occurrences = HashMap::default();
 7816                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7817
 7818                for row in start_row..=end_row {
 7819                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7820                    rows_by_indent_size.entry(indent).or_default().push(row);
 7821                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7822                }
 7823
 7824                let indent_size = indent_size_occurrences
 7825                    .into_iter()
 7826                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7827                    .map(|(indent, _)| indent)
 7828                    .unwrap_or_default();
 7829                let row = rows_by_indent_size[&indent_size][0];
 7830                let indent_end = Point::new(row, indent_size.len);
 7831
 7832                (indent_size, indent_end)
 7833            };
 7834
 7835            let mut line_prefix = indent_size.chars().collect::<String>();
 7836
 7837            if let Some(comment_prefix) =
 7838                buffer
 7839                    .language_scope_at(selection.head())
 7840                    .and_then(|language| {
 7841                        language
 7842                            .line_comment_prefixes()
 7843                            .iter()
 7844                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7845                            .cloned()
 7846                    })
 7847            {
 7848                line_prefix.push_str(&comment_prefix);
 7849                should_rewrap = true;
 7850            }
 7851
 7852            if !should_rewrap {
 7853                continue;
 7854            }
 7855
 7856            if selection.is_empty() {
 7857                'expand_upwards: while start_row > 0 {
 7858                    let prev_row = start_row - 1;
 7859                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7860                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7861                    {
 7862                        start_row = prev_row;
 7863                    } else {
 7864                        break 'expand_upwards;
 7865                    }
 7866                }
 7867
 7868                'expand_downwards: while end_row < buffer.max_point().row {
 7869                    let next_row = end_row + 1;
 7870                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7871                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7872                    {
 7873                        end_row = next_row;
 7874                    } else {
 7875                        break 'expand_downwards;
 7876                    }
 7877                }
 7878            }
 7879
 7880            let start = Point::new(start_row, 0);
 7881            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7882            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7883            let Some(lines_without_prefixes) = selection_text
 7884                .lines()
 7885                .map(|line| {
 7886                    line.strip_prefix(&line_prefix)
 7887                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7888                        .ok_or_else(|| {
 7889                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7890                        })
 7891                })
 7892                .collect::<Result<Vec<_>, _>>()
 7893                .log_err()
 7894            else {
 7895                continue;
 7896            };
 7897
 7898            let wrap_column = buffer
 7899                .settings_at(Point::new(start_row, 0), cx)
 7900                .preferred_line_length as usize;
 7901            let wrapped_text = wrap_with_prefix(
 7902                line_prefix,
 7903                lines_without_prefixes.join(" "),
 7904                wrap_column,
 7905                tab_size,
 7906            );
 7907
 7908            // TODO: should always use char-based diff while still supporting cursor behavior that
 7909            // matches vim.
 7910            let diff = match is_vim_mode {
 7911                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7912                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7913            };
 7914            let mut offset = start.to_offset(&buffer);
 7915            let mut moved_since_edit = true;
 7916
 7917            for change in diff.iter_all_changes() {
 7918                let value = change.value();
 7919                match change.tag() {
 7920                    ChangeTag::Equal => {
 7921                        offset += value.len();
 7922                        moved_since_edit = true;
 7923                    }
 7924                    ChangeTag::Delete => {
 7925                        let start = buffer.anchor_after(offset);
 7926                        let end = buffer.anchor_before(offset + value.len());
 7927
 7928                        if moved_since_edit {
 7929                            edits.push((start..end, String::new()));
 7930                        } else {
 7931                            edits.last_mut().unwrap().0.end = end;
 7932                        }
 7933
 7934                        offset += value.len();
 7935                        moved_since_edit = false;
 7936                    }
 7937                    ChangeTag::Insert => {
 7938                        if moved_since_edit {
 7939                            let anchor = buffer.anchor_after(offset);
 7940                            edits.push((anchor..anchor, value.to_string()));
 7941                        } else {
 7942                            edits.last_mut().unwrap().1.push_str(value);
 7943                        }
 7944
 7945                        moved_since_edit = false;
 7946                    }
 7947                }
 7948            }
 7949
 7950            rewrapped_row_ranges.push(start_row..=end_row);
 7951        }
 7952
 7953        self.buffer
 7954            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7955    }
 7956
 7957    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7958        let mut text = String::new();
 7959        let buffer = self.buffer.read(cx).snapshot(cx);
 7960        let mut selections = self.selections.all::<Point>(cx);
 7961        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7962        {
 7963            let max_point = buffer.max_point();
 7964            let mut is_first = true;
 7965            for selection in &mut selections {
 7966                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7967                if is_entire_line {
 7968                    selection.start = Point::new(selection.start.row, 0);
 7969                    if !selection.is_empty() && selection.end.column == 0 {
 7970                        selection.end = cmp::min(max_point, selection.end);
 7971                    } else {
 7972                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7973                    }
 7974                    selection.goal = SelectionGoal::None;
 7975                }
 7976                if is_first {
 7977                    is_first = false;
 7978                } else {
 7979                    text += "\n";
 7980                }
 7981                let mut len = 0;
 7982                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7983                    text.push_str(chunk);
 7984                    len += chunk.len();
 7985                }
 7986                clipboard_selections.push(ClipboardSelection {
 7987                    len,
 7988                    is_entire_line,
 7989                    first_line_indent: buffer
 7990                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7991                        .len,
 7992                });
 7993            }
 7994        }
 7995
 7996        self.transact(window, cx, |this, window, cx| {
 7997            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7998                s.select(selections);
 7999            });
 8000            this.insert("", window, cx);
 8001        });
 8002        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8003    }
 8004
 8005    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8006        let item = self.cut_common(window, cx);
 8007        cx.write_to_clipboard(item);
 8008    }
 8009
 8010    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8011        self.change_selections(None, window, cx, |s| {
 8012            s.move_with(|snapshot, sel| {
 8013                if sel.is_empty() {
 8014                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8015                }
 8016            });
 8017        });
 8018        let item = self.cut_common(window, cx);
 8019        cx.set_global(KillRing(item))
 8020    }
 8021
 8022    pub fn kill_ring_yank(
 8023        &mut self,
 8024        _: &KillRingYank,
 8025        window: &mut Window,
 8026        cx: &mut Context<Self>,
 8027    ) {
 8028        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8029            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8030                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8031            } else {
 8032                return;
 8033            }
 8034        } else {
 8035            return;
 8036        };
 8037        self.do_paste(&text, metadata, false, window, cx);
 8038    }
 8039
 8040    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8041        let selections = self.selections.all::<Point>(cx);
 8042        let buffer = self.buffer.read(cx).read(cx);
 8043        let mut text = String::new();
 8044
 8045        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8046        {
 8047            let max_point = buffer.max_point();
 8048            let mut is_first = true;
 8049            for selection in selections.iter() {
 8050                let mut start = selection.start;
 8051                let mut end = selection.end;
 8052                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8053                if is_entire_line {
 8054                    start = Point::new(start.row, 0);
 8055                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8056                }
 8057                if is_first {
 8058                    is_first = false;
 8059                } else {
 8060                    text += "\n";
 8061                }
 8062                let mut len = 0;
 8063                for chunk in buffer.text_for_range(start..end) {
 8064                    text.push_str(chunk);
 8065                    len += chunk.len();
 8066                }
 8067                clipboard_selections.push(ClipboardSelection {
 8068                    len,
 8069                    is_entire_line,
 8070                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8071                });
 8072            }
 8073        }
 8074
 8075        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8076            text,
 8077            clipboard_selections,
 8078        ));
 8079    }
 8080
 8081    pub fn do_paste(
 8082        &mut self,
 8083        text: &String,
 8084        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8085        handle_entire_lines: bool,
 8086        window: &mut Window,
 8087        cx: &mut Context<Self>,
 8088    ) {
 8089        if self.read_only(cx) {
 8090            return;
 8091        }
 8092
 8093        let clipboard_text = Cow::Borrowed(text);
 8094
 8095        self.transact(window, cx, |this, window, cx| {
 8096            if let Some(mut clipboard_selections) = clipboard_selections {
 8097                let old_selections = this.selections.all::<usize>(cx);
 8098                let all_selections_were_entire_line =
 8099                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8100                let first_selection_indent_column =
 8101                    clipboard_selections.first().map(|s| s.first_line_indent);
 8102                if clipboard_selections.len() != old_selections.len() {
 8103                    clipboard_selections.drain(..);
 8104                }
 8105                let cursor_offset = this.selections.last::<usize>(cx).head();
 8106                let mut auto_indent_on_paste = true;
 8107
 8108                this.buffer.update(cx, |buffer, cx| {
 8109                    let snapshot = buffer.read(cx);
 8110                    auto_indent_on_paste =
 8111                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8112
 8113                    let mut start_offset = 0;
 8114                    let mut edits = Vec::new();
 8115                    let mut original_indent_columns = Vec::new();
 8116                    for (ix, selection) in old_selections.iter().enumerate() {
 8117                        let to_insert;
 8118                        let entire_line;
 8119                        let original_indent_column;
 8120                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8121                            let end_offset = start_offset + clipboard_selection.len;
 8122                            to_insert = &clipboard_text[start_offset..end_offset];
 8123                            entire_line = clipboard_selection.is_entire_line;
 8124                            start_offset = end_offset + 1;
 8125                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8126                        } else {
 8127                            to_insert = clipboard_text.as_str();
 8128                            entire_line = all_selections_were_entire_line;
 8129                            original_indent_column = first_selection_indent_column
 8130                        }
 8131
 8132                        // If the corresponding selection was empty when this slice of the
 8133                        // clipboard text was written, then the entire line containing the
 8134                        // selection was copied. If this selection is also currently empty,
 8135                        // then paste the line before the current line of the buffer.
 8136                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8137                            let column = selection.start.to_point(&snapshot).column as usize;
 8138                            let line_start = selection.start - column;
 8139                            line_start..line_start
 8140                        } else {
 8141                            selection.range()
 8142                        };
 8143
 8144                        edits.push((range, to_insert));
 8145                        original_indent_columns.extend(original_indent_column);
 8146                    }
 8147                    drop(snapshot);
 8148
 8149                    buffer.edit(
 8150                        edits,
 8151                        if auto_indent_on_paste {
 8152                            Some(AutoindentMode::Block {
 8153                                original_indent_columns,
 8154                            })
 8155                        } else {
 8156                            None
 8157                        },
 8158                        cx,
 8159                    );
 8160                });
 8161
 8162                let selections = this.selections.all::<usize>(cx);
 8163                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8164                    s.select(selections)
 8165                });
 8166            } else {
 8167                this.insert(&clipboard_text, window, cx);
 8168            }
 8169        });
 8170    }
 8171
 8172    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8173        if let Some(item) = cx.read_from_clipboard() {
 8174            let entries = item.entries();
 8175
 8176            match entries.first() {
 8177                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8178                // of all the pasted entries.
 8179                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8180                    .do_paste(
 8181                        clipboard_string.text(),
 8182                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8183                        true,
 8184                        window,
 8185                        cx,
 8186                    ),
 8187                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8188            }
 8189        }
 8190    }
 8191
 8192    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8193        if self.read_only(cx) {
 8194            return;
 8195        }
 8196
 8197        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8198            if let Some((selections, _)) =
 8199                self.selection_history.transaction(transaction_id).cloned()
 8200            {
 8201                self.change_selections(None, window, cx, |s| {
 8202                    s.select_anchors(selections.to_vec());
 8203                });
 8204            }
 8205            self.request_autoscroll(Autoscroll::fit(), cx);
 8206            self.unmark_text(window, cx);
 8207            self.refresh_inline_completion(true, false, window, cx);
 8208            cx.emit(EditorEvent::Edited { transaction_id });
 8209            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8210        }
 8211    }
 8212
 8213    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8214        if self.read_only(cx) {
 8215            return;
 8216        }
 8217
 8218        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8219            if let Some((_, Some(selections))) =
 8220                self.selection_history.transaction(transaction_id).cloned()
 8221            {
 8222                self.change_selections(None, window, cx, |s| {
 8223                    s.select_anchors(selections.to_vec());
 8224                });
 8225            }
 8226            self.request_autoscroll(Autoscroll::fit(), cx);
 8227            self.unmark_text(window, cx);
 8228            self.refresh_inline_completion(true, false, window, cx);
 8229            cx.emit(EditorEvent::Edited { transaction_id });
 8230        }
 8231    }
 8232
 8233    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8234        self.buffer
 8235            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8236    }
 8237
 8238    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8239        self.buffer
 8240            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8241    }
 8242
 8243    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8244        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8245            let line_mode = s.line_mode;
 8246            s.move_with(|map, selection| {
 8247                let cursor = if selection.is_empty() && !line_mode {
 8248                    movement::left(map, selection.start)
 8249                } else {
 8250                    selection.start
 8251                };
 8252                selection.collapse_to(cursor, SelectionGoal::None);
 8253            });
 8254        })
 8255    }
 8256
 8257    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8258        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8259            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8260        })
 8261    }
 8262
 8263    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8264        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8265            let line_mode = s.line_mode;
 8266            s.move_with(|map, selection| {
 8267                let cursor = if selection.is_empty() && !line_mode {
 8268                    movement::right(map, selection.end)
 8269                } else {
 8270                    selection.end
 8271                };
 8272                selection.collapse_to(cursor, SelectionGoal::None)
 8273            });
 8274        })
 8275    }
 8276
 8277    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8278        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8279            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8280        })
 8281    }
 8282
 8283    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8284        if self.take_rename(true, window, cx).is_some() {
 8285            return;
 8286        }
 8287
 8288        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8289            cx.propagate();
 8290            return;
 8291        }
 8292
 8293        let text_layout_details = &self.text_layout_details(window);
 8294        let selection_count = self.selections.count();
 8295        let first_selection = self.selections.first_anchor();
 8296
 8297        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8298            let line_mode = s.line_mode;
 8299            s.move_with(|map, selection| {
 8300                if !selection.is_empty() && !line_mode {
 8301                    selection.goal = SelectionGoal::None;
 8302                }
 8303                let (cursor, goal) = movement::up(
 8304                    map,
 8305                    selection.start,
 8306                    selection.goal,
 8307                    false,
 8308                    text_layout_details,
 8309                );
 8310                selection.collapse_to(cursor, goal);
 8311            });
 8312        });
 8313
 8314        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8315        {
 8316            cx.propagate();
 8317        }
 8318    }
 8319
 8320    pub fn move_up_by_lines(
 8321        &mut self,
 8322        action: &MoveUpByLines,
 8323        window: &mut Window,
 8324        cx: &mut Context<Self>,
 8325    ) {
 8326        if self.take_rename(true, window, cx).is_some() {
 8327            return;
 8328        }
 8329
 8330        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8331            cx.propagate();
 8332            return;
 8333        }
 8334
 8335        let text_layout_details = &self.text_layout_details(window);
 8336
 8337        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8338            let line_mode = s.line_mode;
 8339            s.move_with(|map, selection| {
 8340                if !selection.is_empty() && !line_mode {
 8341                    selection.goal = SelectionGoal::None;
 8342                }
 8343                let (cursor, goal) = movement::up_by_rows(
 8344                    map,
 8345                    selection.start,
 8346                    action.lines,
 8347                    selection.goal,
 8348                    false,
 8349                    text_layout_details,
 8350                );
 8351                selection.collapse_to(cursor, goal);
 8352            });
 8353        })
 8354    }
 8355
 8356    pub fn move_down_by_lines(
 8357        &mut self,
 8358        action: &MoveDownByLines,
 8359        window: &mut Window,
 8360        cx: &mut Context<Self>,
 8361    ) {
 8362        if self.take_rename(true, window, cx).is_some() {
 8363            return;
 8364        }
 8365
 8366        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8367            cx.propagate();
 8368            return;
 8369        }
 8370
 8371        let text_layout_details = &self.text_layout_details(window);
 8372
 8373        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8374            let line_mode = s.line_mode;
 8375            s.move_with(|map, selection| {
 8376                if !selection.is_empty() && !line_mode {
 8377                    selection.goal = SelectionGoal::None;
 8378                }
 8379                let (cursor, goal) = movement::down_by_rows(
 8380                    map,
 8381                    selection.start,
 8382                    action.lines,
 8383                    selection.goal,
 8384                    false,
 8385                    text_layout_details,
 8386                );
 8387                selection.collapse_to(cursor, goal);
 8388            });
 8389        })
 8390    }
 8391
 8392    pub fn select_down_by_lines(
 8393        &mut self,
 8394        action: &SelectDownByLines,
 8395        window: &mut Window,
 8396        cx: &mut Context<Self>,
 8397    ) {
 8398        let text_layout_details = &self.text_layout_details(window);
 8399        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8400            s.move_heads_with(|map, head, goal| {
 8401                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8402            })
 8403        })
 8404    }
 8405
 8406    pub fn select_up_by_lines(
 8407        &mut self,
 8408        action: &SelectUpByLines,
 8409        window: &mut Window,
 8410        cx: &mut Context<Self>,
 8411    ) {
 8412        let text_layout_details = &self.text_layout_details(window);
 8413        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8414            s.move_heads_with(|map, head, goal| {
 8415                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8416            })
 8417        })
 8418    }
 8419
 8420    pub fn select_page_up(
 8421        &mut self,
 8422        _: &SelectPageUp,
 8423        window: &mut Window,
 8424        cx: &mut Context<Self>,
 8425    ) {
 8426        let Some(row_count) = self.visible_row_count() else {
 8427            return;
 8428        };
 8429
 8430        let text_layout_details = &self.text_layout_details(window);
 8431
 8432        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8433            s.move_heads_with(|map, head, goal| {
 8434                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8435            })
 8436        })
 8437    }
 8438
 8439    pub fn move_page_up(
 8440        &mut self,
 8441        action: &MovePageUp,
 8442        window: &mut Window,
 8443        cx: &mut Context<Self>,
 8444    ) {
 8445        if self.take_rename(true, window, cx).is_some() {
 8446            return;
 8447        }
 8448
 8449        if self
 8450            .context_menu
 8451            .borrow_mut()
 8452            .as_mut()
 8453            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8454            .unwrap_or(false)
 8455        {
 8456            return;
 8457        }
 8458
 8459        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8460            cx.propagate();
 8461            return;
 8462        }
 8463
 8464        let Some(row_count) = self.visible_row_count() else {
 8465            return;
 8466        };
 8467
 8468        let autoscroll = if action.center_cursor {
 8469            Autoscroll::center()
 8470        } else {
 8471            Autoscroll::fit()
 8472        };
 8473
 8474        let text_layout_details = &self.text_layout_details(window);
 8475
 8476        self.change_selections(Some(autoscroll), window, cx, |s| {
 8477            let line_mode = s.line_mode;
 8478            s.move_with(|map, selection| {
 8479                if !selection.is_empty() && !line_mode {
 8480                    selection.goal = SelectionGoal::None;
 8481                }
 8482                let (cursor, goal) = movement::up_by_rows(
 8483                    map,
 8484                    selection.end,
 8485                    row_count,
 8486                    selection.goal,
 8487                    false,
 8488                    text_layout_details,
 8489                );
 8490                selection.collapse_to(cursor, goal);
 8491            });
 8492        });
 8493    }
 8494
 8495    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8496        let text_layout_details = &self.text_layout_details(window);
 8497        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8498            s.move_heads_with(|map, head, goal| {
 8499                movement::up(map, head, goal, false, text_layout_details)
 8500            })
 8501        })
 8502    }
 8503
 8504    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8505        self.take_rename(true, window, cx);
 8506
 8507        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8508            cx.propagate();
 8509            return;
 8510        }
 8511
 8512        let text_layout_details = &self.text_layout_details(window);
 8513        let selection_count = self.selections.count();
 8514        let first_selection = self.selections.first_anchor();
 8515
 8516        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8517            let line_mode = s.line_mode;
 8518            s.move_with(|map, selection| {
 8519                if !selection.is_empty() && !line_mode {
 8520                    selection.goal = SelectionGoal::None;
 8521                }
 8522                let (cursor, goal) = movement::down(
 8523                    map,
 8524                    selection.end,
 8525                    selection.goal,
 8526                    false,
 8527                    text_layout_details,
 8528                );
 8529                selection.collapse_to(cursor, goal);
 8530            });
 8531        });
 8532
 8533        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8534        {
 8535            cx.propagate();
 8536        }
 8537    }
 8538
 8539    pub fn select_page_down(
 8540        &mut self,
 8541        _: &SelectPageDown,
 8542        window: &mut Window,
 8543        cx: &mut Context<Self>,
 8544    ) {
 8545        let Some(row_count) = self.visible_row_count() else {
 8546            return;
 8547        };
 8548
 8549        let text_layout_details = &self.text_layout_details(window);
 8550
 8551        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8552            s.move_heads_with(|map, head, goal| {
 8553                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8554            })
 8555        })
 8556    }
 8557
 8558    pub fn move_page_down(
 8559        &mut self,
 8560        action: &MovePageDown,
 8561        window: &mut Window,
 8562        cx: &mut Context<Self>,
 8563    ) {
 8564        if self.take_rename(true, window, cx).is_some() {
 8565            return;
 8566        }
 8567
 8568        if self
 8569            .context_menu
 8570            .borrow_mut()
 8571            .as_mut()
 8572            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8573            .unwrap_or(false)
 8574        {
 8575            return;
 8576        }
 8577
 8578        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8579            cx.propagate();
 8580            return;
 8581        }
 8582
 8583        let Some(row_count) = self.visible_row_count() else {
 8584            return;
 8585        };
 8586
 8587        let autoscroll = if action.center_cursor {
 8588            Autoscroll::center()
 8589        } else {
 8590            Autoscroll::fit()
 8591        };
 8592
 8593        let text_layout_details = &self.text_layout_details(window);
 8594        self.change_selections(Some(autoscroll), window, cx, |s| {
 8595            let line_mode = s.line_mode;
 8596            s.move_with(|map, selection| {
 8597                if !selection.is_empty() && !line_mode {
 8598                    selection.goal = SelectionGoal::None;
 8599                }
 8600                let (cursor, goal) = movement::down_by_rows(
 8601                    map,
 8602                    selection.end,
 8603                    row_count,
 8604                    selection.goal,
 8605                    false,
 8606                    text_layout_details,
 8607                );
 8608                selection.collapse_to(cursor, goal);
 8609            });
 8610        });
 8611    }
 8612
 8613    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8614        let text_layout_details = &self.text_layout_details(window);
 8615        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8616            s.move_heads_with(|map, head, goal| {
 8617                movement::down(map, head, goal, false, text_layout_details)
 8618            })
 8619        });
 8620    }
 8621
 8622    pub fn context_menu_first(
 8623        &mut self,
 8624        _: &ContextMenuFirst,
 8625        _window: &mut Window,
 8626        cx: &mut Context<Self>,
 8627    ) {
 8628        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8629            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8630        }
 8631    }
 8632
 8633    pub fn context_menu_prev(
 8634        &mut self,
 8635        _: &ContextMenuPrev,
 8636        _window: &mut Window,
 8637        cx: &mut Context<Self>,
 8638    ) {
 8639        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8640            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8641        }
 8642    }
 8643
 8644    pub fn context_menu_next(
 8645        &mut self,
 8646        _: &ContextMenuNext,
 8647        _window: &mut Window,
 8648        cx: &mut Context<Self>,
 8649    ) {
 8650        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8651            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8652        }
 8653    }
 8654
 8655    pub fn context_menu_last(
 8656        &mut self,
 8657        _: &ContextMenuLast,
 8658        _window: &mut Window,
 8659        cx: &mut Context<Self>,
 8660    ) {
 8661        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8662            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8663        }
 8664    }
 8665
 8666    pub fn move_to_previous_word_start(
 8667        &mut self,
 8668        _: &MoveToPreviousWordStart,
 8669        window: &mut Window,
 8670        cx: &mut Context<Self>,
 8671    ) {
 8672        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8673            s.move_cursors_with(|map, head, _| {
 8674                (
 8675                    movement::previous_word_start(map, head),
 8676                    SelectionGoal::None,
 8677                )
 8678            });
 8679        })
 8680    }
 8681
 8682    pub fn move_to_previous_subword_start(
 8683        &mut self,
 8684        _: &MoveToPreviousSubwordStart,
 8685        window: &mut Window,
 8686        cx: &mut Context<Self>,
 8687    ) {
 8688        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8689            s.move_cursors_with(|map, head, _| {
 8690                (
 8691                    movement::previous_subword_start(map, head),
 8692                    SelectionGoal::None,
 8693                )
 8694            });
 8695        })
 8696    }
 8697
 8698    pub fn select_to_previous_word_start(
 8699        &mut self,
 8700        _: &SelectToPreviousWordStart,
 8701        window: &mut Window,
 8702        cx: &mut Context<Self>,
 8703    ) {
 8704        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8705            s.move_heads_with(|map, head, _| {
 8706                (
 8707                    movement::previous_word_start(map, head),
 8708                    SelectionGoal::None,
 8709                )
 8710            });
 8711        })
 8712    }
 8713
 8714    pub fn select_to_previous_subword_start(
 8715        &mut self,
 8716        _: &SelectToPreviousSubwordStart,
 8717        window: &mut Window,
 8718        cx: &mut Context<Self>,
 8719    ) {
 8720        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8721            s.move_heads_with(|map, head, _| {
 8722                (
 8723                    movement::previous_subword_start(map, head),
 8724                    SelectionGoal::None,
 8725                )
 8726            });
 8727        })
 8728    }
 8729
 8730    pub fn delete_to_previous_word_start(
 8731        &mut self,
 8732        action: &DeleteToPreviousWordStart,
 8733        window: &mut Window,
 8734        cx: &mut Context<Self>,
 8735    ) {
 8736        self.transact(window, cx, |this, window, cx| {
 8737            this.select_autoclose_pair(window, cx);
 8738            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8739                let line_mode = s.line_mode;
 8740                s.move_with(|map, selection| {
 8741                    if selection.is_empty() && !line_mode {
 8742                        let cursor = if action.ignore_newlines {
 8743                            movement::previous_word_start(map, selection.head())
 8744                        } else {
 8745                            movement::previous_word_start_or_newline(map, selection.head())
 8746                        };
 8747                        selection.set_head(cursor, SelectionGoal::None);
 8748                    }
 8749                });
 8750            });
 8751            this.insert("", window, cx);
 8752        });
 8753    }
 8754
 8755    pub fn delete_to_previous_subword_start(
 8756        &mut self,
 8757        _: &DeleteToPreviousSubwordStart,
 8758        window: &mut Window,
 8759        cx: &mut Context<Self>,
 8760    ) {
 8761        self.transact(window, cx, |this, window, cx| {
 8762            this.select_autoclose_pair(window, cx);
 8763            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8764                let line_mode = s.line_mode;
 8765                s.move_with(|map, selection| {
 8766                    if selection.is_empty() && !line_mode {
 8767                        let cursor = movement::previous_subword_start(map, selection.head());
 8768                        selection.set_head(cursor, SelectionGoal::None);
 8769                    }
 8770                });
 8771            });
 8772            this.insert("", window, cx);
 8773        });
 8774    }
 8775
 8776    pub fn move_to_next_word_end(
 8777        &mut self,
 8778        _: &MoveToNextWordEnd,
 8779        window: &mut Window,
 8780        cx: &mut Context<Self>,
 8781    ) {
 8782        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8783            s.move_cursors_with(|map, head, _| {
 8784                (movement::next_word_end(map, head), SelectionGoal::None)
 8785            });
 8786        })
 8787    }
 8788
 8789    pub fn move_to_next_subword_end(
 8790        &mut self,
 8791        _: &MoveToNextSubwordEnd,
 8792        window: &mut Window,
 8793        cx: &mut Context<Self>,
 8794    ) {
 8795        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8796            s.move_cursors_with(|map, head, _| {
 8797                (movement::next_subword_end(map, head), SelectionGoal::None)
 8798            });
 8799        })
 8800    }
 8801
 8802    pub fn select_to_next_word_end(
 8803        &mut self,
 8804        _: &SelectToNextWordEnd,
 8805        window: &mut Window,
 8806        cx: &mut Context<Self>,
 8807    ) {
 8808        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8809            s.move_heads_with(|map, head, _| {
 8810                (movement::next_word_end(map, head), SelectionGoal::None)
 8811            });
 8812        })
 8813    }
 8814
 8815    pub fn select_to_next_subword_end(
 8816        &mut self,
 8817        _: &SelectToNextSubwordEnd,
 8818        window: &mut Window,
 8819        cx: &mut Context<Self>,
 8820    ) {
 8821        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8822            s.move_heads_with(|map, head, _| {
 8823                (movement::next_subword_end(map, head), SelectionGoal::None)
 8824            });
 8825        })
 8826    }
 8827
 8828    pub fn delete_to_next_word_end(
 8829        &mut self,
 8830        action: &DeleteToNextWordEnd,
 8831        window: &mut Window,
 8832        cx: &mut Context<Self>,
 8833    ) {
 8834        self.transact(window, cx, |this, window, cx| {
 8835            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8836                let line_mode = s.line_mode;
 8837                s.move_with(|map, selection| {
 8838                    if selection.is_empty() && !line_mode {
 8839                        let cursor = if action.ignore_newlines {
 8840                            movement::next_word_end(map, selection.head())
 8841                        } else {
 8842                            movement::next_word_end_or_newline(map, selection.head())
 8843                        };
 8844                        selection.set_head(cursor, SelectionGoal::None);
 8845                    }
 8846                });
 8847            });
 8848            this.insert("", window, cx);
 8849        });
 8850    }
 8851
 8852    pub fn delete_to_next_subword_end(
 8853        &mut self,
 8854        _: &DeleteToNextSubwordEnd,
 8855        window: &mut Window,
 8856        cx: &mut Context<Self>,
 8857    ) {
 8858        self.transact(window, cx, |this, window, cx| {
 8859            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8860                s.move_with(|map, selection| {
 8861                    if selection.is_empty() {
 8862                        let cursor = movement::next_subword_end(map, selection.head());
 8863                        selection.set_head(cursor, SelectionGoal::None);
 8864                    }
 8865                });
 8866            });
 8867            this.insert("", window, cx);
 8868        });
 8869    }
 8870
 8871    pub fn move_to_beginning_of_line(
 8872        &mut self,
 8873        action: &MoveToBeginningOfLine,
 8874        window: &mut Window,
 8875        cx: &mut Context<Self>,
 8876    ) {
 8877        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8878            s.move_cursors_with(|map, head, _| {
 8879                (
 8880                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8881                    SelectionGoal::None,
 8882                )
 8883            });
 8884        })
 8885    }
 8886
 8887    pub fn select_to_beginning_of_line(
 8888        &mut self,
 8889        action: &SelectToBeginningOfLine,
 8890        window: &mut Window,
 8891        cx: &mut Context<Self>,
 8892    ) {
 8893        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8894            s.move_heads_with(|map, head, _| {
 8895                (
 8896                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8897                    SelectionGoal::None,
 8898                )
 8899            });
 8900        });
 8901    }
 8902
 8903    pub fn delete_to_beginning_of_line(
 8904        &mut self,
 8905        _: &DeleteToBeginningOfLine,
 8906        window: &mut Window,
 8907        cx: &mut Context<Self>,
 8908    ) {
 8909        self.transact(window, cx, |this, window, cx| {
 8910            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8911                s.move_with(|_, selection| {
 8912                    selection.reversed = true;
 8913                });
 8914            });
 8915
 8916            this.select_to_beginning_of_line(
 8917                &SelectToBeginningOfLine {
 8918                    stop_at_soft_wraps: false,
 8919                },
 8920                window,
 8921                cx,
 8922            );
 8923            this.backspace(&Backspace, window, cx);
 8924        });
 8925    }
 8926
 8927    pub fn move_to_end_of_line(
 8928        &mut self,
 8929        action: &MoveToEndOfLine,
 8930        window: &mut Window,
 8931        cx: &mut Context<Self>,
 8932    ) {
 8933        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8934            s.move_cursors_with(|map, head, _| {
 8935                (
 8936                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8937                    SelectionGoal::None,
 8938                )
 8939            });
 8940        })
 8941    }
 8942
 8943    pub fn select_to_end_of_line(
 8944        &mut self,
 8945        action: &SelectToEndOfLine,
 8946        window: &mut Window,
 8947        cx: &mut Context<Self>,
 8948    ) {
 8949        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8950            s.move_heads_with(|map, head, _| {
 8951                (
 8952                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8953                    SelectionGoal::None,
 8954                )
 8955            });
 8956        })
 8957    }
 8958
 8959    pub fn delete_to_end_of_line(
 8960        &mut self,
 8961        _: &DeleteToEndOfLine,
 8962        window: &mut Window,
 8963        cx: &mut Context<Self>,
 8964    ) {
 8965        self.transact(window, cx, |this, window, cx| {
 8966            this.select_to_end_of_line(
 8967                &SelectToEndOfLine {
 8968                    stop_at_soft_wraps: false,
 8969                },
 8970                window,
 8971                cx,
 8972            );
 8973            this.delete(&Delete, window, cx);
 8974        });
 8975    }
 8976
 8977    pub fn cut_to_end_of_line(
 8978        &mut self,
 8979        _: &CutToEndOfLine,
 8980        window: &mut Window,
 8981        cx: &mut Context<Self>,
 8982    ) {
 8983        self.transact(window, cx, |this, window, cx| {
 8984            this.select_to_end_of_line(
 8985                &SelectToEndOfLine {
 8986                    stop_at_soft_wraps: false,
 8987                },
 8988                window,
 8989                cx,
 8990            );
 8991            this.cut(&Cut, window, cx);
 8992        });
 8993    }
 8994
 8995    pub fn move_to_start_of_paragraph(
 8996        &mut self,
 8997        _: &MoveToStartOfParagraph,
 8998        window: &mut Window,
 8999        cx: &mut Context<Self>,
 9000    ) {
 9001        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9002            cx.propagate();
 9003            return;
 9004        }
 9005
 9006        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9007            s.move_with(|map, selection| {
 9008                selection.collapse_to(
 9009                    movement::start_of_paragraph(map, selection.head(), 1),
 9010                    SelectionGoal::None,
 9011                )
 9012            });
 9013        })
 9014    }
 9015
 9016    pub fn move_to_end_of_paragraph(
 9017        &mut self,
 9018        _: &MoveToEndOfParagraph,
 9019        window: &mut Window,
 9020        cx: &mut Context<Self>,
 9021    ) {
 9022        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9023            cx.propagate();
 9024            return;
 9025        }
 9026
 9027        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9028            s.move_with(|map, selection| {
 9029                selection.collapse_to(
 9030                    movement::end_of_paragraph(map, selection.head(), 1),
 9031                    SelectionGoal::None,
 9032                )
 9033            });
 9034        })
 9035    }
 9036
 9037    pub fn select_to_start_of_paragraph(
 9038        &mut self,
 9039        _: &SelectToStartOfParagraph,
 9040        window: &mut Window,
 9041        cx: &mut Context<Self>,
 9042    ) {
 9043        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9044            cx.propagate();
 9045            return;
 9046        }
 9047
 9048        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9049            s.move_heads_with(|map, head, _| {
 9050                (
 9051                    movement::start_of_paragraph(map, head, 1),
 9052                    SelectionGoal::None,
 9053                )
 9054            });
 9055        })
 9056    }
 9057
 9058    pub fn select_to_end_of_paragraph(
 9059        &mut self,
 9060        _: &SelectToEndOfParagraph,
 9061        window: &mut Window,
 9062        cx: &mut Context<Self>,
 9063    ) {
 9064        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9065            cx.propagate();
 9066            return;
 9067        }
 9068
 9069        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9070            s.move_heads_with(|map, head, _| {
 9071                (
 9072                    movement::end_of_paragraph(map, head, 1),
 9073                    SelectionGoal::None,
 9074                )
 9075            });
 9076        })
 9077    }
 9078
 9079    pub fn move_to_beginning(
 9080        &mut self,
 9081        _: &MoveToBeginning,
 9082        window: &mut Window,
 9083        cx: &mut Context<Self>,
 9084    ) {
 9085        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9086            cx.propagate();
 9087            return;
 9088        }
 9089
 9090        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9091            s.select_ranges(vec![0..0]);
 9092        });
 9093    }
 9094
 9095    pub fn select_to_beginning(
 9096        &mut self,
 9097        _: &SelectToBeginning,
 9098        window: &mut Window,
 9099        cx: &mut Context<Self>,
 9100    ) {
 9101        let mut selection = self.selections.last::<Point>(cx);
 9102        selection.set_head(Point::zero(), SelectionGoal::None);
 9103
 9104        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9105            s.select(vec![selection]);
 9106        });
 9107    }
 9108
 9109    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9110        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9111            cx.propagate();
 9112            return;
 9113        }
 9114
 9115        let cursor = self.buffer.read(cx).read(cx).len();
 9116        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9117            s.select_ranges(vec![cursor..cursor])
 9118        });
 9119    }
 9120
 9121    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9122        self.nav_history = nav_history;
 9123    }
 9124
 9125    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9126        self.nav_history.as_ref()
 9127    }
 9128
 9129    fn push_to_nav_history(
 9130        &mut self,
 9131        cursor_anchor: Anchor,
 9132        new_position: Option<Point>,
 9133        cx: &mut Context<Self>,
 9134    ) {
 9135        if let Some(nav_history) = self.nav_history.as_mut() {
 9136            let buffer = self.buffer.read(cx).read(cx);
 9137            let cursor_position = cursor_anchor.to_point(&buffer);
 9138            let scroll_state = self.scroll_manager.anchor();
 9139            let scroll_top_row = scroll_state.top_row(&buffer);
 9140            drop(buffer);
 9141
 9142            if let Some(new_position) = new_position {
 9143                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9144                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9145                    return;
 9146                }
 9147            }
 9148
 9149            nav_history.push(
 9150                Some(NavigationData {
 9151                    cursor_anchor,
 9152                    cursor_position,
 9153                    scroll_anchor: scroll_state,
 9154                    scroll_top_row,
 9155                }),
 9156                cx,
 9157            );
 9158        }
 9159    }
 9160
 9161    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9162        let buffer = self.buffer.read(cx).snapshot(cx);
 9163        let mut selection = self.selections.first::<usize>(cx);
 9164        selection.set_head(buffer.len(), SelectionGoal::None);
 9165        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9166            s.select(vec![selection]);
 9167        });
 9168    }
 9169
 9170    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9171        let end = self.buffer.read(cx).read(cx).len();
 9172        self.change_selections(None, window, cx, |s| {
 9173            s.select_ranges(vec![0..end]);
 9174        });
 9175    }
 9176
 9177    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9178        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9179        let mut selections = self.selections.all::<Point>(cx);
 9180        let max_point = display_map.buffer_snapshot.max_point();
 9181        for selection in &mut selections {
 9182            let rows = selection.spanned_rows(true, &display_map);
 9183            selection.start = Point::new(rows.start.0, 0);
 9184            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9185            selection.reversed = false;
 9186        }
 9187        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9188            s.select(selections);
 9189        });
 9190    }
 9191
 9192    pub fn split_selection_into_lines(
 9193        &mut self,
 9194        _: &SplitSelectionIntoLines,
 9195        window: &mut Window,
 9196        cx: &mut Context<Self>,
 9197    ) {
 9198        let selections = self
 9199            .selections
 9200            .all::<Point>(cx)
 9201            .into_iter()
 9202            .map(|selection| selection.start..selection.end)
 9203            .collect::<Vec<_>>();
 9204        self.unfold_ranges(&selections, true, true, cx);
 9205
 9206        let mut new_selection_ranges = Vec::new();
 9207        {
 9208            let buffer = self.buffer.read(cx).read(cx);
 9209            for selection in selections {
 9210                for row in selection.start.row..selection.end.row {
 9211                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9212                    new_selection_ranges.push(cursor..cursor);
 9213                }
 9214
 9215                let is_multiline_selection = selection.start.row != selection.end.row;
 9216                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9217                // so this action feels more ergonomic when paired with other selection operations
 9218                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9219                if !should_skip_last {
 9220                    new_selection_ranges.push(selection.end..selection.end);
 9221                }
 9222            }
 9223        }
 9224        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9225            s.select_ranges(new_selection_ranges);
 9226        });
 9227    }
 9228
 9229    pub fn add_selection_above(
 9230        &mut self,
 9231        _: &AddSelectionAbove,
 9232        window: &mut Window,
 9233        cx: &mut Context<Self>,
 9234    ) {
 9235        self.add_selection(true, window, cx);
 9236    }
 9237
 9238    pub fn add_selection_below(
 9239        &mut self,
 9240        _: &AddSelectionBelow,
 9241        window: &mut Window,
 9242        cx: &mut Context<Self>,
 9243    ) {
 9244        self.add_selection(false, window, cx);
 9245    }
 9246
 9247    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9248        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9249        let mut selections = self.selections.all::<Point>(cx);
 9250        let text_layout_details = self.text_layout_details(window);
 9251        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9252            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9253            let range = oldest_selection.display_range(&display_map).sorted();
 9254
 9255            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9256            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9257            let positions = start_x.min(end_x)..start_x.max(end_x);
 9258
 9259            selections.clear();
 9260            let mut stack = Vec::new();
 9261            for row in range.start.row().0..=range.end.row().0 {
 9262                if let Some(selection) = self.selections.build_columnar_selection(
 9263                    &display_map,
 9264                    DisplayRow(row),
 9265                    &positions,
 9266                    oldest_selection.reversed,
 9267                    &text_layout_details,
 9268                ) {
 9269                    stack.push(selection.id);
 9270                    selections.push(selection);
 9271                }
 9272            }
 9273
 9274            if above {
 9275                stack.reverse();
 9276            }
 9277
 9278            AddSelectionsState { above, stack }
 9279        });
 9280
 9281        let last_added_selection = *state.stack.last().unwrap();
 9282        let mut new_selections = Vec::new();
 9283        if above == state.above {
 9284            let end_row = if above {
 9285                DisplayRow(0)
 9286            } else {
 9287                display_map.max_point().row()
 9288            };
 9289
 9290            'outer: for selection in selections {
 9291                if selection.id == last_added_selection {
 9292                    let range = selection.display_range(&display_map).sorted();
 9293                    debug_assert_eq!(range.start.row(), range.end.row());
 9294                    let mut row = range.start.row();
 9295                    let positions =
 9296                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9297                            px(start)..px(end)
 9298                        } else {
 9299                            let start_x =
 9300                                display_map.x_for_display_point(range.start, &text_layout_details);
 9301                            let end_x =
 9302                                display_map.x_for_display_point(range.end, &text_layout_details);
 9303                            start_x.min(end_x)..start_x.max(end_x)
 9304                        };
 9305
 9306                    while row != end_row {
 9307                        if above {
 9308                            row.0 -= 1;
 9309                        } else {
 9310                            row.0 += 1;
 9311                        }
 9312
 9313                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9314                            &display_map,
 9315                            row,
 9316                            &positions,
 9317                            selection.reversed,
 9318                            &text_layout_details,
 9319                        ) {
 9320                            state.stack.push(new_selection.id);
 9321                            if above {
 9322                                new_selections.push(new_selection);
 9323                                new_selections.push(selection);
 9324                            } else {
 9325                                new_selections.push(selection);
 9326                                new_selections.push(new_selection);
 9327                            }
 9328
 9329                            continue 'outer;
 9330                        }
 9331                    }
 9332                }
 9333
 9334                new_selections.push(selection);
 9335            }
 9336        } else {
 9337            new_selections = selections;
 9338            new_selections.retain(|s| s.id != last_added_selection);
 9339            state.stack.pop();
 9340        }
 9341
 9342        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9343            s.select(new_selections);
 9344        });
 9345        if state.stack.len() > 1 {
 9346            self.add_selections_state = Some(state);
 9347        }
 9348    }
 9349
 9350    pub fn select_next_match_internal(
 9351        &mut self,
 9352        display_map: &DisplaySnapshot,
 9353        replace_newest: bool,
 9354        autoscroll: Option<Autoscroll>,
 9355        window: &mut Window,
 9356        cx: &mut Context<Self>,
 9357    ) -> Result<()> {
 9358        fn select_next_match_ranges(
 9359            this: &mut Editor,
 9360            range: Range<usize>,
 9361            replace_newest: bool,
 9362            auto_scroll: Option<Autoscroll>,
 9363            window: &mut Window,
 9364            cx: &mut Context<Editor>,
 9365        ) {
 9366            this.unfold_ranges(&[range.clone()], false, true, cx);
 9367            this.change_selections(auto_scroll, window, cx, |s| {
 9368                if replace_newest {
 9369                    s.delete(s.newest_anchor().id);
 9370                }
 9371                s.insert_range(range.clone());
 9372            });
 9373        }
 9374
 9375        let buffer = &display_map.buffer_snapshot;
 9376        let mut selections = self.selections.all::<usize>(cx);
 9377        if let Some(mut select_next_state) = self.select_next_state.take() {
 9378            let query = &select_next_state.query;
 9379            if !select_next_state.done {
 9380                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9381                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9382                let mut next_selected_range = None;
 9383
 9384                let bytes_after_last_selection =
 9385                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9386                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9387                let query_matches = query
 9388                    .stream_find_iter(bytes_after_last_selection)
 9389                    .map(|result| (last_selection.end, result))
 9390                    .chain(
 9391                        query
 9392                            .stream_find_iter(bytes_before_first_selection)
 9393                            .map(|result| (0, result)),
 9394                    );
 9395
 9396                for (start_offset, query_match) in query_matches {
 9397                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9398                    let offset_range =
 9399                        start_offset + query_match.start()..start_offset + query_match.end();
 9400                    let display_range = offset_range.start.to_display_point(display_map)
 9401                        ..offset_range.end.to_display_point(display_map);
 9402
 9403                    if !select_next_state.wordwise
 9404                        || (!movement::is_inside_word(display_map, display_range.start)
 9405                            && !movement::is_inside_word(display_map, display_range.end))
 9406                    {
 9407                        // TODO: This is n^2, because we might check all the selections
 9408                        if !selections
 9409                            .iter()
 9410                            .any(|selection| selection.range().overlaps(&offset_range))
 9411                        {
 9412                            next_selected_range = Some(offset_range);
 9413                            break;
 9414                        }
 9415                    }
 9416                }
 9417
 9418                if let Some(next_selected_range) = next_selected_range {
 9419                    select_next_match_ranges(
 9420                        self,
 9421                        next_selected_range,
 9422                        replace_newest,
 9423                        autoscroll,
 9424                        window,
 9425                        cx,
 9426                    );
 9427                } else {
 9428                    select_next_state.done = true;
 9429                }
 9430            }
 9431
 9432            self.select_next_state = Some(select_next_state);
 9433        } else {
 9434            let mut only_carets = true;
 9435            let mut same_text_selected = true;
 9436            let mut selected_text = None;
 9437
 9438            let mut selections_iter = selections.iter().peekable();
 9439            while let Some(selection) = selections_iter.next() {
 9440                if selection.start != selection.end {
 9441                    only_carets = false;
 9442                }
 9443
 9444                if same_text_selected {
 9445                    if selected_text.is_none() {
 9446                        selected_text =
 9447                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9448                    }
 9449
 9450                    if let Some(next_selection) = selections_iter.peek() {
 9451                        if next_selection.range().len() == selection.range().len() {
 9452                            let next_selected_text = buffer
 9453                                .text_for_range(next_selection.range())
 9454                                .collect::<String>();
 9455                            if Some(next_selected_text) != selected_text {
 9456                                same_text_selected = false;
 9457                                selected_text = None;
 9458                            }
 9459                        } else {
 9460                            same_text_selected = false;
 9461                            selected_text = None;
 9462                        }
 9463                    }
 9464                }
 9465            }
 9466
 9467            if only_carets {
 9468                for selection in &mut selections {
 9469                    let word_range = movement::surrounding_word(
 9470                        display_map,
 9471                        selection.start.to_display_point(display_map),
 9472                    );
 9473                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9474                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9475                    selection.goal = SelectionGoal::None;
 9476                    selection.reversed = false;
 9477                    select_next_match_ranges(
 9478                        self,
 9479                        selection.start..selection.end,
 9480                        replace_newest,
 9481                        autoscroll,
 9482                        window,
 9483                        cx,
 9484                    );
 9485                }
 9486
 9487                if selections.len() == 1 {
 9488                    let selection = selections
 9489                        .last()
 9490                        .expect("ensured that there's only one selection");
 9491                    let query = buffer
 9492                        .text_for_range(selection.start..selection.end)
 9493                        .collect::<String>();
 9494                    let is_empty = query.is_empty();
 9495                    let select_state = SelectNextState {
 9496                        query: AhoCorasick::new(&[query])?,
 9497                        wordwise: true,
 9498                        done: is_empty,
 9499                    };
 9500                    self.select_next_state = Some(select_state);
 9501                } else {
 9502                    self.select_next_state = None;
 9503                }
 9504            } else if let Some(selected_text) = selected_text {
 9505                self.select_next_state = Some(SelectNextState {
 9506                    query: AhoCorasick::new(&[selected_text])?,
 9507                    wordwise: false,
 9508                    done: false,
 9509                });
 9510                self.select_next_match_internal(
 9511                    display_map,
 9512                    replace_newest,
 9513                    autoscroll,
 9514                    window,
 9515                    cx,
 9516                )?;
 9517            }
 9518        }
 9519        Ok(())
 9520    }
 9521
 9522    pub fn select_all_matches(
 9523        &mut self,
 9524        _action: &SelectAllMatches,
 9525        window: &mut Window,
 9526        cx: &mut Context<Self>,
 9527    ) -> Result<()> {
 9528        self.push_to_selection_history();
 9529        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9530
 9531        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9532        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9533            return Ok(());
 9534        };
 9535        if select_next_state.done {
 9536            return Ok(());
 9537        }
 9538
 9539        let mut new_selections = self.selections.all::<usize>(cx);
 9540
 9541        let buffer = &display_map.buffer_snapshot;
 9542        let query_matches = select_next_state
 9543            .query
 9544            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9545
 9546        for query_match in query_matches {
 9547            let query_match = query_match.unwrap(); // can only fail due to I/O
 9548            let offset_range = query_match.start()..query_match.end();
 9549            let display_range = offset_range.start.to_display_point(&display_map)
 9550                ..offset_range.end.to_display_point(&display_map);
 9551
 9552            if !select_next_state.wordwise
 9553                || (!movement::is_inside_word(&display_map, display_range.start)
 9554                    && !movement::is_inside_word(&display_map, display_range.end))
 9555            {
 9556                self.selections.change_with(cx, |selections| {
 9557                    new_selections.push(Selection {
 9558                        id: selections.new_selection_id(),
 9559                        start: offset_range.start,
 9560                        end: offset_range.end,
 9561                        reversed: false,
 9562                        goal: SelectionGoal::None,
 9563                    });
 9564                });
 9565            }
 9566        }
 9567
 9568        new_selections.sort_by_key(|selection| selection.start);
 9569        let mut ix = 0;
 9570        while ix + 1 < new_selections.len() {
 9571            let current_selection = &new_selections[ix];
 9572            let next_selection = &new_selections[ix + 1];
 9573            if current_selection.range().overlaps(&next_selection.range()) {
 9574                if current_selection.id < next_selection.id {
 9575                    new_selections.remove(ix + 1);
 9576                } else {
 9577                    new_selections.remove(ix);
 9578                }
 9579            } else {
 9580                ix += 1;
 9581            }
 9582        }
 9583
 9584        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9585
 9586        for selection in new_selections.iter_mut() {
 9587            selection.reversed = reversed;
 9588        }
 9589
 9590        select_next_state.done = true;
 9591        self.unfold_ranges(
 9592            &new_selections
 9593                .iter()
 9594                .map(|selection| selection.range())
 9595                .collect::<Vec<_>>(),
 9596            false,
 9597            false,
 9598            cx,
 9599        );
 9600        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9601            selections.select(new_selections)
 9602        });
 9603
 9604        Ok(())
 9605    }
 9606
 9607    pub fn select_next(
 9608        &mut self,
 9609        action: &SelectNext,
 9610        window: &mut Window,
 9611        cx: &mut Context<Self>,
 9612    ) -> Result<()> {
 9613        self.push_to_selection_history();
 9614        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9615        self.select_next_match_internal(
 9616            &display_map,
 9617            action.replace_newest,
 9618            Some(Autoscroll::newest()),
 9619            window,
 9620            cx,
 9621        )?;
 9622        Ok(())
 9623    }
 9624
 9625    pub fn select_previous(
 9626        &mut self,
 9627        action: &SelectPrevious,
 9628        window: &mut Window,
 9629        cx: &mut Context<Self>,
 9630    ) -> Result<()> {
 9631        self.push_to_selection_history();
 9632        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9633        let buffer = &display_map.buffer_snapshot;
 9634        let mut selections = self.selections.all::<usize>(cx);
 9635        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9636            let query = &select_prev_state.query;
 9637            if !select_prev_state.done {
 9638                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9639                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9640                let mut next_selected_range = None;
 9641                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9642                let bytes_before_last_selection =
 9643                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9644                let bytes_after_first_selection =
 9645                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9646                let query_matches = query
 9647                    .stream_find_iter(bytes_before_last_selection)
 9648                    .map(|result| (last_selection.start, result))
 9649                    .chain(
 9650                        query
 9651                            .stream_find_iter(bytes_after_first_selection)
 9652                            .map(|result| (buffer.len(), result)),
 9653                    );
 9654                for (end_offset, query_match) in query_matches {
 9655                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9656                    let offset_range =
 9657                        end_offset - query_match.end()..end_offset - query_match.start();
 9658                    let display_range = offset_range.start.to_display_point(&display_map)
 9659                        ..offset_range.end.to_display_point(&display_map);
 9660
 9661                    if !select_prev_state.wordwise
 9662                        || (!movement::is_inside_word(&display_map, display_range.start)
 9663                            && !movement::is_inside_word(&display_map, display_range.end))
 9664                    {
 9665                        next_selected_range = Some(offset_range);
 9666                        break;
 9667                    }
 9668                }
 9669
 9670                if let Some(next_selected_range) = next_selected_range {
 9671                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9672                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9673                        if action.replace_newest {
 9674                            s.delete(s.newest_anchor().id);
 9675                        }
 9676                        s.insert_range(next_selected_range);
 9677                    });
 9678                } else {
 9679                    select_prev_state.done = true;
 9680                }
 9681            }
 9682
 9683            self.select_prev_state = Some(select_prev_state);
 9684        } else {
 9685            let mut only_carets = true;
 9686            let mut same_text_selected = true;
 9687            let mut selected_text = None;
 9688
 9689            let mut selections_iter = selections.iter().peekable();
 9690            while let Some(selection) = selections_iter.next() {
 9691                if selection.start != selection.end {
 9692                    only_carets = false;
 9693                }
 9694
 9695                if same_text_selected {
 9696                    if selected_text.is_none() {
 9697                        selected_text =
 9698                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9699                    }
 9700
 9701                    if let Some(next_selection) = selections_iter.peek() {
 9702                        if next_selection.range().len() == selection.range().len() {
 9703                            let next_selected_text = buffer
 9704                                .text_for_range(next_selection.range())
 9705                                .collect::<String>();
 9706                            if Some(next_selected_text) != selected_text {
 9707                                same_text_selected = false;
 9708                                selected_text = None;
 9709                            }
 9710                        } else {
 9711                            same_text_selected = false;
 9712                            selected_text = None;
 9713                        }
 9714                    }
 9715                }
 9716            }
 9717
 9718            if only_carets {
 9719                for selection in &mut selections {
 9720                    let word_range = movement::surrounding_word(
 9721                        &display_map,
 9722                        selection.start.to_display_point(&display_map),
 9723                    );
 9724                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9725                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9726                    selection.goal = SelectionGoal::None;
 9727                    selection.reversed = false;
 9728                }
 9729                if selections.len() == 1 {
 9730                    let selection = selections
 9731                        .last()
 9732                        .expect("ensured that there's only one selection");
 9733                    let query = buffer
 9734                        .text_for_range(selection.start..selection.end)
 9735                        .collect::<String>();
 9736                    let is_empty = query.is_empty();
 9737                    let select_state = SelectNextState {
 9738                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9739                        wordwise: true,
 9740                        done: is_empty,
 9741                    };
 9742                    self.select_prev_state = Some(select_state);
 9743                } else {
 9744                    self.select_prev_state = None;
 9745                }
 9746
 9747                self.unfold_ranges(
 9748                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9749                    false,
 9750                    true,
 9751                    cx,
 9752                );
 9753                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9754                    s.select(selections);
 9755                });
 9756            } else if let Some(selected_text) = selected_text {
 9757                self.select_prev_state = Some(SelectNextState {
 9758                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9759                    wordwise: false,
 9760                    done: false,
 9761                });
 9762                self.select_previous(action, window, cx)?;
 9763            }
 9764        }
 9765        Ok(())
 9766    }
 9767
 9768    pub fn toggle_comments(
 9769        &mut self,
 9770        action: &ToggleComments,
 9771        window: &mut Window,
 9772        cx: &mut Context<Self>,
 9773    ) {
 9774        if self.read_only(cx) {
 9775            return;
 9776        }
 9777        let text_layout_details = &self.text_layout_details(window);
 9778        self.transact(window, cx, |this, window, cx| {
 9779            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9780            let mut edits = Vec::new();
 9781            let mut selection_edit_ranges = Vec::new();
 9782            let mut last_toggled_row = None;
 9783            let snapshot = this.buffer.read(cx).read(cx);
 9784            let empty_str: Arc<str> = Arc::default();
 9785            let mut suffixes_inserted = Vec::new();
 9786            let ignore_indent = action.ignore_indent;
 9787
 9788            fn comment_prefix_range(
 9789                snapshot: &MultiBufferSnapshot,
 9790                row: MultiBufferRow,
 9791                comment_prefix: &str,
 9792                comment_prefix_whitespace: &str,
 9793                ignore_indent: bool,
 9794            ) -> Range<Point> {
 9795                let indent_size = if ignore_indent {
 9796                    0
 9797                } else {
 9798                    snapshot.indent_size_for_line(row).len
 9799                };
 9800
 9801                let start = Point::new(row.0, indent_size);
 9802
 9803                let mut line_bytes = snapshot
 9804                    .bytes_in_range(start..snapshot.max_point())
 9805                    .flatten()
 9806                    .copied();
 9807
 9808                // If this line currently begins with the line comment prefix, then record
 9809                // the range containing the prefix.
 9810                if line_bytes
 9811                    .by_ref()
 9812                    .take(comment_prefix.len())
 9813                    .eq(comment_prefix.bytes())
 9814                {
 9815                    // Include any whitespace that matches the comment prefix.
 9816                    let matching_whitespace_len = line_bytes
 9817                        .zip(comment_prefix_whitespace.bytes())
 9818                        .take_while(|(a, b)| a == b)
 9819                        .count() as u32;
 9820                    let end = Point::new(
 9821                        start.row,
 9822                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9823                    );
 9824                    start..end
 9825                } else {
 9826                    start..start
 9827                }
 9828            }
 9829
 9830            fn comment_suffix_range(
 9831                snapshot: &MultiBufferSnapshot,
 9832                row: MultiBufferRow,
 9833                comment_suffix: &str,
 9834                comment_suffix_has_leading_space: bool,
 9835            ) -> Range<Point> {
 9836                let end = Point::new(row.0, snapshot.line_len(row));
 9837                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9838
 9839                let mut line_end_bytes = snapshot
 9840                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9841                    .flatten()
 9842                    .copied();
 9843
 9844                let leading_space_len = if suffix_start_column > 0
 9845                    && line_end_bytes.next() == Some(b' ')
 9846                    && comment_suffix_has_leading_space
 9847                {
 9848                    1
 9849                } else {
 9850                    0
 9851                };
 9852
 9853                // If this line currently begins with the line comment prefix, then record
 9854                // the range containing the prefix.
 9855                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9856                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9857                    start..end
 9858                } else {
 9859                    end..end
 9860                }
 9861            }
 9862
 9863            // TODO: Handle selections that cross excerpts
 9864            for selection in &mut selections {
 9865                let start_column = snapshot
 9866                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9867                    .len;
 9868                let language = if let Some(language) =
 9869                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9870                {
 9871                    language
 9872                } else {
 9873                    continue;
 9874                };
 9875
 9876                selection_edit_ranges.clear();
 9877
 9878                // If multiple selections contain a given row, avoid processing that
 9879                // row more than once.
 9880                let mut start_row = MultiBufferRow(selection.start.row);
 9881                if last_toggled_row == Some(start_row) {
 9882                    start_row = start_row.next_row();
 9883                }
 9884                let end_row =
 9885                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9886                        MultiBufferRow(selection.end.row - 1)
 9887                    } else {
 9888                        MultiBufferRow(selection.end.row)
 9889                    };
 9890                last_toggled_row = Some(end_row);
 9891
 9892                if start_row > end_row {
 9893                    continue;
 9894                }
 9895
 9896                // If the language has line comments, toggle those.
 9897                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9898
 9899                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9900                if ignore_indent {
 9901                    full_comment_prefixes = full_comment_prefixes
 9902                        .into_iter()
 9903                        .map(|s| Arc::from(s.trim_end()))
 9904                        .collect();
 9905                }
 9906
 9907                if !full_comment_prefixes.is_empty() {
 9908                    let first_prefix = full_comment_prefixes
 9909                        .first()
 9910                        .expect("prefixes is non-empty");
 9911                    let prefix_trimmed_lengths = full_comment_prefixes
 9912                        .iter()
 9913                        .map(|p| p.trim_end_matches(' ').len())
 9914                        .collect::<SmallVec<[usize; 4]>>();
 9915
 9916                    let mut all_selection_lines_are_comments = true;
 9917
 9918                    for row in start_row.0..=end_row.0 {
 9919                        let row = MultiBufferRow(row);
 9920                        if start_row < end_row && snapshot.is_line_blank(row) {
 9921                            continue;
 9922                        }
 9923
 9924                        let prefix_range = full_comment_prefixes
 9925                            .iter()
 9926                            .zip(prefix_trimmed_lengths.iter().copied())
 9927                            .map(|(prefix, trimmed_prefix_len)| {
 9928                                comment_prefix_range(
 9929                                    snapshot.deref(),
 9930                                    row,
 9931                                    &prefix[..trimmed_prefix_len],
 9932                                    &prefix[trimmed_prefix_len..],
 9933                                    ignore_indent,
 9934                                )
 9935                            })
 9936                            .max_by_key(|range| range.end.column - range.start.column)
 9937                            .expect("prefixes is non-empty");
 9938
 9939                        if prefix_range.is_empty() {
 9940                            all_selection_lines_are_comments = false;
 9941                        }
 9942
 9943                        selection_edit_ranges.push(prefix_range);
 9944                    }
 9945
 9946                    if all_selection_lines_are_comments {
 9947                        edits.extend(
 9948                            selection_edit_ranges
 9949                                .iter()
 9950                                .cloned()
 9951                                .map(|range| (range, empty_str.clone())),
 9952                        );
 9953                    } else {
 9954                        let min_column = selection_edit_ranges
 9955                            .iter()
 9956                            .map(|range| range.start.column)
 9957                            .min()
 9958                            .unwrap_or(0);
 9959                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9960                            let position = Point::new(range.start.row, min_column);
 9961                            (position..position, first_prefix.clone())
 9962                        }));
 9963                    }
 9964                } else if let Some((full_comment_prefix, comment_suffix)) =
 9965                    language.block_comment_delimiters()
 9966                {
 9967                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9968                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9969                    let prefix_range = comment_prefix_range(
 9970                        snapshot.deref(),
 9971                        start_row,
 9972                        comment_prefix,
 9973                        comment_prefix_whitespace,
 9974                        ignore_indent,
 9975                    );
 9976                    let suffix_range = comment_suffix_range(
 9977                        snapshot.deref(),
 9978                        end_row,
 9979                        comment_suffix.trim_start_matches(' '),
 9980                        comment_suffix.starts_with(' '),
 9981                    );
 9982
 9983                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9984                        edits.push((
 9985                            prefix_range.start..prefix_range.start,
 9986                            full_comment_prefix.clone(),
 9987                        ));
 9988                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9989                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9990                    } else {
 9991                        edits.push((prefix_range, empty_str.clone()));
 9992                        edits.push((suffix_range, empty_str.clone()));
 9993                    }
 9994                } else {
 9995                    continue;
 9996                }
 9997            }
 9998
 9999            drop(snapshot);
10000            this.buffer.update(cx, |buffer, cx| {
10001                buffer.edit(edits, None, cx);
10002            });
10003
10004            // Adjust selections so that they end before any comment suffixes that
10005            // were inserted.
10006            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10007            let mut selections = this.selections.all::<Point>(cx);
10008            let snapshot = this.buffer.read(cx).read(cx);
10009            for selection in &mut selections {
10010                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10011                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10012                        Ordering::Less => {
10013                            suffixes_inserted.next();
10014                            continue;
10015                        }
10016                        Ordering::Greater => break,
10017                        Ordering::Equal => {
10018                            if selection.end.column == snapshot.line_len(row) {
10019                                if selection.is_empty() {
10020                                    selection.start.column -= suffix_len as u32;
10021                                }
10022                                selection.end.column -= suffix_len as u32;
10023                            }
10024                            break;
10025                        }
10026                    }
10027                }
10028            }
10029
10030            drop(snapshot);
10031            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10032                s.select(selections)
10033            });
10034
10035            let selections = this.selections.all::<Point>(cx);
10036            let selections_on_single_row = selections.windows(2).all(|selections| {
10037                selections[0].start.row == selections[1].start.row
10038                    && selections[0].end.row == selections[1].end.row
10039                    && selections[0].start.row == selections[0].end.row
10040            });
10041            let selections_selecting = selections
10042                .iter()
10043                .any(|selection| selection.start != selection.end);
10044            let advance_downwards = action.advance_downwards
10045                && selections_on_single_row
10046                && !selections_selecting
10047                && !matches!(this.mode, EditorMode::SingleLine { .. });
10048
10049            if advance_downwards {
10050                let snapshot = this.buffer.read(cx).snapshot(cx);
10051
10052                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10053                    s.move_cursors_with(|display_snapshot, display_point, _| {
10054                        let mut point = display_point.to_point(display_snapshot);
10055                        point.row += 1;
10056                        point = snapshot.clip_point(point, Bias::Left);
10057                        let display_point = point.to_display_point(display_snapshot);
10058                        let goal = SelectionGoal::HorizontalPosition(
10059                            display_snapshot
10060                                .x_for_display_point(display_point, text_layout_details)
10061                                .into(),
10062                        );
10063                        (display_point, goal)
10064                    })
10065                });
10066            }
10067        });
10068    }
10069
10070    pub fn select_enclosing_symbol(
10071        &mut self,
10072        _: &SelectEnclosingSymbol,
10073        window: &mut Window,
10074        cx: &mut Context<Self>,
10075    ) {
10076        let buffer = self.buffer.read(cx).snapshot(cx);
10077        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10078
10079        fn update_selection(
10080            selection: &Selection<usize>,
10081            buffer_snap: &MultiBufferSnapshot,
10082        ) -> Option<Selection<usize>> {
10083            let cursor = selection.head();
10084            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10085            for symbol in symbols.iter().rev() {
10086                let start = symbol.range.start.to_offset(buffer_snap);
10087                let end = symbol.range.end.to_offset(buffer_snap);
10088                let new_range = start..end;
10089                if start < selection.start || end > selection.end {
10090                    return Some(Selection {
10091                        id: selection.id,
10092                        start: new_range.start,
10093                        end: new_range.end,
10094                        goal: SelectionGoal::None,
10095                        reversed: selection.reversed,
10096                    });
10097                }
10098            }
10099            None
10100        }
10101
10102        let mut selected_larger_symbol = false;
10103        let new_selections = old_selections
10104            .iter()
10105            .map(|selection| match update_selection(selection, &buffer) {
10106                Some(new_selection) => {
10107                    if new_selection.range() != selection.range() {
10108                        selected_larger_symbol = true;
10109                    }
10110                    new_selection
10111                }
10112                None => selection.clone(),
10113            })
10114            .collect::<Vec<_>>();
10115
10116        if selected_larger_symbol {
10117            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10118                s.select(new_selections);
10119            });
10120        }
10121    }
10122
10123    pub fn select_larger_syntax_node(
10124        &mut self,
10125        _: &SelectLargerSyntaxNode,
10126        window: &mut Window,
10127        cx: &mut Context<Self>,
10128    ) {
10129        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10130        let buffer = self.buffer.read(cx).snapshot(cx);
10131        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10132
10133        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10134        let mut selected_larger_node = false;
10135        let new_selections = old_selections
10136            .iter()
10137            .map(|selection| {
10138                let old_range = selection.start..selection.end;
10139                let mut new_range = old_range.clone();
10140                let mut new_node = None;
10141                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10142                {
10143                    new_node = Some(node);
10144                    new_range = containing_range;
10145                    if !display_map.intersects_fold(new_range.start)
10146                        && !display_map.intersects_fold(new_range.end)
10147                    {
10148                        break;
10149                    }
10150                }
10151
10152                if let Some(node) = new_node {
10153                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10154                    // nodes. Parent and grandparent are also logged because this operation will not
10155                    // visit nodes that have the same range as their parent.
10156                    log::info!("Node: {node:?}");
10157                    let parent = node.parent();
10158                    log::info!("Parent: {parent:?}");
10159                    let grandparent = parent.and_then(|x| x.parent());
10160                    log::info!("Grandparent: {grandparent:?}");
10161                }
10162
10163                selected_larger_node |= new_range != old_range;
10164                Selection {
10165                    id: selection.id,
10166                    start: new_range.start,
10167                    end: new_range.end,
10168                    goal: SelectionGoal::None,
10169                    reversed: selection.reversed,
10170                }
10171            })
10172            .collect::<Vec<_>>();
10173
10174        if selected_larger_node {
10175            stack.push(old_selections);
10176            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10177                s.select(new_selections);
10178            });
10179        }
10180        self.select_larger_syntax_node_stack = stack;
10181    }
10182
10183    pub fn select_smaller_syntax_node(
10184        &mut self,
10185        _: &SelectSmallerSyntaxNode,
10186        window: &mut Window,
10187        cx: &mut Context<Self>,
10188    ) {
10189        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10190        if let Some(selections) = stack.pop() {
10191            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10192                s.select(selections.to_vec());
10193            });
10194        }
10195        self.select_larger_syntax_node_stack = stack;
10196    }
10197
10198    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10199        if !EditorSettings::get_global(cx).gutter.runnables {
10200            self.clear_tasks();
10201            return Task::ready(());
10202        }
10203        let project = self.project.as_ref().map(Entity::downgrade);
10204        cx.spawn_in(window, |this, mut cx| async move {
10205            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10206            let Some(project) = project.and_then(|p| p.upgrade()) else {
10207                return;
10208            };
10209            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10210                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10211            }) else {
10212                return;
10213            };
10214
10215            let hide_runnables = project
10216                .update(&mut cx, |project, cx| {
10217                    // Do not display any test indicators in non-dev server remote projects.
10218                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10219                })
10220                .unwrap_or(true);
10221            if hide_runnables {
10222                return;
10223            }
10224            let new_rows =
10225                cx.background_spawn({
10226                    let snapshot = display_snapshot.clone();
10227                    async move {
10228                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10229                    }
10230                })
10231                    .await;
10232
10233            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10234            this.update(&mut cx, |this, _| {
10235                this.clear_tasks();
10236                for (key, value) in rows {
10237                    this.insert_tasks(key, value);
10238                }
10239            })
10240            .ok();
10241        })
10242    }
10243    fn fetch_runnable_ranges(
10244        snapshot: &DisplaySnapshot,
10245        range: Range<Anchor>,
10246    ) -> Vec<language::RunnableRange> {
10247        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10248    }
10249
10250    fn runnable_rows(
10251        project: Entity<Project>,
10252        snapshot: DisplaySnapshot,
10253        runnable_ranges: Vec<RunnableRange>,
10254        mut cx: AsyncWindowContext,
10255    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10256        runnable_ranges
10257            .into_iter()
10258            .filter_map(|mut runnable| {
10259                let tasks = cx
10260                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10261                    .ok()?;
10262                if tasks.is_empty() {
10263                    return None;
10264                }
10265
10266                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10267
10268                let row = snapshot
10269                    .buffer_snapshot
10270                    .buffer_line_for_row(MultiBufferRow(point.row))?
10271                    .1
10272                    .start
10273                    .row;
10274
10275                let context_range =
10276                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10277                Some((
10278                    (runnable.buffer_id, row),
10279                    RunnableTasks {
10280                        templates: tasks,
10281                        offset: MultiBufferOffset(runnable.run_range.start),
10282                        context_range,
10283                        column: point.column,
10284                        extra_variables: runnable.extra_captures,
10285                    },
10286                ))
10287            })
10288            .collect()
10289    }
10290
10291    fn templates_with_tags(
10292        project: &Entity<Project>,
10293        runnable: &mut Runnable,
10294        cx: &mut App,
10295    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10296        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10297            let (worktree_id, file) = project
10298                .buffer_for_id(runnable.buffer, cx)
10299                .and_then(|buffer| buffer.read(cx).file())
10300                .map(|file| (file.worktree_id(cx), file.clone()))
10301                .unzip();
10302
10303            (
10304                project.task_store().read(cx).task_inventory().cloned(),
10305                worktree_id,
10306                file,
10307            )
10308        });
10309
10310        let tags = mem::take(&mut runnable.tags);
10311        let mut tags: Vec<_> = tags
10312            .into_iter()
10313            .flat_map(|tag| {
10314                let tag = tag.0.clone();
10315                inventory
10316                    .as_ref()
10317                    .into_iter()
10318                    .flat_map(|inventory| {
10319                        inventory.read(cx).list_tasks(
10320                            file.clone(),
10321                            Some(runnable.language.clone()),
10322                            worktree_id,
10323                            cx,
10324                        )
10325                    })
10326                    .filter(move |(_, template)| {
10327                        template.tags.iter().any(|source_tag| source_tag == &tag)
10328                    })
10329            })
10330            .sorted_by_key(|(kind, _)| kind.to_owned())
10331            .collect();
10332        if let Some((leading_tag_source, _)) = tags.first() {
10333            // Strongest source wins; if we have worktree tag binding, prefer that to
10334            // global and language bindings;
10335            // if we have a global binding, prefer that to language binding.
10336            let first_mismatch = tags
10337                .iter()
10338                .position(|(tag_source, _)| tag_source != leading_tag_source);
10339            if let Some(index) = first_mismatch {
10340                tags.truncate(index);
10341            }
10342        }
10343
10344        tags
10345    }
10346
10347    pub fn move_to_enclosing_bracket(
10348        &mut self,
10349        _: &MoveToEnclosingBracket,
10350        window: &mut Window,
10351        cx: &mut Context<Self>,
10352    ) {
10353        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10354            s.move_offsets_with(|snapshot, selection| {
10355                let Some(enclosing_bracket_ranges) =
10356                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10357                else {
10358                    return;
10359                };
10360
10361                let mut best_length = usize::MAX;
10362                let mut best_inside = false;
10363                let mut best_in_bracket_range = false;
10364                let mut best_destination = None;
10365                for (open, close) in enclosing_bracket_ranges {
10366                    let close = close.to_inclusive();
10367                    let length = close.end() - open.start;
10368                    let inside = selection.start >= open.end && selection.end <= *close.start();
10369                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10370                        || close.contains(&selection.head());
10371
10372                    // If best is next to a bracket and current isn't, skip
10373                    if !in_bracket_range && best_in_bracket_range {
10374                        continue;
10375                    }
10376
10377                    // Prefer smaller lengths unless best is inside and current isn't
10378                    if length > best_length && (best_inside || !inside) {
10379                        continue;
10380                    }
10381
10382                    best_length = length;
10383                    best_inside = inside;
10384                    best_in_bracket_range = in_bracket_range;
10385                    best_destination = Some(
10386                        if close.contains(&selection.start) && close.contains(&selection.end) {
10387                            if inside {
10388                                open.end
10389                            } else {
10390                                open.start
10391                            }
10392                        } else if inside {
10393                            *close.start()
10394                        } else {
10395                            *close.end()
10396                        },
10397                    );
10398                }
10399
10400                if let Some(destination) = best_destination {
10401                    selection.collapse_to(destination, SelectionGoal::None);
10402                }
10403            })
10404        });
10405    }
10406
10407    pub fn undo_selection(
10408        &mut self,
10409        _: &UndoSelection,
10410        window: &mut Window,
10411        cx: &mut Context<Self>,
10412    ) {
10413        self.end_selection(window, cx);
10414        self.selection_history.mode = SelectionHistoryMode::Undoing;
10415        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10416            self.change_selections(None, window, cx, |s| {
10417                s.select_anchors(entry.selections.to_vec())
10418            });
10419            self.select_next_state = entry.select_next_state;
10420            self.select_prev_state = entry.select_prev_state;
10421            self.add_selections_state = entry.add_selections_state;
10422            self.request_autoscroll(Autoscroll::newest(), cx);
10423        }
10424        self.selection_history.mode = SelectionHistoryMode::Normal;
10425    }
10426
10427    pub fn redo_selection(
10428        &mut self,
10429        _: &RedoSelection,
10430        window: &mut Window,
10431        cx: &mut Context<Self>,
10432    ) {
10433        self.end_selection(window, cx);
10434        self.selection_history.mode = SelectionHistoryMode::Redoing;
10435        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10436            self.change_selections(None, window, cx, |s| {
10437                s.select_anchors(entry.selections.to_vec())
10438            });
10439            self.select_next_state = entry.select_next_state;
10440            self.select_prev_state = entry.select_prev_state;
10441            self.add_selections_state = entry.add_selections_state;
10442            self.request_autoscroll(Autoscroll::newest(), cx);
10443        }
10444        self.selection_history.mode = SelectionHistoryMode::Normal;
10445    }
10446
10447    pub fn expand_excerpts(
10448        &mut self,
10449        action: &ExpandExcerpts,
10450        _: &mut Window,
10451        cx: &mut Context<Self>,
10452    ) {
10453        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10454    }
10455
10456    pub fn expand_excerpts_down(
10457        &mut self,
10458        action: &ExpandExcerptsDown,
10459        _: &mut Window,
10460        cx: &mut Context<Self>,
10461    ) {
10462        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10463    }
10464
10465    pub fn expand_excerpts_up(
10466        &mut self,
10467        action: &ExpandExcerptsUp,
10468        _: &mut Window,
10469        cx: &mut Context<Self>,
10470    ) {
10471        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10472    }
10473
10474    pub fn expand_excerpts_for_direction(
10475        &mut self,
10476        lines: u32,
10477        direction: ExpandExcerptDirection,
10478
10479        cx: &mut Context<Self>,
10480    ) {
10481        let selections = self.selections.disjoint_anchors();
10482
10483        let lines = if lines == 0 {
10484            EditorSettings::get_global(cx).expand_excerpt_lines
10485        } else {
10486            lines
10487        };
10488
10489        self.buffer.update(cx, |buffer, cx| {
10490            let snapshot = buffer.snapshot(cx);
10491            let mut excerpt_ids = selections
10492                .iter()
10493                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10494                .collect::<Vec<_>>();
10495            excerpt_ids.sort();
10496            excerpt_ids.dedup();
10497            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10498        })
10499    }
10500
10501    pub fn expand_excerpt(
10502        &mut self,
10503        excerpt: ExcerptId,
10504        direction: ExpandExcerptDirection,
10505        cx: &mut Context<Self>,
10506    ) {
10507        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10508        self.buffer.update(cx, |buffer, cx| {
10509            buffer.expand_excerpts([excerpt], lines, direction, cx)
10510        })
10511    }
10512
10513    pub fn go_to_singleton_buffer_point(
10514        &mut self,
10515        point: Point,
10516        window: &mut Window,
10517        cx: &mut Context<Self>,
10518    ) {
10519        self.go_to_singleton_buffer_range(point..point, window, cx);
10520    }
10521
10522    pub fn go_to_singleton_buffer_range(
10523        &mut self,
10524        range: Range<Point>,
10525        window: &mut Window,
10526        cx: &mut Context<Self>,
10527    ) {
10528        let multibuffer = self.buffer().read(cx);
10529        let Some(buffer) = multibuffer.as_singleton() else {
10530            return;
10531        };
10532        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10533            return;
10534        };
10535        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10536            return;
10537        };
10538        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10539            s.select_anchor_ranges([start..end])
10540        });
10541    }
10542
10543    fn go_to_diagnostic(
10544        &mut self,
10545        _: &GoToDiagnostic,
10546        window: &mut Window,
10547        cx: &mut Context<Self>,
10548    ) {
10549        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10550    }
10551
10552    fn go_to_prev_diagnostic(
10553        &mut self,
10554        _: &GoToPrevDiagnostic,
10555        window: &mut Window,
10556        cx: &mut Context<Self>,
10557    ) {
10558        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10559    }
10560
10561    pub fn go_to_diagnostic_impl(
10562        &mut self,
10563        direction: Direction,
10564        window: &mut Window,
10565        cx: &mut Context<Self>,
10566    ) {
10567        let buffer = self.buffer.read(cx).snapshot(cx);
10568        let selection = self.selections.newest::<usize>(cx);
10569
10570        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10571        if direction == Direction::Next {
10572            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10573                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10574                    return;
10575                };
10576                self.activate_diagnostics(
10577                    buffer_id,
10578                    popover.local_diagnostic.diagnostic.group_id,
10579                    window,
10580                    cx,
10581                );
10582                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10583                    let primary_range_start = active_diagnostics.primary_range.start;
10584                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10585                        let mut new_selection = s.newest_anchor().clone();
10586                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10587                        s.select_anchors(vec![new_selection.clone()]);
10588                    });
10589                    self.refresh_inline_completion(false, true, window, cx);
10590                }
10591                return;
10592            }
10593        }
10594
10595        let active_group_id = self
10596            .active_diagnostics
10597            .as_ref()
10598            .map(|active_group| active_group.group_id);
10599        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10600            active_diagnostics
10601                .primary_range
10602                .to_offset(&buffer)
10603                .to_inclusive()
10604        });
10605        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10606            if active_primary_range.contains(&selection.head()) {
10607                *active_primary_range.start()
10608            } else {
10609                selection.head()
10610            }
10611        } else {
10612            selection.head()
10613        };
10614
10615        let snapshot = self.snapshot(window, cx);
10616        let primary_diagnostics_before = buffer
10617            .diagnostics_in_range::<usize>(0..search_start)
10618            .filter(|entry| entry.diagnostic.is_primary)
10619            .filter(|entry| entry.range.start != entry.range.end)
10620            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10621            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10622            .collect::<Vec<_>>();
10623        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10624            primary_diagnostics_before
10625                .iter()
10626                .position(|entry| entry.diagnostic.group_id == active_group_id)
10627        });
10628
10629        let primary_diagnostics_after = buffer
10630            .diagnostics_in_range::<usize>(search_start..buffer.len())
10631            .filter(|entry| entry.diagnostic.is_primary)
10632            .filter(|entry| entry.range.start != entry.range.end)
10633            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10634            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10635            .collect::<Vec<_>>();
10636        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10637            primary_diagnostics_after
10638                .iter()
10639                .enumerate()
10640                .rev()
10641                .find_map(|(i, entry)| {
10642                    if entry.diagnostic.group_id == active_group_id {
10643                        Some(i)
10644                    } else {
10645                        None
10646                    }
10647                })
10648        });
10649
10650        let next_primary_diagnostic = match direction {
10651            Direction::Prev => primary_diagnostics_before
10652                .iter()
10653                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10654                .rev()
10655                .next(),
10656            Direction::Next => primary_diagnostics_after
10657                .iter()
10658                .skip(
10659                    last_same_group_diagnostic_after
10660                        .map(|index| index + 1)
10661                        .unwrap_or(0),
10662                )
10663                .next(),
10664        };
10665
10666        // Cycle around to the start of the buffer, potentially moving back to the start of
10667        // the currently active diagnostic.
10668        let cycle_around = || match direction {
10669            Direction::Prev => primary_diagnostics_after
10670                .iter()
10671                .rev()
10672                .chain(primary_diagnostics_before.iter().rev())
10673                .next(),
10674            Direction::Next => primary_diagnostics_before
10675                .iter()
10676                .chain(primary_diagnostics_after.iter())
10677                .next(),
10678        };
10679
10680        if let Some((primary_range, group_id)) = next_primary_diagnostic
10681            .or_else(cycle_around)
10682            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10683        {
10684            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10685                return;
10686            };
10687            self.activate_diagnostics(buffer_id, group_id, window, cx);
10688            if self.active_diagnostics.is_some() {
10689                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10690                    s.select(vec![Selection {
10691                        id: selection.id,
10692                        start: primary_range.start,
10693                        end: primary_range.start,
10694                        reversed: false,
10695                        goal: SelectionGoal::None,
10696                    }]);
10697                });
10698                self.refresh_inline_completion(false, true, window, cx);
10699            }
10700        }
10701    }
10702
10703    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10704        let snapshot = self.snapshot(window, cx);
10705        let selection = self.selections.newest::<Point>(cx);
10706        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10707    }
10708
10709    fn go_to_hunk_after_position(
10710        &mut self,
10711        snapshot: &EditorSnapshot,
10712        position: Point,
10713        window: &mut Window,
10714        cx: &mut Context<Editor>,
10715    ) -> Option<MultiBufferDiffHunk> {
10716        let mut hunk = snapshot
10717            .buffer_snapshot
10718            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10719            .find(|hunk| hunk.row_range.start.0 > position.row);
10720        if hunk.is_none() {
10721            hunk = snapshot
10722                .buffer_snapshot
10723                .diff_hunks_in_range(Point::zero()..position)
10724                .find(|hunk| hunk.row_range.end.0 < position.row)
10725        }
10726        if let Some(hunk) = &hunk {
10727            let destination = Point::new(hunk.row_range.start.0, 0);
10728            self.unfold_ranges(&[destination..destination], false, false, cx);
10729            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10730                s.select_ranges(vec![destination..destination]);
10731            });
10732        }
10733
10734        hunk
10735    }
10736
10737    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10738        let snapshot = self.snapshot(window, cx);
10739        let selection = self.selections.newest::<Point>(cx);
10740        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10741    }
10742
10743    fn go_to_hunk_before_position(
10744        &mut self,
10745        snapshot: &EditorSnapshot,
10746        position: Point,
10747        window: &mut Window,
10748        cx: &mut Context<Editor>,
10749    ) -> Option<MultiBufferDiffHunk> {
10750        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10751        if hunk.is_none() {
10752            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10753        }
10754        if let Some(hunk) = &hunk {
10755            let destination = Point::new(hunk.row_range.start.0, 0);
10756            self.unfold_ranges(&[destination..destination], false, false, cx);
10757            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10758                s.select_ranges(vec![destination..destination]);
10759            });
10760        }
10761
10762        hunk
10763    }
10764
10765    pub fn go_to_definition(
10766        &mut self,
10767        _: &GoToDefinition,
10768        window: &mut Window,
10769        cx: &mut Context<Self>,
10770    ) -> Task<Result<Navigated>> {
10771        let definition =
10772            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10773        cx.spawn_in(window, |editor, mut cx| async move {
10774            if definition.await? == Navigated::Yes {
10775                return Ok(Navigated::Yes);
10776            }
10777            match editor.update_in(&mut cx, |editor, window, cx| {
10778                editor.find_all_references(&FindAllReferences, window, cx)
10779            })? {
10780                Some(references) => references.await,
10781                None => Ok(Navigated::No),
10782            }
10783        })
10784    }
10785
10786    pub fn go_to_declaration(
10787        &mut self,
10788        _: &GoToDeclaration,
10789        window: &mut Window,
10790        cx: &mut Context<Self>,
10791    ) -> Task<Result<Navigated>> {
10792        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10793    }
10794
10795    pub fn go_to_declaration_split(
10796        &mut self,
10797        _: &GoToDeclaration,
10798        window: &mut Window,
10799        cx: &mut Context<Self>,
10800    ) -> Task<Result<Navigated>> {
10801        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10802    }
10803
10804    pub fn go_to_implementation(
10805        &mut self,
10806        _: &GoToImplementation,
10807        window: &mut Window,
10808        cx: &mut Context<Self>,
10809    ) -> Task<Result<Navigated>> {
10810        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10811    }
10812
10813    pub fn go_to_implementation_split(
10814        &mut self,
10815        _: &GoToImplementationSplit,
10816        window: &mut Window,
10817        cx: &mut Context<Self>,
10818    ) -> Task<Result<Navigated>> {
10819        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10820    }
10821
10822    pub fn go_to_type_definition(
10823        &mut self,
10824        _: &GoToTypeDefinition,
10825        window: &mut Window,
10826        cx: &mut Context<Self>,
10827    ) -> Task<Result<Navigated>> {
10828        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10829    }
10830
10831    pub fn go_to_definition_split(
10832        &mut self,
10833        _: &GoToDefinitionSplit,
10834        window: &mut Window,
10835        cx: &mut Context<Self>,
10836    ) -> Task<Result<Navigated>> {
10837        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10838    }
10839
10840    pub fn go_to_type_definition_split(
10841        &mut self,
10842        _: &GoToTypeDefinitionSplit,
10843        window: &mut Window,
10844        cx: &mut Context<Self>,
10845    ) -> Task<Result<Navigated>> {
10846        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10847    }
10848
10849    fn go_to_definition_of_kind(
10850        &mut self,
10851        kind: GotoDefinitionKind,
10852        split: bool,
10853        window: &mut Window,
10854        cx: &mut Context<Self>,
10855    ) -> Task<Result<Navigated>> {
10856        let Some(provider) = self.semantics_provider.clone() else {
10857            return Task::ready(Ok(Navigated::No));
10858        };
10859        let head = self.selections.newest::<usize>(cx).head();
10860        let buffer = self.buffer.read(cx);
10861        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10862            text_anchor
10863        } else {
10864            return Task::ready(Ok(Navigated::No));
10865        };
10866
10867        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10868            return Task::ready(Ok(Navigated::No));
10869        };
10870
10871        cx.spawn_in(window, |editor, mut cx| async move {
10872            let definitions = definitions.await?;
10873            let navigated = editor
10874                .update_in(&mut cx, |editor, window, cx| {
10875                    editor.navigate_to_hover_links(
10876                        Some(kind),
10877                        definitions
10878                            .into_iter()
10879                            .filter(|location| {
10880                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10881                            })
10882                            .map(HoverLink::Text)
10883                            .collect::<Vec<_>>(),
10884                        split,
10885                        window,
10886                        cx,
10887                    )
10888                })?
10889                .await?;
10890            anyhow::Ok(navigated)
10891        })
10892    }
10893
10894    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10895        let selection = self.selections.newest_anchor();
10896        let head = selection.head();
10897        let tail = selection.tail();
10898
10899        let Some((buffer, start_position)) =
10900            self.buffer.read(cx).text_anchor_for_position(head, cx)
10901        else {
10902            return;
10903        };
10904
10905        let end_position = if head != tail {
10906            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10907                return;
10908            };
10909            Some(pos)
10910        } else {
10911            None
10912        };
10913
10914        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10915            let url = if let Some(end_pos) = end_position {
10916                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10917            } else {
10918                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10919            };
10920
10921            if let Some(url) = url {
10922                editor.update(&mut cx, |_, cx| {
10923                    cx.open_url(&url);
10924                })
10925            } else {
10926                Ok(())
10927            }
10928        });
10929
10930        url_finder.detach();
10931    }
10932
10933    pub fn open_selected_filename(
10934        &mut self,
10935        _: &OpenSelectedFilename,
10936        window: &mut Window,
10937        cx: &mut Context<Self>,
10938    ) {
10939        let Some(workspace) = self.workspace() else {
10940            return;
10941        };
10942
10943        let position = self.selections.newest_anchor().head();
10944
10945        let Some((buffer, buffer_position)) =
10946            self.buffer.read(cx).text_anchor_for_position(position, cx)
10947        else {
10948            return;
10949        };
10950
10951        let project = self.project.clone();
10952
10953        cx.spawn_in(window, |_, mut cx| async move {
10954            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10955
10956            if let Some((_, path)) = result {
10957                workspace
10958                    .update_in(&mut cx, |workspace, window, cx| {
10959                        workspace.open_resolved_path(path, window, cx)
10960                    })?
10961                    .await?;
10962            }
10963            anyhow::Ok(())
10964        })
10965        .detach();
10966    }
10967
10968    pub(crate) fn navigate_to_hover_links(
10969        &mut self,
10970        kind: Option<GotoDefinitionKind>,
10971        mut definitions: Vec<HoverLink>,
10972        split: bool,
10973        window: &mut Window,
10974        cx: &mut Context<Editor>,
10975    ) -> Task<Result<Navigated>> {
10976        // If there is one definition, just open it directly
10977        if definitions.len() == 1 {
10978            let definition = definitions.pop().unwrap();
10979
10980            enum TargetTaskResult {
10981                Location(Option<Location>),
10982                AlreadyNavigated,
10983            }
10984
10985            let target_task = match definition {
10986                HoverLink::Text(link) => {
10987                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10988                }
10989                HoverLink::InlayHint(lsp_location, server_id) => {
10990                    let computation =
10991                        self.compute_target_location(lsp_location, server_id, window, cx);
10992                    cx.background_spawn(async move {
10993                        let location = computation.await?;
10994                        Ok(TargetTaskResult::Location(location))
10995                    })
10996                }
10997                HoverLink::Url(url) => {
10998                    cx.open_url(&url);
10999                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11000                }
11001                HoverLink::File(path) => {
11002                    if let Some(workspace) = self.workspace() {
11003                        cx.spawn_in(window, |_, mut cx| async move {
11004                            workspace
11005                                .update_in(&mut cx, |workspace, window, cx| {
11006                                    workspace.open_resolved_path(path, window, cx)
11007                                })?
11008                                .await
11009                                .map(|_| TargetTaskResult::AlreadyNavigated)
11010                        })
11011                    } else {
11012                        Task::ready(Ok(TargetTaskResult::Location(None)))
11013                    }
11014                }
11015            };
11016            cx.spawn_in(window, |editor, mut cx| async move {
11017                let target = match target_task.await.context("target resolution task")? {
11018                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11019                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11020                    TargetTaskResult::Location(Some(target)) => target,
11021                };
11022
11023                editor.update_in(&mut cx, |editor, window, cx| {
11024                    let Some(workspace) = editor.workspace() else {
11025                        return Navigated::No;
11026                    };
11027                    let pane = workspace.read(cx).active_pane().clone();
11028
11029                    let range = target.range.to_point(target.buffer.read(cx));
11030                    let range = editor.range_for_match(&range);
11031                    let range = collapse_multiline_range(range);
11032
11033                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11034                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11035                    } else {
11036                        window.defer(cx, move |window, cx| {
11037                            let target_editor: Entity<Self> =
11038                                workspace.update(cx, |workspace, cx| {
11039                                    let pane = if split {
11040                                        workspace.adjacent_pane(window, cx)
11041                                    } else {
11042                                        workspace.active_pane().clone()
11043                                    };
11044
11045                                    workspace.open_project_item(
11046                                        pane,
11047                                        target.buffer.clone(),
11048                                        true,
11049                                        true,
11050                                        window,
11051                                        cx,
11052                                    )
11053                                });
11054                            target_editor.update(cx, |target_editor, cx| {
11055                                // When selecting a definition in a different buffer, disable the nav history
11056                                // to avoid creating a history entry at the previous cursor location.
11057                                pane.update(cx, |pane, _| pane.disable_history());
11058                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11059                                pane.update(cx, |pane, _| pane.enable_history());
11060                            });
11061                        });
11062                    }
11063                    Navigated::Yes
11064                })
11065            })
11066        } else if !definitions.is_empty() {
11067            cx.spawn_in(window, |editor, mut cx| async move {
11068                let (title, location_tasks, workspace) = editor
11069                    .update_in(&mut cx, |editor, window, cx| {
11070                        let tab_kind = match kind {
11071                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11072                            _ => "Definitions",
11073                        };
11074                        let title = definitions
11075                            .iter()
11076                            .find_map(|definition| match definition {
11077                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11078                                    let buffer = origin.buffer.read(cx);
11079                                    format!(
11080                                        "{} for {}",
11081                                        tab_kind,
11082                                        buffer
11083                                            .text_for_range(origin.range.clone())
11084                                            .collect::<String>()
11085                                    )
11086                                }),
11087                                HoverLink::InlayHint(_, _) => None,
11088                                HoverLink::Url(_) => None,
11089                                HoverLink::File(_) => None,
11090                            })
11091                            .unwrap_or(tab_kind.to_string());
11092                        let location_tasks = definitions
11093                            .into_iter()
11094                            .map(|definition| match definition {
11095                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11096                                HoverLink::InlayHint(lsp_location, server_id) => editor
11097                                    .compute_target_location(lsp_location, server_id, window, cx),
11098                                HoverLink::Url(_) => Task::ready(Ok(None)),
11099                                HoverLink::File(_) => Task::ready(Ok(None)),
11100                            })
11101                            .collect::<Vec<_>>();
11102                        (title, location_tasks, editor.workspace().clone())
11103                    })
11104                    .context("location tasks preparation")?;
11105
11106                let locations = future::join_all(location_tasks)
11107                    .await
11108                    .into_iter()
11109                    .filter_map(|location| location.transpose())
11110                    .collect::<Result<_>>()
11111                    .context("location tasks")?;
11112
11113                let Some(workspace) = workspace else {
11114                    return Ok(Navigated::No);
11115                };
11116                let opened = workspace
11117                    .update_in(&mut cx, |workspace, window, cx| {
11118                        Self::open_locations_in_multibuffer(
11119                            workspace,
11120                            locations,
11121                            title,
11122                            split,
11123                            MultibufferSelectionMode::First,
11124                            window,
11125                            cx,
11126                        )
11127                    })
11128                    .ok();
11129
11130                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11131            })
11132        } else {
11133            Task::ready(Ok(Navigated::No))
11134        }
11135    }
11136
11137    fn compute_target_location(
11138        &self,
11139        lsp_location: lsp::Location,
11140        server_id: LanguageServerId,
11141        window: &mut Window,
11142        cx: &mut Context<Self>,
11143    ) -> Task<anyhow::Result<Option<Location>>> {
11144        let Some(project) = self.project.clone() else {
11145            return Task::ready(Ok(None));
11146        };
11147
11148        cx.spawn_in(window, move |editor, mut cx| async move {
11149            let location_task = editor.update(&mut cx, |_, cx| {
11150                project.update(cx, |project, cx| {
11151                    let language_server_name = project
11152                        .language_server_statuses(cx)
11153                        .find(|(id, _)| server_id == *id)
11154                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11155                    language_server_name.map(|language_server_name| {
11156                        project.open_local_buffer_via_lsp(
11157                            lsp_location.uri.clone(),
11158                            server_id,
11159                            language_server_name,
11160                            cx,
11161                        )
11162                    })
11163                })
11164            })?;
11165            let location = match location_task {
11166                Some(task) => Some({
11167                    let target_buffer_handle = task.await.context("open local buffer")?;
11168                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11169                        let target_start = target_buffer
11170                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11171                        let target_end = target_buffer
11172                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11173                        target_buffer.anchor_after(target_start)
11174                            ..target_buffer.anchor_before(target_end)
11175                    })?;
11176                    Location {
11177                        buffer: target_buffer_handle,
11178                        range,
11179                    }
11180                }),
11181                None => None,
11182            };
11183            Ok(location)
11184        })
11185    }
11186
11187    pub fn find_all_references(
11188        &mut self,
11189        _: &FindAllReferences,
11190        window: &mut Window,
11191        cx: &mut Context<Self>,
11192    ) -> Option<Task<Result<Navigated>>> {
11193        let selection = self.selections.newest::<usize>(cx);
11194        let multi_buffer = self.buffer.read(cx);
11195        let head = selection.head();
11196
11197        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11198        let head_anchor = multi_buffer_snapshot.anchor_at(
11199            head,
11200            if head < selection.tail() {
11201                Bias::Right
11202            } else {
11203                Bias::Left
11204            },
11205        );
11206
11207        match self
11208            .find_all_references_task_sources
11209            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11210        {
11211            Ok(_) => {
11212                log::info!(
11213                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11214                );
11215                return None;
11216            }
11217            Err(i) => {
11218                self.find_all_references_task_sources.insert(i, head_anchor);
11219            }
11220        }
11221
11222        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11223        let workspace = self.workspace()?;
11224        let project = workspace.read(cx).project().clone();
11225        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11226        Some(cx.spawn_in(window, |editor, mut cx| async move {
11227            let _cleanup = defer({
11228                let mut cx = cx.clone();
11229                move || {
11230                    let _ = editor.update(&mut cx, |editor, _| {
11231                        if let Ok(i) =
11232                            editor
11233                                .find_all_references_task_sources
11234                                .binary_search_by(|anchor| {
11235                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11236                                })
11237                        {
11238                            editor.find_all_references_task_sources.remove(i);
11239                        }
11240                    });
11241                }
11242            });
11243
11244            let locations = references.await?;
11245            if locations.is_empty() {
11246                return anyhow::Ok(Navigated::No);
11247            }
11248
11249            workspace.update_in(&mut cx, |workspace, window, cx| {
11250                let title = locations
11251                    .first()
11252                    .as_ref()
11253                    .map(|location| {
11254                        let buffer = location.buffer.read(cx);
11255                        format!(
11256                            "References to `{}`",
11257                            buffer
11258                                .text_for_range(location.range.clone())
11259                                .collect::<String>()
11260                        )
11261                    })
11262                    .unwrap();
11263                Self::open_locations_in_multibuffer(
11264                    workspace,
11265                    locations,
11266                    title,
11267                    false,
11268                    MultibufferSelectionMode::First,
11269                    window,
11270                    cx,
11271                );
11272                Navigated::Yes
11273            })
11274        }))
11275    }
11276
11277    /// Opens a multibuffer with the given project locations in it
11278    pub fn open_locations_in_multibuffer(
11279        workspace: &mut Workspace,
11280        mut locations: Vec<Location>,
11281        title: String,
11282        split: bool,
11283        multibuffer_selection_mode: MultibufferSelectionMode,
11284        window: &mut Window,
11285        cx: &mut Context<Workspace>,
11286    ) {
11287        // If there are multiple definitions, open them in a multibuffer
11288        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11289        let mut locations = locations.into_iter().peekable();
11290        let mut ranges = Vec::new();
11291        let capability = workspace.project().read(cx).capability();
11292
11293        let excerpt_buffer = cx.new(|cx| {
11294            let mut multibuffer = MultiBuffer::new(capability);
11295            while let Some(location) = locations.next() {
11296                let buffer = location.buffer.read(cx);
11297                let mut ranges_for_buffer = Vec::new();
11298                let range = location.range.to_offset(buffer);
11299                ranges_for_buffer.push(range.clone());
11300
11301                while let Some(next_location) = locations.peek() {
11302                    if next_location.buffer == location.buffer {
11303                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11304                        locations.next();
11305                    } else {
11306                        break;
11307                    }
11308                }
11309
11310                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11311                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11312                    location.buffer.clone(),
11313                    ranges_for_buffer,
11314                    DEFAULT_MULTIBUFFER_CONTEXT,
11315                    cx,
11316                ))
11317            }
11318
11319            multibuffer.with_title(title)
11320        });
11321
11322        let editor = cx.new(|cx| {
11323            Editor::for_multibuffer(
11324                excerpt_buffer,
11325                Some(workspace.project().clone()),
11326                true,
11327                window,
11328                cx,
11329            )
11330        });
11331        editor.update(cx, |editor, cx| {
11332            match multibuffer_selection_mode {
11333                MultibufferSelectionMode::First => {
11334                    if let Some(first_range) = ranges.first() {
11335                        editor.change_selections(None, window, cx, |selections| {
11336                            selections.clear_disjoint();
11337                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11338                        });
11339                    }
11340                    editor.highlight_background::<Self>(
11341                        &ranges,
11342                        |theme| theme.editor_highlighted_line_background,
11343                        cx,
11344                    );
11345                }
11346                MultibufferSelectionMode::All => {
11347                    editor.change_selections(None, window, cx, |selections| {
11348                        selections.clear_disjoint();
11349                        selections.select_anchor_ranges(ranges);
11350                    });
11351                }
11352            }
11353            editor.register_buffers_with_language_servers(cx);
11354        });
11355
11356        let item = Box::new(editor);
11357        let item_id = item.item_id();
11358
11359        if split {
11360            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11361        } else {
11362            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11363                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11364                    pane.close_current_preview_item(window, cx)
11365                } else {
11366                    None
11367                }
11368            });
11369            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11370        }
11371        workspace.active_pane().update(cx, |pane, cx| {
11372            pane.set_preview_item_id(Some(item_id), cx);
11373        });
11374    }
11375
11376    pub fn rename(
11377        &mut self,
11378        _: &Rename,
11379        window: &mut Window,
11380        cx: &mut Context<Self>,
11381    ) -> Option<Task<Result<()>>> {
11382        use language::ToOffset as _;
11383
11384        let provider = self.semantics_provider.clone()?;
11385        let selection = self.selections.newest_anchor().clone();
11386        let (cursor_buffer, cursor_buffer_position) = self
11387            .buffer
11388            .read(cx)
11389            .text_anchor_for_position(selection.head(), cx)?;
11390        let (tail_buffer, cursor_buffer_position_end) = self
11391            .buffer
11392            .read(cx)
11393            .text_anchor_for_position(selection.tail(), cx)?;
11394        if tail_buffer != cursor_buffer {
11395            return None;
11396        }
11397
11398        let snapshot = cursor_buffer.read(cx).snapshot();
11399        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11400        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11401        let prepare_rename = provider
11402            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11403            .unwrap_or_else(|| Task::ready(Ok(None)));
11404        drop(snapshot);
11405
11406        Some(cx.spawn_in(window, |this, mut cx| async move {
11407            let rename_range = if let Some(range) = prepare_rename.await? {
11408                Some(range)
11409            } else {
11410                this.update(&mut cx, |this, cx| {
11411                    let buffer = this.buffer.read(cx).snapshot(cx);
11412                    let mut buffer_highlights = this
11413                        .document_highlights_for_position(selection.head(), &buffer)
11414                        .filter(|highlight| {
11415                            highlight.start.excerpt_id == selection.head().excerpt_id
11416                                && highlight.end.excerpt_id == selection.head().excerpt_id
11417                        });
11418                    buffer_highlights
11419                        .next()
11420                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11421                })?
11422            };
11423            if let Some(rename_range) = rename_range {
11424                this.update_in(&mut cx, |this, window, cx| {
11425                    let snapshot = cursor_buffer.read(cx).snapshot();
11426                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11427                    let cursor_offset_in_rename_range =
11428                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11429                    let cursor_offset_in_rename_range_end =
11430                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11431
11432                    this.take_rename(false, window, cx);
11433                    let buffer = this.buffer.read(cx).read(cx);
11434                    let cursor_offset = selection.head().to_offset(&buffer);
11435                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11436                    let rename_end = rename_start + rename_buffer_range.len();
11437                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11438                    let mut old_highlight_id = None;
11439                    let old_name: Arc<str> = buffer
11440                        .chunks(rename_start..rename_end, true)
11441                        .map(|chunk| {
11442                            if old_highlight_id.is_none() {
11443                                old_highlight_id = chunk.syntax_highlight_id;
11444                            }
11445                            chunk.text
11446                        })
11447                        .collect::<String>()
11448                        .into();
11449
11450                    drop(buffer);
11451
11452                    // Position the selection in the rename editor so that it matches the current selection.
11453                    this.show_local_selections = false;
11454                    let rename_editor = cx.new(|cx| {
11455                        let mut editor = Editor::single_line(window, cx);
11456                        editor.buffer.update(cx, |buffer, cx| {
11457                            buffer.edit([(0..0, old_name.clone())], None, cx)
11458                        });
11459                        let rename_selection_range = match cursor_offset_in_rename_range
11460                            .cmp(&cursor_offset_in_rename_range_end)
11461                        {
11462                            Ordering::Equal => {
11463                                editor.select_all(&SelectAll, window, cx);
11464                                return editor;
11465                            }
11466                            Ordering::Less => {
11467                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11468                            }
11469                            Ordering::Greater => {
11470                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11471                            }
11472                        };
11473                        if rename_selection_range.end > old_name.len() {
11474                            editor.select_all(&SelectAll, window, cx);
11475                        } else {
11476                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11477                                s.select_ranges([rename_selection_range]);
11478                            });
11479                        }
11480                        editor
11481                    });
11482                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11483                        if e == &EditorEvent::Focused {
11484                            cx.emit(EditorEvent::FocusedIn)
11485                        }
11486                    })
11487                    .detach();
11488
11489                    let write_highlights =
11490                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11491                    let read_highlights =
11492                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11493                    let ranges = write_highlights
11494                        .iter()
11495                        .flat_map(|(_, ranges)| ranges.iter())
11496                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11497                        .cloned()
11498                        .collect();
11499
11500                    this.highlight_text::<Rename>(
11501                        ranges,
11502                        HighlightStyle {
11503                            fade_out: Some(0.6),
11504                            ..Default::default()
11505                        },
11506                        cx,
11507                    );
11508                    let rename_focus_handle = rename_editor.focus_handle(cx);
11509                    window.focus(&rename_focus_handle);
11510                    let block_id = this.insert_blocks(
11511                        [BlockProperties {
11512                            style: BlockStyle::Flex,
11513                            placement: BlockPlacement::Below(range.start),
11514                            height: 1,
11515                            render: Arc::new({
11516                                let rename_editor = rename_editor.clone();
11517                                move |cx: &mut BlockContext| {
11518                                    let mut text_style = cx.editor_style.text.clone();
11519                                    if let Some(highlight_style) = old_highlight_id
11520                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11521                                    {
11522                                        text_style = text_style.highlight(highlight_style);
11523                                    }
11524                                    div()
11525                                        .block_mouse_down()
11526                                        .pl(cx.anchor_x)
11527                                        .child(EditorElement::new(
11528                                            &rename_editor,
11529                                            EditorStyle {
11530                                                background: cx.theme().system().transparent,
11531                                                local_player: cx.editor_style.local_player,
11532                                                text: text_style,
11533                                                scrollbar_width: cx.editor_style.scrollbar_width,
11534                                                syntax: cx.editor_style.syntax.clone(),
11535                                                status: cx.editor_style.status.clone(),
11536                                                inlay_hints_style: HighlightStyle {
11537                                                    font_weight: Some(FontWeight::BOLD),
11538                                                    ..make_inlay_hints_style(cx.app)
11539                                                },
11540                                                inline_completion_styles: make_suggestion_styles(
11541                                                    cx.app,
11542                                                ),
11543                                                ..EditorStyle::default()
11544                                            },
11545                                        ))
11546                                        .into_any_element()
11547                                }
11548                            }),
11549                            priority: 0,
11550                        }],
11551                        Some(Autoscroll::fit()),
11552                        cx,
11553                    )[0];
11554                    this.pending_rename = Some(RenameState {
11555                        range,
11556                        old_name,
11557                        editor: rename_editor,
11558                        block_id,
11559                    });
11560                })?;
11561            }
11562
11563            Ok(())
11564        }))
11565    }
11566
11567    pub fn confirm_rename(
11568        &mut self,
11569        _: &ConfirmRename,
11570        window: &mut Window,
11571        cx: &mut Context<Self>,
11572    ) -> Option<Task<Result<()>>> {
11573        let rename = self.take_rename(false, window, cx)?;
11574        let workspace = self.workspace()?.downgrade();
11575        let (buffer, start) = self
11576            .buffer
11577            .read(cx)
11578            .text_anchor_for_position(rename.range.start, cx)?;
11579        let (end_buffer, _) = self
11580            .buffer
11581            .read(cx)
11582            .text_anchor_for_position(rename.range.end, cx)?;
11583        if buffer != end_buffer {
11584            return None;
11585        }
11586
11587        let old_name = rename.old_name;
11588        let new_name = rename.editor.read(cx).text(cx);
11589
11590        let rename = self.semantics_provider.as_ref()?.perform_rename(
11591            &buffer,
11592            start,
11593            new_name.clone(),
11594            cx,
11595        )?;
11596
11597        Some(cx.spawn_in(window, |editor, mut cx| async move {
11598            let project_transaction = rename.await?;
11599            Self::open_project_transaction(
11600                &editor,
11601                workspace,
11602                project_transaction,
11603                format!("Rename: {}{}", old_name, new_name),
11604                cx.clone(),
11605            )
11606            .await?;
11607
11608            editor.update(&mut cx, |editor, cx| {
11609                editor.refresh_document_highlights(cx);
11610            })?;
11611            Ok(())
11612        }))
11613    }
11614
11615    fn take_rename(
11616        &mut self,
11617        moving_cursor: bool,
11618        window: &mut Window,
11619        cx: &mut Context<Self>,
11620    ) -> Option<RenameState> {
11621        let rename = self.pending_rename.take()?;
11622        if rename.editor.focus_handle(cx).is_focused(window) {
11623            window.focus(&self.focus_handle);
11624        }
11625
11626        self.remove_blocks(
11627            [rename.block_id].into_iter().collect(),
11628            Some(Autoscroll::fit()),
11629            cx,
11630        );
11631        self.clear_highlights::<Rename>(cx);
11632        self.show_local_selections = true;
11633
11634        if moving_cursor {
11635            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11636                editor.selections.newest::<usize>(cx).head()
11637            });
11638
11639            // Update the selection to match the position of the selection inside
11640            // the rename editor.
11641            let snapshot = self.buffer.read(cx).read(cx);
11642            let rename_range = rename.range.to_offset(&snapshot);
11643            let cursor_in_editor = snapshot
11644                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11645                .min(rename_range.end);
11646            drop(snapshot);
11647
11648            self.change_selections(None, window, cx, |s| {
11649                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11650            });
11651        } else {
11652            self.refresh_document_highlights(cx);
11653        }
11654
11655        Some(rename)
11656    }
11657
11658    pub fn pending_rename(&self) -> Option<&RenameState> {
11659        self.pending_rename.as_ref()
11660    }
11661
11662    fn format(
11663        &mut self,
11664        _: &Format,
11665        window: &mut Window,
11666        cx: &mut Context<Self>,
11667    ) -> Option<Task<Result<()>>> {
11668        let project = match &self.project {
11669            Some(project) => project.clone(),
11670            None => return None,
11671        };
11672
11673        Some(self.perform_format(
11674            project,
11675            FormatTrigger::Manual,
11676            FormatTarget::Buffers,
11677            window,
11678            cx,
11679        ))
11680    }
11681
11682    fn format_selections(
11683        &mut self,
11684        _: &FormatSelections,
11685        window: &mut Window,
11686        cx: &mut Context<Self>,
11687    ) -> Option<Task<Result<()>>> {
11688        let project = match &self.project {
11689            Some(project) => project.clone(),
11690            None => return None,
11691        };
11692
11693        let ranges = self
11694            .selections
11695            .all_adjusted(cx)
11696            .into_iter()
11697            .map(|selection| selection.range())
11698            .collect_vec();
11699
11700        Some(self.perform_format(
11701            project,
11702            FormatTrigger::Manual,
11703            FormatTarget::Ranges(ranges),
11704            window,
11705            cx,
11706        ))
11707    }
11708
11709    fn perform_format(
11710        &mut self,
11711        project: Entity<Project>,
11712        trigger: FormatTrigger,
11713        target: FormatTarget,
11714        window: &mut Window,
11715        cx: &mut Context<Self>,
11716    ) -> Task<Result<()>> {
11717        let buffer = self.buffer.clone();
11718        let (buffers, target) = match target {
11719            FormatTarget::Buffers => {
11720                let mut buffers = buffer.read(cx).all_buffers();
11721                if trigger == FormatTrigger::Save {
11722                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11723                }
11724                (buffers, LspFormatTarget::Buffers)
11725            }
11726            FormatTarget::Ranges(selection_ranges) => {
11727                let multi_buffer = buffer.read(cx);
11728                let snapshot = multi_buffer.read(cx);
11729                let mut buffers = HashSet::default();
11730                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11731                    BTreeMap::new();
11732                for selection_range in selection_ranges {
11733                    for (buffer, buffer_range, _) in
11734                        snapshot.range_to_buffer_ranges(selection_range)
11735                    {
11736                        let buffer_id = buffer.remote_id();
11737                        let start = buffer.anchor_before(buffer_range.start);
11738                        let end = buffer.anchor_after(buffer_range.end);
11739                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11740                        buffer_id_to_ranges
11741                            .entry(buffer_id)
11742                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11743                            .or_insert_with(|| vec![start..end]);
11744                    }
11745                }
11746                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11747            }
11748        };
11749
11750        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11751        let format = project.update(cx, |project, cx| {
11752            project.format(buffers, target, true, trigger, cx)
11753        });
11754
11755        cx.spawn_in(window, |_, mut cx| async move {
11756            let transaction = futures::select_biased! {
11757                () = timeout => {
11758                    log::warn!("timed out waiting for formatting");
11759                    None
11760                }
11761                transaction = format.log_err().fuse() => transaction,
11762            };
11763
11764            buffer
11765                .update(&mut cx, |buffer, cx| {
11766                    if let Some(transaction) = transaction {
11767                        if !buffer.is_singleton() {
11768                            buffer.push_transaction(&transaction.0, cx);
11769                        }
11770                    }
11771
11772                    cx.notify();
11773                })
11774                .ok();
11775
11776            Ok(())
11777        })
11778    }
11779
11780    fn restart_language_server(
11781        &mut self,
11782        _: &RestartLanguageServer,
11783        _: &mut Window,
11784        cx: &mut Context<Self>,
11785    ) {
11786        if let Some(project) = self.project.clone() {
11787            self.buffer.update(cx, |multi_buffer, cx| {
11788                project.update(cx, |project, cx| {
11789                    project.restart_language_servers_for_buffers(
11790                        multi_buffer.all_buffers().into_iter().collect(),
11791                        cx,
11792                    );
11793                });
11794            })
11795        }
11796    }
11797
11798    fn cancel_language_server_work(
11799        workspace: &mut Workspace,
11800        _: &actions::CancelLanguageServerWork,
11801        _: &mut Window,
11802        cx: &mut Context<Workspace>,
11803    ) {
11804        let project = workspace.project();
11805        let buffers = workspace
11806            .active_item(cx)
11807            .and_then(|item| item.act_as::<Editor>(cx))
11808            .map_or(HashSet::default(), |editor| {
11809                editor.read(cx).buffer.read(cx).all_buffers()
11810            });
11811        project.update(cx, |project, cx| {
11812            project.cancel_language_server_work_for_buffers(buffers, cx);
11813        });
11814    }
11815
11816    fn show_character_palette(
11817        &mut self,
11818        _: &ShowCharacterPalette,
11819        window: &mut Window,
11820        _: &mut Context<Self>,
11821    ) {
11822        window.show_character_palette();
11823    }
11824
11825    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11826        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11827            let buffer = self.buffer.read(cx).snapshot(cx);
11828            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11829            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11830            let is_valid = buffer
11831                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11832                .any(|entry| {
11833                    entry.diagnostic.is_primary
11834                        && !entry.range.is_empty()
11835                        && entry.range.start == primary_range_start
11836                        && entry.diagnostic.message == active_diagnostics.primary_message
11837                });
11838
11839            if is_valid != active_diagnostics.is_valid {
11840                active_diagnostics.is_valid = is_valid;
11841                let mut new_styles = HashMap::default();
11842                for (block_id, diagnostic) in &active_diagnostics.blocks {
11843                    new_styles.insert(
11844                        *block_id,
11845                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11846                    );
11847                }
11848                self.display_map.update(cx, |display_map, _cx| {
11849                    display_map.replace_blocks(new_styles)
11850                });
11851            }
11852        }
11853    }
11854
11855    fn activate_diagnostics(
11856        &mut self,
11857        buffer_id: BufferId,
11858        group_id: usize,
11859        window: &mut Window,
11860        cx: &mut Context<Self>,
11861    ) {
11862        self.dismiss_diagnostics(cx);
11863        let snapshot = self.snapshot(window, cx);
11864        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11865            let buffer = self.buffer.read(cx).snapshot(cx);
11866
11867            let mut primary_range = None;
11868            let mut primary_message = None;
11869            let diagnostic_group = buffer
11870                .diagnostic_group(buffer_id, group_id)
11871                .filter_map(|entry| {
11872                    let start = entry.range.start;
11873                    let end = entry.range.end;
11874                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11875                        && (start.row == end.row
11876                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11877                    {
11878                        return None;
11879                    }
11880                    if entry.diagnostic.is_primary {
11881                        primary_range = Some(entry.range.clone());
11882                        primary_message = Some(entry.diagnostic.message.clone());
11883                    }
11884                    Some(entry)
11885                })
11886                .collect::<Vec<_>>();
11887            let primary_range = primary_range?;
11888            let primary_message = primary_message?;
11889
11890            let blocks = display_map
11891                .insert_blocks(
11892                    diagnostic_group.iter().map(|entry| {
11893                        let diagnostic = entry.diagnostic.clone();
11894                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11895                        BlockProperties {
11896                            style: BlockStyle::Fixed,
11897                            placement: BlockPlacement::Below(
11898                                buffer.anchor_after(entry.range.start),
11899                            ),
11900                            height: message_height,
11901                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11902                            priority: 0,
11903                        }
11904                    }),
11905                    cx,
11906                )
11907                .into_iter()
11908                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11909                .collect();
11910
11911            Some(ActiveDiagnosticGroup {
11912                primary_range: buffer.anchor_before(primary_range.start)
11913                    ..buffer.anchor_after(primary_range.end),
11914                primary_message,
11915                group_id,
11916                blocks,
11917                is_valid: true,
11918            })
11919        });
11920    }
11921
11922    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11923        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11924            self.display_map.update(cx, |display_map, cx| {
11925                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11926            });
11927            cx.notify();
11928        }
11929    }
11930
11931    pub fn set_selections_from_remote(
11932        &mut self,
11933        selections: Vec<Selection<Anchor>>,
11934        pending_selection: Option<Selection<Anchor>>,
11935        window: &mut Window,
11936        cx: &mut Context<Self>,
11937    ) {
11938        let old_cursor_position = self.selections.newest_anchor().head();
11939        self.selections.change_with(cx, |s| {
11940            s.select_anchors(selections);
11941            if let Some(pending_selection) = pending_selection {
11942                s.set_pending(pending_selection, SelectMode::Character);
11943            } else {
11944                s.clear_pending();
11945            }
11946        });
11947        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11948    }
11949
11950    fn push_to_selection_history(&mut self) {
11951        self.selection_history.push(SelectionHistoryEntry {
11952            selections: self.selections.disjoint_anchors(),
11953            select_next_state: self.select_next_state.clone(),
11954            select_prev_state: self.select_prev_state.clone(),
11955            add_selections_state: self.add_selections_state.clone(),
11956        });
11957    }
11958
11959    pub fn transact(
11960        &mut self,
11961        window: &mut Window,
11962        cx: &mut Context<Self>,
11963        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11964    ) -> Option<TransactionId> {
11965        self.start_transaction_at(Instant::now(), window, cx);
11966        update(self, window, cx);
11967        self.end_transaction_at(Instant::now(), cx)
11968    }
11969
11970    pub fn start_transaction_at(
11971        &mut self,
11972        now: Instant,
11973        window: &mut Window,
11974        cx: &mut Context<Self>,
11975    ) {
11976        self.end_selection(window, cx);
11977        if let Some(tx_id) = self
11978            .buffer
11979            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11980        {
11981            self.selection_history
11982                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11983            cx.emit(EditorEvent::TransactionBegun {
11984                transaction_id: tx_id,
11985            })
11986        }
11987    }
11988
11989    pub fn end_transaction_at(
11990        &mut self,
11991        now: Instant,
11992        cx: &mut Context<Self>,
11993    ) -> Option<TransactionId> {
11994        if let Some(transaction_id) = self
11995            .buffer
11996            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11997        {
11998            if let Some((_, end_selections)) =
11999                self.selection_history.transaction_mut(transaction_id)
12000            {
12001                *end_selections = Some(self.selections.disjoint_anchors());
12002            } else {
12003                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12004            }
12005
12006            cx.emit(EditorEvent::Edited { transaction_id });
12007            Some(transaction_id)
12008        } else {
12009            None
12010        }
12011    }
12012
12013    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12014        if self.selection_mark_mode {
12015            self.change_selections(None, window, cx, |s| {
12016                s.move_with(|_, sel| {
12017                    sel.collapse_to(sel.head(), SelectionGoal::None);
12018                });
12019            })
12020        }
12021        self.selection_mark_mode = true;
12022        cx.notify();
12023    }
12024
12025    pub fn swap_selection_ends(
12026        &mut self,
12027        _: &actions::SwapSelectionEnds,
12028        window: &mut Window,
12029        cx: &mut Context<Self>,
12030    ) {
12031        self.change_selections(None, window, cx, |s| {
12032            s.move_with(|_, sel| {
12033                if sel.start != sel.end {
12034                    sel.reversed = !sel.reversed
12035                }
12036            });
12037        });
12038        self.request_autoscroll(Autoscroll::newest(), cx);
12039        cx.notify();
12040    }
12041
12042    pub fn toggle_fold(
12043        &mut self,
12044        _: &actions::ToggleFold,
12045        window: &mut Window,
12046        cx: &mut Context<Self>,
12047    ) {
12048        if self.is_singleton(cx) {
12049            let selection = self.selections.newest::<Point>(cx);
12050
12051            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12052            let range = if selection.is_empty() {
12053                let point = selection.head().to_display_point(&display_map);
12054                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12055                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12056                    .to_point(&display_map);
12057                start..end
12058            } else {
12059                selection.range()
12060            };
12061            if display_map.folds_in_range(range).next().is_some() {
12062                self.unfold_lines(&Default::default(), window, cx)
12063            } else {
12064                self.fold(&Default::default(), window, cx)
12065            }
12066        } else {
12067            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12068            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12069                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12070                .map(|(snapshot, _, _)| snapshot.remote_id())
12071                .collect();
12072
12073            for buffer_id in buffer_ids {
12074                if self.is_buffer_folded(buffer_id, cx) {
12075                    self.unfold_buffer(buffer_id, cx);
12076                } else {
12077                    self.fold_buffer(buffer_id, cx);
12078                }
12079            }
12080        }
12081    }
12082
12083    pub fn toggle_fold_recursive(
12084        &mut self,
12085        _: &actions::ToggleFoldRecursive,
12086        window: &mut Window,
12087        cx: &mut Context<Self>,
12088    ) {
12089        let selection = self.selections.newest::<Point>(cx);
12090
12091        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12092        let range = if selection.is_empty() {
12093            let point = selection.head().to_display_point(&display_map);
12094            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12095            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12096                .to_point(&display_map);
12097            start..end
12098        } else {
12099            selection.range()
12100        };
12101        if display_map.folds_in_range(range).next().is_some() {
12102            self.unfold_recursive(&Default::default(), window, cx)
12103        } else {
12104            self.fold_recursive(&Default::default(), window, cx)
12105        }
12106    }
12107
12108    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12109        if self.is_singleton(cx) {
12110            let mut to_fold = Vec::new();
12111            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12112            let selections = self.selections.all_adjusted(cx);
12113
12114            for selection in selections {
12115                let range = selection.range().sorted();
12116                let buffer_start_row = range.start.row;
12117
12118                if range.start.row != range.end.row {
12119                    let mut found = false;
12120                    let mut row = range.start.row;
12121                    while row <= range.end.row {
12122                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12123                        {
12124                            found = true;
12125                            row = crease.range().end.row + 1;
12126                            to_fold.push(crease);
12127                        } else {
12128                            row += 1
12129                        }
12130                    }
12131                    if found {
12132                        continue;
12133                    }
12134                }
12135
12136                for row in (0..=range.start.row).rev() {
12137                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12138                        if crease.range().end.row >= buffer_start_row {
12139                            to_fold.push(crease);
12140                            if row <= range.start.row {
12141                                break;
12142                            }
12143                        }
12144                    }
12145                }
12146            }
12147
12148            self.fold_creases(to_fold, true, window, cx);
12149        } else {
12150            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12151
12152            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12153                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12154                .map(|(snapshot, _, _)| snapshot.remote_id())
12155                .collect();
12156            for buffer_id in buffer_ids {
12157                self.fold_buffer(buffer_id, cx);
12158            }
12159        }
12160    }
12161
12162    fn fold_at_level(
12163        &mut self,
12164        fold_at: &FoldAtLevel,
12165        window: &mut Window,
12166        cx: &mut Context<Self>,
12167    ) {
12168        if !self.buffer.read(cx).is_singleton() {
12169            return;
12170        }
12171
12172        let fold_at_level = fold_at.0;
12173        let snapshot = self.buffer.read(cx).snapshot(cx);
12174        let mut to_fold = Vec::new();
12175        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12176
12177        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12178            while start_row < end_row {
12179                match self
12180                    .snapshot(window, cx)
12181                    .crease_for_buffer_row(MultiBufferRow(start_row))
12182                {
12183                    Some(crease) => {
12184                        let nested_start_row = crease.range().start.row + 1;
12185                        let nested_end_row = crease.range().end.row;
12186
12187                        if current_level < fold_at_level {
12188                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12189                        } else if current_level == fold_at_level {
12190                            to_fold.push(crease);
12191                        }
12192
12193                        start_row = nested_end_row + 1;
12194                    }
12195                    None => start_row += 1,
12196                }
12197            }
12198        }
12199
12200        self.fold_creases(to_fold, true, window, cx);
12201    }
12202
12203    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12204        if self.buffer.read(cx).is_singleton() {
12205            let mut fold_ranges = Vec::new();
12206            let snapshot = self.buffer.read(cx).snapshot(cx);
12207
12208            for row in 0..snapshot.max_row().0 {
12209                if let Some(foldable_range) = self
12210                    .snapshot(window, cx)
12211                    .crease_for_buffer_row(MultiBufferRow(row))
12212                {
12213                    fold_ranges.push(foldable_range);
12214                }
12215            }
12216
12217            self.fold_creases(fold_ranges, true, window, cx);
12218        } else {
12219            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12220                editor
12221                    .update_in(&mut cx, |editor, _, cx| {
12222                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12223                            editor.fold_buffer(buffer_id, cx);
12224                        }
12225                    })
12226                    .ok();
12227            });
12228        }
12229    }
12230
12231    pub fn fold_function_bodies(
12232        &mut self,
12233        _: &actions::FoldFunctionBodies,
12234        window: &mut Window,
12235        cx: &mut Context<Self>,
12236    ) {
12237        let snapshot = self.buffer.read(cx).snapshot(cx);
12238
12239        let ranges = snapshot
12240            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12241            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12242            .collect::<Vec<_>>();
12243
12244        let creases = ranges
12245            .into_iter()
12246            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12247            .collect();
12248
12249        self.fold_creases(creases, true, window, cx);
12250    }
12251
12252    pub fn fold_recursive(
12253        &mut self,
12254        _: &actions::FoldRecursive,
12255        window: &mut Window,
12256        cx: &mut Context<Self>,
12257    ) {
12258        let mut to_fold = Vec::new();
12259        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12260        let selections = self.selections.all_adjusted(cx);
12261
12262        for selection in selections {
12263            let range = selection.range().sorted();
12264            let buffer_start_row = range.start.row;
12265
12266            if range.start.row != range.end.row {
12267                let mut found = false;
12268                for row in range.start.row..=range.end.row {
12269                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12270                        found = true;
12271                        to_fold.push(crease);
12272                    }
12273                }
12274                if found {
12275                    continue;
12276                }
12277            }
12278
12279            for row in (0..=range.start.row).rev() {
12280                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12281                    if crease.range().end.row >= buffer_start_row {
12282                        to_fold.push(crease);
12283                    } else {
12284                        break;
12285                    }
12286                }
12287            }
12288        }
12289
12290        self.fold_creases(to_fold, true, window, cx);
12291    }
12292
12293    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12294        let buffer_row = fold_at.buffer_row;
12295        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12296
12297        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12298            let autoscroll = self
12299                .selections
12300                .all::<Point>(cx)
12301                .iter()
12302                .any(|selection| crease.range().overlaps(&selection.range()));
12303
12304            self.fold_creases(vec![crease], autoscroll, window, cx);
12305        }
12306    }
12307
12308    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12309        if self.is_singleton(cx) {
12310            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12311            let buffer = &display_map.buffer_snapshot;
12312            let selections = self.selections.all::<Point>(cx);
12313            let ranges = selections
12314                .iter()
12315                .map(|s| {
12316                    let range = s.display_range(&display_map).sorted();
12317                    let mut start = range.start.to_point(&display_map);
12318                    let mut end = range.end.to_point(&display_map);
12319                    start.column = 0;
12320                    end.column = buffer.line_len(MultiBufferRow(end.row));
12321                    start..end
12322                })
12323                .collect::<Vec<_>>();
12324
12325            self.unfold_ranges(&ranges, true, true, cx);
12326        } else {
12327            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12328            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12329                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12330                .map(|(snapshot, _, _)| snapshot.remote_id())
12331                .collect();
12332            for buffer_id in buffer_ids {
12333                self.unfold_buffer(buffer_id, cx);
12334            }
12335        }
12336    }
12337
12338    pub fn unfold_recursive(
12339        &mut self,
12340        _: &UnfoldRecursive,
12341        _window: &mut Window,
12342        cx: &mut Context<Self>,
12343    ) {
12344        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12345        let selections = self.selections.all::<Point>(cx);
12346        let ranges = selections
12347            .iter()
12348            .map(|s| {
12349                let mut range = s.display_range(&display_map).sorted();
12350                *range.start.column_mut() = 0;
12351                *range.end.column_mut() = display_map.line_len(range.end.row());
12352                let start = range.start.to_point(&display_map);
12353                let end = range.end.to_point(&display_map);
12354                start..end
12355            })
12356            .collect::<Vec<_>>();
12357
12358        self.unfold_ranges(&ranges, true, true, cx);
12359    }
12360
12361    pub fn unfold_at(
12362        &mut self,
12363        unfold_at: &UnfoldAt,
12364        _window: &mut Window,
12365        cx: &mut Context<Self>,
12366    ) {
12367        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12368
12369        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12370            ..Point::new(
12371                unfold_at.buffer_row.0,
12372                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12373            );
12374
12375        let autoscroll = self
12376            .selections
12377            .all::<Point>(cx)
12378            .iter()
12379            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12380
12381        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12382    }
12383
12384    pub fn unfold_all(
12385        &mut self,
12386        _: &actions::UnfoldAll,
12387        _window: &mut Window,
12388        cx: &mut Context<Self>,
12389    ) {
12390        if self.buffer.read(cx).is_singleton() {
12391            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12392            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12393        } else {
12394            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12395                editor
12396                    .update(&mut cx, |editor, cx| {
12397                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12398                            editor.unfold_buffer(buffer_id, cx);
12399                        }
12400                    })
12401                    .ok();
12402            });
12403        }
12404    }
12405
12406    pub fn fold_selected_ranges(
12407        &mut self,
12408        _: &FoldSelectedRanges,
12409        window: &mut Window,
12410        cx: &mut Context<Self>,
12411    ) {
12412        let selections = self.selections.all::<Point>(cx);
12413        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12414        let line_mode = self.selections.line_mode;
12415        let ranges = selections
12416            .into_iter()
12417            .map(|s| {
12418                if line_mode {
12419                    let start = Point::new(s.start.row, 0);
12420                    let end = Point::new(
12421                        s.end.row,
12422                        display_map
12423                            .buffer_snapshot
12424                            .line_len(MultiBufferRow(s.end.row)),
12425                    );
12426                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12427                } else {
12428                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12429                }
12430            })
12431            .collect::<Vec<_>>();
12432        self.fold_creases(ranges, true, window, cx);
12433    }
12434
12435    pub fn fold_ranges<T: ToOffset + Clone>(
12436        &mut self,
12437        ranges: Vec<Range<T>>,
12438        auto_scroll: bool,
12439        window: &mut Window,
12440        cx: &mut Context<Self>,
12441    ) {
12442        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12443        let ranges = ranges
12444            .into_iter()
12445            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12446            .collect::<Vec<_>>();
12447        self.fold_creases(ranges, auto_scroll, window, cx);
12448    }
12449
12450    pub fn fold_creases<T: ToOffset + Clone>(
12451        &mut self,
12452        creases: Vec<Crease<T>>,
12453        auto_scroll: bool,
12454        window: &mut Window,
12455        cx: &mut Context<Self>,
12456    ) {
12457        if creases.is_empty() {
12458            return;
12459        }
12460
12461        let mut buffers_affected = HashSet::default();
12462        let multi_buffer = self.buffer().read(cx);
12463        for crease in &creases {
12464            if let Some((_, buffer, _)) =
12465                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12466            {
12467                buffers_affected.insert(buffer.read(cx).remote_id());
12468            };
12469        }
12470
12471        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12472
12473        if auto_scroll {
12474            self.request_autoscroll(Autoscroll::fit(), cx);
12475        }
12476
12477        cx.notify();
12478
12479        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12480            // Clear diagnostics block when folding a range that contains it.
12481            let snapshot = self.snapshot(window, cx);
12482            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12483                drop(snapshot);
12484                self.active_diagnostics = Some(active_diagnostics);
12485                self.dismiss_diagnostics(cx);
12486            } else {
12487                self.active_diagnostics = Some(active_diagnostics);
12488            }
12489        }
12490
12491        self.scrollbar_marker_state.dirty = true;
12492    }
12493
12494    /// Removes any folds whose ranges intersect any of the given ranges.
12495    pub fn unfold_ranges<T: ToOffset + Clone>(
12496        &mut self,
12497        ranges: &[Range<T>],
12498        inclusive: bool,
12499        auto_scroll: bool,
12500        cx: &mut Context<Self>,
12501    ) {
12502        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12503            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12504        });
12505    }
12506
12507    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12508        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12509            return;
12510        }
12511        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12512        self.display_map
12513            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12514        cx.emit(EditorEvent::BufferFoldToggled {
12515            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12516            folded: true,
12517        });
12518        cx.notify();
12519    }
12520
12521    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12522        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12523            return;
12524        }
12525        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12526        self.display_map.update(cx, |display_map, cx| {
12527            display_map.unfold_buffer(buffer_id, cx);
12528        });
12529        cx.emit(EditorEvent::BufferFoldToggled {
12530            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12531            folded: false,
12532        });
12533        cx.notify();
12534    }
12535
12536    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12537        self.display_map.read(cx).is_buffer_folded(buffer)
12538    }
12539
12540    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12541        self.display_map.read(cx).folded_buffers()
12542    }
12543
12544    /// Removes any folds with the given ranges.
12545    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12546        &mut self,
12547        ranges: &[Range<T>],
12548        type_id: TypeId,
12549        auto_scroll: bool,
12550        cx: &mut Context<Self>,
12551    ) {
12552        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12553            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12554        });
12555    }
12556
12557    fn remove_folds_with<T: ToOffset + Clone>(
12558        &mut self,
12559        ranges: &[Range<T>],
12560        auto_scroll: bool,
12561        cx: &mut Context<Self>,
12562        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12563    ) {
12564        if ranges.is_empty() {
12565            return;
12566        }
12567
12568        let mut buffers_affected = HashSet::default();
12569        let multi_buffer = self.buffer().read(cx);
12570        for range in ranges {
12571            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12572                buffers_affected.insert(buffer.read(cx).remote_id());
12573            };
12574        }
12575
12576        self.display_map.update(cx, update);
12577
12578        if auto_scroll {
12579            self.request_autoscroll(Autoscroll::fit(), cx);
12580        }
12581
12582        cx.notify();
12583        self.scrollbar_marker_state.dirty = true;
12584        self.active_indent_guides_state.dirty = true;
12585    }
12586
12587    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12588        self.display_map.read(cx).fold_placeholder.clone()
12589    }
12590
12591    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12592        self.buffer.update(cx, |buffer, cx| {
12593            buffer.set_all_diff_hunks_expanded(cx);
12594        });
12595    }
12596
12597    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12598        self.distinguish_unstaged_diff_hunks = true;
12599    }
12600
12601    pub fn expand_all_diff_hunks(
12602        &mut self,
12603        _: &ExpandAllHunkDiffs,
12604        _window: &mut Window,
12605        cx: &mut Context<Self>,
12606    ) {
12607        self.buffer.update(cx, |buffer, cx| {
12608            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12609        });
12610    }
12611
12612    pub fn toggle_selected_diff_hunks(
12613        &mut self,
12614        _: &ToggleSelectedDiffHunks,
12615        _window: &mut Window,
12616        cx: &mut Context<Self>,
12617    ) {
12618        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12619        self.toggle_diff_hunks_in_ranges(ranges, cx);
12620    }
12621
12622    fn diff_hunks_in_ranges<'a>(
12623        &'a self,
12624        ranges: &'a [Range<Anchor>],
12625        buffer: &'a MultiBufferSnapshot,
12626    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12627        ranges.iter().flat_map(move |range| {
12628            let end_excerpt_id = range.end.excerpt_id;
12629            let range = range.to_point(buffer);
12630            let mut peek_end = range.end;
12631            if range.end.row < buffer.max_row().0 {
12632                peek_end = Point::new(range.end.row + 1, 0);
12633            }
12634            buffer
12635                .diff_hunks_in_range(range.start..peek_end)
12636                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12637        })
12638    }
12639
12640    pub fn has_stageable_diff_hunks_in_ranges(
12641        &self,
12642        ranges: &[Range<Anchor>],
12643        snapshot: &MultiBufferSnapshot,
12644    ) -> bool {
12645        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12646        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12647    }
12648
12649    pub fn toggle_staged_selected_diff_hunks(
12650        &mut self,
12651        _: &ToggleStagedSelectedDiffHunks,
12652        _window: &mut Window,
12653        cx: &mut Context<Self>,
12654    ) {
12655        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12656        self.stage_or_unstage_diff_hunks(&ranges, cx);
12657    }
12658
12659    pub fn stage_or_unstage_diff_hunks(
12660        &mut self,
12661        ranges: &[Range<Anchor>],
12662        cx: &mut Context<Self>,
12663    ) {
12664        let Some(project) = &self.project else {
12665            return;
12666        };
12667        let snapshot = self.buffer.read(cx).snapshot(cx);
12668        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12669
12670        let chunk_by = self
12671            .diff_hunks_in_ranges(&ranges, &snapshot)
12672            .chunk_by(|hunk| hunk.buffer_id);
12673        for (buffer_id, hunks) in &chunk_by {
12674            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12675                log::debug!("no buffer for id");
12676                continue;
12677            };
12678            let buffer = buffer.read(cx).snapshot();
12679            let Some((repo, path)) = project
12680                .read(cx)
12681                .repository_and_path_for_buffer_id(buffer_id, cx)
12682            else {
12683                log::debug!("no git repo for buffer id");
12684                continue;
12685            };
12686            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12687                log::debug!("no diff for buffer id");
12688                continue;
12689            };
12690            let Some(secondary_diff) = diff.secondary_diff() else {
12691                log::debug!("no secondary diff for buffer id");
12692                continue;
12693            };
12694
12695            let edits = diff.secondary_edits_for_stage_or_unstage(
12696                stage,
12697                hunks.map(|hunk| {
12698                    (
12699                        hunk.diff_base_byte_range.clone(),
12700                        hunk.secondary_diff_base_byte_range.clone(),
12701                        hunk.buffer_range.clone(),
12702                    )
12703                }),
12704                &buffer,
12705            );
12706
12707            let index_base = secondary_diff.base_text().map_or_else(
12708                || Rope::from(""),
12709                |snapshot| snapshot.text.as_rope().clone(),
12710            );
12711            let index_buffer = cx.new(|cx| {
12712                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12713            });
12714            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12715                index_buffer.edit(edits, None, cx);
12716                index_buffer.snapshot().as_rope().to_string()
12717            });
12718            let new_index_text = if new_index_text.is_empty()
12719                && (diff.is_single_insertion
12720                    || buffer
12721                        .file()
12722                        .map_or(false, |file| file.disk_state() == DiskState::New))
12723            {
12724                log::debug!("removing from index");
12725                None
12726            } else {
12727                Some(new_index_text)
12728            };
12729
12730            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12731        }
12732    }
12733
12734    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12735        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12736        self.buffer
12737            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12738    }
12739
12740    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12741        self.buffer.update(cx, |buffer, cx| {
12742            let ranges = vec![Anchor::min()..Anchor::max()];
12743            if !buffer.all_diff_hunks_expanded()
12744                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12745            {
12746                buffer.collapse_diff_hunks(ranges, cx);
12747                true
12748            } else {
12749                false
12750            }
12751        })
12752    }
12753
12754    fn toggle_diff_hunks_in_ranges(
12755        &mut self,
12756        ranges: Vec<Range<Anchor>>,
12757        cx: &mut Context<'_, Editor>,
12758    ) {
12759        self.buffer.update(cx, |buffer, cx| {
12760            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12761            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12762        })
12763    }
12764
12765    fn toggle_diff_hunks_in_ranges_narrow(
12766        &mut self,
12767        ranges: Vec<Range<Anchor>>,
12768        cx: &mut Context<'_, Editor>,
12769    ) {
12770        self.buffer.update(cx, |buffer, cx| {
12771            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12772            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12773        })
12774    }
12775
12776    pub(crate) fn apply_all_diff_hunks(
12777        &mut self,
12778        _: &ApplyAllDiffHunks,
12779        window: &mut Window,
12780        cx: &mut Context<Self>,
12781    ) {
12782        let buffers = self.buffer.read(cx).all_buffers();
12783        for branch_buffer in buffers {
12784            branch_buffer.update(cx, |branch_buffer, cx| {
12785                branch_buffer.merge_into_base(Vec::new(), cx);
12786            });
12787        }
12788
12789        if let Some(project) = self.project.clone() {
12790            self.save(true, project, window, cx).detach_and_log_err(cx);
12791        }
12792    }
12793
12794    pub(crate) fn apply_selected_diff_hunks(
12795        &mut self,
12796        _: &ApplyDiffHunk,
12797        window: &mut Window,
12798        cx: &mut Context<Self>,
12799    ) {
12800        let snapshot = self.snapshot(window, cx);
12801        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12802        let mut ranges_by_buffer = HashMap::default();
12803        self.transact(window, cx, |editor, _window, cx| {
12804            for hunk in hunks {
12805                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12806                    ranges_by_buffer
12807                        .entry(buffer.clone())
12808                        .or_insert_with(Vec::new)
12809                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12810                }
12811            }
12812
12813            for (buffer, ranges) in ranges_by_buffer {
12814                buffer.update(cx, |buffer, cx| {
12815                    buffer.merge_into_base(ranges, cx);
12816                });
12817            }
12818        });
12819
12820        if let Some(project) = self.project.clone() {
12821            self.save(true, project, window, cx).detach_and_log_err(cx);
12822        }
12823    }
12824
12825    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12826        if hovered != self.gutter_hovered {
12827            self.gutter_hovered = hovered;
12828            cx.notify();
12829        }
12830    }
12831
12832    pub fn insert_blocks(
12833        &mut self,
12834        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12835        autoscroll: Option<Autoscroll>,
12836        cx: &mut Context<Self>,
12837    ) -> Vec<CustomBlockId> {
12838        let blocks = self
12839            .display_map
12840            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12841        if let Some(autoscroll) = autoscroll {
12842            self.request_autoscroll(autoscroll, cx);
12843        }
12844        cx.notify();
12845        blocks
12846    }
12847
12848    pub fn resize_blocks(
12849        &mut self,
12850        heights: HashMap<CustomBlockId, u32>,
12851        autoscroll: Option<Autoscroll>,
12852        cx: &mut Context<Self>,
12853    ) {
12854        self.display_map
12855            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12856        if let Some(autoscroll) = autoscroll {
12857            self.request_autoscroll(autoscroll, cx);
12858        }
12859        cx.notify();
12860    }
12861
12862    pub fn replace_blocks(
12863        &mut self,
12864        renderers: HashMap<CustomBlockId, RenderBlock>,
12865        autoscroll: Option<Autoscroll>,
12866        cx: &mut Context<Self>,
12867    ) {
12868        self.display_map
12869            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12870        if let Some(autoscroll) = autoscroll {
12871            self.request_autoscroll(autoscroll, cx);
12872        }
12873        cx.notify();
12874    }
12875
12876    pub fn remove_blocks(
12877        &mut self,
12878        block_ids: HashSet<CustomBlockId>,
12879        autoscroll: Option<Autoscroll>,
12880        cx: &mut Context<Self>,
12881    ) {
12882        self.display_map.update(cx, |display_map, cx| {
12883            display_map.remove_blocks(block_ids, cx)
12884        });
12885        if let Some(autoscroll) = autoscroll {
12886            self.request_autoscroll(autoscroll, cx);
12887        }
12888        cx.notify();
12889    }
12890
12891    pub fn row_for_block(
12892        &self,
12893        block_id: CustomBlockId,
12894        cx: &mut Context<Self>,
12895    ) -> Option<DisplayRow> {
12896        self.display_map
12897            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12898    }
12899
12900    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12901        self.focused_block = Some(focused_block);
12902    }
12903
12904    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12905        self.focused_block.take()
12906    }
12907
12908    pub fn insert_creases(
12909        &mut self,
12910        creases: impl IntoIterator<Item = Crease<Anchor>>,
12911        cx: &mut Context<Self>,
12912    ) -> Vec<CreaseId> {
12913        self.display_map
12914            .update(cx, |map, cx| map.insert_creases(creases, cx))
12915    }
12916
12917    pub fn remove_creases(
12918        &mut self,
12919        ids: impl IntoIterator<Item = CreaseId>,
12920        cx: &mut Context<Self>,
12921    ) {
12922        self.display_map
12923            .update(cx, |map, cx| map.remove_creases(ids, cx));
12924    }
12925
12926    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12927        self.display_map
12928            .update(cx, |map, cx| map.snapshot(cx))
12929            .longest_row()
12930    }
12931
12932    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12933        self.display_map
12934            .update(cx, |map, cx| map.snapshot(cx))
12935            .max_point()
12936    }
12937
12938    pub fn text(&self, cx: &App) -> String {
12939        self.buffer.read(cx).read(cx).text()
12940    }
12941
12942    pub fn is_empty(&self, cx: &App) -> bool {
12943        self.buffer.read(cx).read(cx).is_empty()
12944    }
12945
12946    pub fn text_option(&self, cx: &App) -> Option<String> {
12947        let text = self.text(cx);
12948        let text = text.trim();
12949
12950        if text.is_empty() {
12951            return None;
12952        }
12953
12954        Some(text.to_string())
12955    }
12956
12957    pub fn set_text(
12958        &mut self,
12959        text: impl Into<Arc<str>>,
12960        window: &mut Window,
12961        cx: &mut Context<Self>,
12962    ) {
12963        self.transact(window, cx, |this, _, cx| {
12964            this.buffer
12965                .read(cx)
12966                .as_singleton()
12967                .expect("you can only call set_text on editors for singleton buffers")
12968                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12969        });
12970    }
12971
12972    pub fn display_text(&self, cx: &mut App) -> String {
12973        self.display_map
12974            .update(cx, |map, cx| map.snapshot(cx))
12975            .text()
12976    }
12977
12978    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12979        let mut wrap_guides = smallvec::smallvec![];
12980
12981        if self.show_wrap_guides == Some(false) {
12982            return wrap_guides;
12983        }
12984
12985        let settings = self.buffer.read(cx).settings_at(0, cx);
12986        if settings.show_wrap_guides {
12987            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12988                wrap_guides.push((soft_wrap as usize, true));
12989            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12990                wrap_guides.push((soft_wrap as usize, true));
12991            }
12992            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12993        }
12994
12995        wrap_guides
12996    }
12997
12998    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12999        let settings = self.buffer.read(cx).settings_at(0, cx);
13000        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13001        match mode {
13002            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13003                SoftWrap::None
13004            }
13005            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13006            language_settings::SoftWrap::PreferredLineLength => {
13007                SoftWrap::Column(settings.preferred_line_length)
13008            }
13009            language_settings::SoftWrap::Bounded => {
13010                SoftWrap::Bounded(settings.preferred_line_length)
13011            }
13012        }
13013    }
13014
13015    pub fn set_soft_wrap_mode(
13016        &mut self,
13017        mode: language_settings::SoftWrap,
13018
13019        cx: &mut Context<Self>,
13020    ) {
13021        self.soft_wrap_mode_override = Some(mode);
13022        cx.notify();
13023    }
13024
13025    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13026        self.text_style_refinement = Some(style);
13027    }
13028
13029    /// called by the Element so we know what style we were most recently rendered with.
13030    pub(crate) fn set_style(
13031        &mut self,
13032        style: EditorStyle,
13033        window: &mut Window,
13034        cx: &mut Context<Self>,
13035    ) {
13036        let rem_size = window.rem_size();
13037        self.display_map.update(cx, |map, cx| {
13038            map.set_font(
13039                style.text.font(),
13040                style.text.font_size.to_pixels(rem_size),
13041                cx,
13042            )
13043        });
13044        self.style = Some(style);
13045    }
13046
13047    pub fn style(&self) -> Option<&EditorStyle> {
13048        self.style.as_ref()
13049    }
13050
13051    // Called by the element. This method is not designed to be called outside of the editor
13052    // element's layout code because it does not notify when rewrapping is computed synchronously.
13053    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13054        self.display_map
13055            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13056    }
13057
13058    pub fn set_soft_wrap(&mut self) {
13059        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13060    }
13061
13062    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13063        if self.soft_wrap_mode_override.is_some() {
13064            self.soft_wrap_mode_override.take();
13065        } else {
13066            let soft_wrap = match self.soft_wrap_mode(cx) {
13067                SoftWrap::GitDiff => return,
13068                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13069                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13070                    language_settings::SoftWrap::None
13071                }
13072            };
13073            self.soft_wrap_mode_override = Some(soft_wrap);
13074        }
13075        cx.notify();
13076    }
13077
13078    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13079        let Some(workspace) = self.workspace() else {
13080            return;
13081        };
13082        let fs = workspace.read(cx).app_state().fs.clone();
13083        let current_show = TabBarSettings::get_global(cx).show;
13084        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13085            setting.show = Some(!current_show);
13086        });
13087    }
13088
13089    pub fn toggle_indent_guides(
13090        &mut self,
13091        _: &ToggleIndentGuides,
13092        _: &mut Window,
13093        cx: &mut Context<Self>,
13094    ) {
13095        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13096            self.buffer
13097                .read(cx)
13098                .settings_at(0, cx)
13099                .indent_guides
13100                .enabled
13101        });
13102        self.show_indent_guides = Some(!currently_enabled);
13103        cx.notify();
13104    }
13105
13106    fn should_show_indent_guides(&self) -> Option<bool> {
13107        self.show_indent_guides
13108    }
13109
13110    pub fn toggle_line_numbers(
13111        &mut self,
13112        _: &ToggleLineNumbers,
13113        _: &mut Window,
13114        cx: &mut Context<Self>,
13115    ) {
13116        let mut editor_settings = EditorSettings::get_global(cx).clone();
13117        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13118        EditorSettings::override_global(editor_settings, cx);
13119    }
13120
13121    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13122        self.use_relative_line_numbers
13123            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13124    }
13125
13126    pub fn toggle_relative_line_numbers(
13127        &mut self,
13128        _: &ToggleRelativeLineNumbers,
13129        _: &mut Window,
13130        cx: &mut Context<Self>,
13131    ) {
13132        let is_relative = self.should_use_relative_line_numbers(cx);
13133        self.set_relative_line_number(Some(!is_relative), cx)
13134    }
13135
13136    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13137        self.use_relative_line_numbers = is_relative;
13138        cx.notify();
13139    }
13140
13141    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13142        self.show_gutter = show_gutter;
13143        cx.notify();
13144    }
13145
13146    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13147        self.show_scrollbars = show_scrollbars;
13148        cx.notify();
13149    }
13150
13151    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13152        self.show_line_numbers = Some(show_line_numbers);
13153        cx.notify();
13154    }
13155
13156    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13157        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13158        cx.notify();
13159    }
13160
13161    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13162        self.show_code_actions = Some(show_code_actions);
13163        cx.notify();
13164    }
13165
13166    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13167        self.show_runnables = Some(show_runnables);
13168        cx.notify();
13169    }
13170
13171    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13172        if self.display_map.read(cx).masked != masked {
13173            self.display_map.update(cx, |map, _| map.masked = masked);
13174        }
13175        cx.notify()
13176    }
13177
13178    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13179        self.show_wrap_guides = Some(show_wrap_guides);
13180        cx.notify();
13181    }
13182
13183    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13184        self.show_indent_guides = Some(show_indent_guides);
13185        cx.notify();
13186    }
13187
13188    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13189        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13190            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13191                if let Some(dir) = file.abs_path(cx).parent() {
13192                    return Some(dir.to_owned());
13193                }
13194            }
13195
13196            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13197                return Some(project_path.path.to_path_buf());
13198            }
13199        }
13200
13201        None
13202    }
13203
13204    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13205        self.active_excerpt(cx)?
13206            .1
13207            .read(cx)
13208            .file()
13209            .and_then(|f| f.as_local())
13210    }
13211
13212    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13213        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13214            let buffer = buffer.read(cx);
13215            if let Some(project_path) = buffer.project_path(cx) {
13216                let project = self.project.as_ref()?.read(cx);
13217                project.absolute_path(&project_path, cx)
13218            } else {
13219                buffer
13220                    .file()
13221                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13222            }
13223        })
13224    }
13225
13226    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13227        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13228            let project_path = buffer.read(cx).project_path(cx)?;
13229            let project = self.project.as_ref()?.read(cx);
13230            let entry = project.entry_for_path(&project_path, cx)?;
13231            let path = entry.path.to_path_buf();
13232            Some(path)
13233        })
13234    }
13235
13236    pub fn reveal_in_finder(
13237        &mut self,
13238        _: &RevealInFileManager,
13239        _window: &mut Window,
13240        cx: &mut Context<Self>,
13241    ) {
13242        if let Some(target) = self.target_file(cx) {
13243            cx.reveal_path(&target.abs_path(cx));
13244        }
13245    }
13246
13247    pub fn copy_path(
13248        &mut self,
13249        _: &zed_actions::workspace::CopyPath,
13250        _window: &mut Window,
13251        cx: &mut Context<Self>,
13252    ) {
13253        if let Some(path) = self.target_file_abs_path(cx) {
13254            if let Some(path) = path.to_str() {
13255                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13256            }
13257        }
13258    }
13259
13260    pub fn copy_relative_path(
13261        &mut self,
13262        _: &zed_actions::workspace::CopyRelativePath,
13263        _window: &mut Window,
13264        cx: &mut Context<Self>,
13265    ) {
13266        if let Some(path) = self.target_file_path(cx) {
13267            if let Some(path) = path.to_str() {
13268                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13269            }
13270        }
13271    }
13272
13273    pub fn copy_file_name_without_extension(
13274        &mut self,
13275        _: &CopyFileNameWithoutExtension,
13276        _: &mut Window,
13277        cx: &mut Context<Self>,
13278    ) {
13279        if let Some(file) = self.target_file(cx) {
13280            if let Some(file_stem) = file.path().file_stem() {
13281                if let Some(name) = file_stem.to_str() {
13282                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13283                }
13284            }
13285        }
13286    }
13287
13288    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13289        if let Some(file) = self.target_file(cx) {
13290            if let Some(file_name) = file.path().file_name() {
13291                if let Some(name) = file_name.to_str() {
13292                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13293                }
13294            }
13295        }
13296    }
13297
13298    pub fn toggle_git_blame(
13299        &mut self,
13300        _: &ToggleGitBlame,
13301        window: &mut Window,
13302        cx: &mut Context<Self>,
13303    ) {
13304        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13305
13306        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13307            self.start_git_blame(true, window, cx);
13308        }
13309
13310        cx.notify();
13311    }
13312
13313    pub fn toggle_git_blame_inline(
13314        &mut self,
13315        _: &ToggleGitBlameInline,
13316        window: &mut Window,
13317        cx: &mut Context<Self>,
13318    ) {
13319        self.toggle_git_blame_inline_internal(true, window, cx);
13320        cx.notify();
13321    }
13322
13323    pub fn git_blame_inline_enabled(&self) -> bool {
13324        self.git_blame_inline_enabled
13325    }
13326
13327    pub fn toggle_selection_menu(
13328        &mut self,
13329        _: &ToggleSelectionMenu,
13330        _: &mut Window,
13331        cx: &mut Context<Self>,
13332    ) {
13333        self.show_selection_menu = self
13334            .show_selection_menu
13335            .map(|show_selections_menu| !show_selections_menu)
13336            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13337
13338        cx.notify();
13339    }
13340
13341    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13342        self.show_selection_menu
13343            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13344    }
13345
13346    fn start_git_blame(
13347        &mut self,
13348        user_triggered: bool,
13349        window: &mut Window,
13350        cx: &mut Context<Self>,
13351    ) {
13352        if let Some(project) = self.project.as_ref() {
13353            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13354                return;
13355            };
13356
13357            if buffer.read(cx).file().is_none() {
13358                return;
13359            }
13360
13361            let focused = self.focus_handle(cx).contains_focused(window, cx);
13362
13363            let project = project.clone();
13364            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13365            self.blame_subscription =
13366                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13367            self.blame = Some(blame);
13368        }
13369    }
13370
13371    fn toggle_git_blame_inline_internal(
13372        &mut self,
13373        user_triggered: bool,
13374        window: &mut Window,
13375        cx: &mut Context<Self>,
13376    ) {
13377        if self.git_blame_inline_enabled {
13378            self.git_blame_inline_enabled = false;
13379            self.show_git_blame_inline = false;
13380            self.show_git_blame_inline_delay_task.take();
13381        } else {
13382            self.git_blame_inline_enabled = true;
13383            self.start_git_blame_inline(user_triggered, window, cx);
13384        }
13385
13386        cx.notify();
13387    }
13388
13389    fn start_git_blame_inline(
13390        &mut self,
13391        user_triggered: bool,
13392        window: &mut Window,
13393        cx: &mut Context<Self>,
13394    ) {
13395        self.start_git_blame(user_triggered, window, cx);
13396
13397        if ProjectSettings::get_global(cx)
13398            .git
13399            .inline_blame_delay()
13400            .is_some()
13401        {
13402            self.start_inline_blame_timer(window, cx);
13403        } else {
13404            self.show_git_blame_inline = true
13405        }
13406    }
13407
13408    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13409        self.blame.as_ref()
13410    }
13411
13412    pub fn show_git_blame_gutter(&self) -> bool {
13413        self.show_git_blame_gutter
13414    }
13415
13416    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13417        self.show_git_blame_gutter && self.has_blame_entries(cx)
13418    }
13419
13420    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13421        self.show_git_blame_inline
13422            && self.focus_handle.is_focused(window)
13423            && !self.newest_selection_head_on_empty_line(cx)
13424            && self.has_blame_entries(cx)
13425    }
13426
13427    fn has_blame_entries(&self, cx: &App) -> bool {
13428        self.blame()
13429            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13430    }
13431
13432    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13433        let cursor_anchor = self.selections.newest_anchor().head();
13434
13435        let snapshot = self.buffer.read(cx).snapshot(cx);
13436        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13437
13438        snapshot.line_len(buffer_row) == 0
13439    }
13440
13441    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13442        let buffer_and_selection = maybe!({
13443            let selection = self.selections.newest::<Point>(cx);
13444            let selection_range = selection.range();
13445
13446            let multi_buffer = self.buffer().read(cx);
13447            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13448            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13449
13450            let (buffer, range, _) = if selection.reversed {
13451                buffer_ranges.first()
13452            } else {
13453                buffer_ranges.last()
13454            }?;
13455
13456            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13457                ..text::ToPoint::to_point(&range.end, &buffer).row;
13458            Some((
13459                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13460                selection,
13461            ))
13462        });
13463
13464        let Some((buffer, selection)) = buffer_and_selection else {
13465            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13466        };
13467
13468        let Some(project) = self.project.as_ref() else {
13469            return Task::ready(Err(anyhow!("editor does not have project")));
13470        };
13471
13472        project.update(cx, |project, cx| {
13473            project.get_permalink_to_line(&buffer, selection, cx)
13474        })
13475    }
13476
13477    pub fn copy_permalink_to_line(
13478        &mut self,
13479        _: &CopyPermalinkToLine,
13480        window: &mut Window,
13481        cx: &mut Context<Self>,
13482    ) {
13483        let permalink_task = self.get_permalink_to_line(cx);
13484        let workspace = self.workspace();
13485
13486        cx.spawn_in(window, |_, mut cx| async move {
13487            match permalink_task.await {
13488                Ok(permalink) => {
13489                    cx.update(|_, cx| {
13490                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13491                    })
13492                    .ok();
13493                }
13494                Err(err) => {
13495                    let message = format!("Failed to copy permalink: {err}");
13496
13497                    Err::<(), anyhow::Error>(err).log_err();
13498
13499                    if let Some(workspace) = workspace {
13500                        workspace
13501                            .update_in(&mut cx, |workspace, _, cx| {
13502                                struct CopyPermalinkToLine;
13503
13504                                workspace.show_toast(
13505                                    Toast::new(
13506                                        NotificationId::unique::<CopyPermalinkToLine>(),
13507                                        message,
13508                                    ),
13509                                    cx,
13510                                )
13511                            })
13512                            .ok();
13513                    }
13514                }
13515            }
13516        })
13517        .detach();
13518    }
13519
13520    pub fn copy_file_location(
13521        &mut self,
13522        _: &CopyFileLocation,
13523        _: &mut Window,
13524        cx: &mut Context<Self>,
13525    ) {
13526        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13527        if let Some(file) = self.target_file(cx) {
13528            if let Some(path) = file.path().to_str() {
13529                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13530            }
13531        }
13532    }
13533
13534    pub fn open_permalink_to_line(
13535        &mut self,
13536        _: &OpenPermalinkToLine,
13537        window: &mut Window,
13538        cx: &mut Context<Self>,
13539    ) {
13540        let permalink_task = self.get_permalink_to_line(cx);
13541        let workspace = self.workspace();
13542
13543        cx.spawn_in(window, |_, mut cx| async move {
13544            match permalink_task.await {
13545                Ok(permalink) => {
13546                    cx.update(|_, cx| {
13547                        cx.open_url(permalink.as_ref());
13548                    })
13549                    .ok();
13550                }
13551                Err(err) => {
13552                    let message = format!("Failed to open permalink: {err}");
13553
13554                    Err::<(), anyhow::Error>(err).log_err();
13555
13556                    if let Some(workspace) = workspace {
13557                        workspace
13558                            .update(&mut cx, |workspace, cx| {
13559                                struct OpenPermalinkToLine;
13560
13561                                workspace.show_toast(
13562                                    Toast::new(
13563                                        NotificationId::unique::<OpenPermalinkToLine>(),
13564                                        message,
13565                                    ),
13566                                    cx,
13567                                )
13568                            })
13569                            .ok();
13570                    }
13571                }
13572            }
13573        })
13574        .detach();
13575    }
13576
13577    pub fn insert_uuid_v4(
13578        &mut self,
13579        _: &InsertUuidV4,
13580        window: &mut Window,
13581        cx: &mut Context<Self>,
13582    ) {
13583        self.insert_uuid(UuidVersion::V4, window, cx);
13584    }
13585
13586    pub fn insert_uuid_v7(
13587        &mut self,
13588        _: &InsertUuidV7,
13589        window: &mut Window,
13590        cx: &mut Context<Self>,
13591    ) {
13592        self.insert_uuid(UuidVersion::V7, window, cx);
13593    }
13594
13595    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13596        self.transact(window, cx, |this, window, cx| {
13597            let edits = this
13598                .selections
13599                .all::<Point>(cx)
13600                .into_iter()
13601                .map(|selection| {
13602                    let uuid = match version {
13603                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13604                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13605                    };
13606
13607                    (selection.range(), uuid.to_string())
13608                });
13609            this.edit(edits, cx);
13610            this.refresh_inline_completion(true, false, window, cx);
13611        });
13612    }
13613
13614    pub fn open_selections_in_multibuffer(
13615        &mut self,
13616        _: &OpenSelectionsInMultibuffer,
13617        window: &mut Window,
13618        cx: &mut Context<Self>,
13619    ) {
13620        let multibuffer = self.buffer.read(cx);
13621
13622        let Some(buffer) = multibuffer.as_singleton() else {
13623            return;
13624        };
13625
13626        let Some(workspace) = self.workspace() else {
13627            return;
13628        };
13629
13630        let locations = self
13631            .selections
13632            .disjoint_anchors()
13633            .iter()
13634            .map(|range| Location {
13635                buffer: buffer.clone(),
13636                range: range.start.text_anchor..range.end.text_anchor,
13637            })
13638            .collect::<Vec<_>>();
13639
13640        let title = multibuffer.title(cx).to_string();
13641
13642        cx.spawn_in(window, |_, mut cx| async move {
13643            workspace.update_in(&mut cx, |workspace, window, cx| {
13644                Self::open_locations_in_multibuffer(
13645                    workspace,
13646                    locations,
13647                    format!("Selections for '{title}'"),
13648                    false,
13649                    MultibufferSelectionMode::All,
13650                    window,
13651                    cx,
13652                );
13653            })
13654        })
13655        .detach();
13656    }
13657
13658    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13659    /// last highlight added will be used.
13660    ///
13661    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13662    pub fn highlight_rows<T: 'static>(
13663        &mut self,
13664        range: Range<Anchor>,
13665        color: Hsla,
13666        should_autoscroll: bool,
13667        cx: &mut Context<Self>,
13668    ) {
13669        let snapshot = self.buffer().read(cx).snapshot(cx);
13670        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13671        let ix = row_highlights.binary_search_by(|highlight| {
13672            Ordering::Equal
13673                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13674                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13675        });
13676
13677        if let Err(mut ix) = ix {
13678            let index = post_inc(&mut self.highlight_order);
13679
13680            // If this range intersects with the preceding highlight, then merge it with
13681            // the preceding highlight. Otherwise insert a new highlight.
13682            let mut merged = false;
13683            if ix > 0 {
13684                let prev_highlight = &mut row_highlights[ix - 1];
13685                if prev_highlight
13686                    .range
13687                    .end
13688                    .cmp(&range.start, &snapshot)
13689                    .is_ge()
13690                {
13691                    ix -= 1;
13692                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13693                        prev_highlight.range.end = range.end;
13694                    }
13695                    merged = true;
13696                    prev_highlight.index = index;
13697                    prev_highlight.color = color;
13698                    prev_highlight.should_autoscroll = should_autoscroll;
13699                }
13700            }
13701
13702            if !merged {
13703                row_highlights.insert(
13704                    ix,
13705                    RowHighlight {
13706                        range: range.clone(),
13707                        index,
13708                        color,
13709                        should_autoscroll,
13710                    },
13711                );
13712            }
13713
13714            // If any of the following highlights intersect with this one, merge them.
13715            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13716                let highlight = &row_highlights[ix];
13717                if next_highlight
13718                    .range
13719                    .start
13720                    .cmp(&highlight.range.end, &snapshot)
13721                    .is_le()
13722                {
13723                    if next_highlight
13724                        .range
13725                        .end
13726                        .cmp(&highlight.range.end, &snapshot)
13727                        .is_gt()
13728                    {
13729                        row_highlights[ix].range.end = next_highlight.range.end;
13730                    }
13731                    row_highlights.remove(ix + 1);
13732                } else {
13733                    break;
13734                }
13735            }
13736        }
13737    }
13738
13739    /// Remove any highlighted row ranges of the given type that intersect the
13740    /// given ranges.
13741    pub fn remove_highlighted_rows<T: 'static>(
13742        &mut self,
13743        ranges_to_remove: Vec<Range<Anchor>>,
13744        cx: &mut Context<Self>,
13745    ) {
13746        let snapshot = self.buffer().read(cx).snapshot(cx);
13747        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13748        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13749        row_highlights.retain(|highlight| {
13750            while let Some(range_to_remove) = ranges_to_remove.peek() {
13751                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13752                    Ordering::Less | Ordering::Equal => {
13753                        ranges_to_remove.next();
13754                    }
13755                    Ordering::Greater => {
13756                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13757                            Ordering::Less | Ordering::Equal => {
13758                                return false;
13759                            }
13760                            Ordering::Greater => break,
13761                        }
13762                    }
13763                }
13764            }
13765
13766            true
13767        })
13768    }
13769
13770    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13771    pub fn clear_row_highlights<T: 'static>(&mut self) {
13772        self.highlighted_rows.remove(&TypeId::of::<T>());
13773    }
13774
13775    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13776    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13777        self.highlighted_rows
13778            .get(&TypeId::of::<T>())
13779            .map_or(&[] as &[_], |vec| vec.as_slice())
13780            .iter()
13781            .map(|highlight| (highlight.range.clone(), highlight.color))
13782    }
13783
13784    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13785    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13786    /// Allows to ignore certain kinds of highlights.
13787    pub fn highlighted_display_rows(
13788        &self,
13789        window: &mut Window,
13790        cx: &mut App,
13791    ) -> BTreeMap<DisplayRow, Background> {
13792        let snapshot = self.snapshot(window, cx);
13793        let mut used_highlight_orders = HashMap::default();
13794        self.highlighted_rows
13795            .iter()
13796            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13797            .fold(
13798                BTreeMap::<DisplayRow, Background>::new(),
13799                |mut unique_rows, highlight| {
13800                    let start = highlight.range.start.to_display_point(&snapshot);
13801                    let end = highlight.range.end.to_display_point(&snapshot);
13802                    let start_row = start.row().0;
13803                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13804                        && end.column() == 0
13805                    {
13806                        end.row().0.saturating_sub(1)
13807                    } else {
13808                        end.row().0
13809                    };
13810                    for row in start_row..=end_row {
13811                        let used_index =
13812                            used_highlight_orders.entry(row).or_insert(highlight.index);
13813                        if highlight.index >= *used_index {
13814                            *used_index = highlight.index;
13815                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13816                        }
13817                    }
13818                    unique_rows
13819                },
13820            )
13821    }
13822
13823    pub fn highlighted_display_row_for_autoscroll(
13824        &self,
13825        snapshot: &DisplaySnapshot,
13826    ) -> Option<DisplayRow> {
13827        self.highlighted_rows
13828            .values()
13829            .flat_map(|highlighted_rows| highlighted_rows.iter())
13830            .filter_map(|highlight| {
13831                if highlight.should_autoscroll {
13832                    Some(highlight.range.start.to_display_point(snapshot).row())
13833                } else {
13834                    None
13835                }
13836            })
13837            .min()
13838    }
13839
13840    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13841        self.highlight_background::<SearchWithinRange>(
13842            ranges,
13843            |colors| colors.editor_document_highlight_read_background,
13844            cx,
13845        )
13846    }
13847
13848    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13849        self.breadcrumb_header = Some(new_header);
13850    }
13851
13852    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13853        self.clear_background_highlights::<SearchWithinRange>(cx);
13854    }
13855
13856    pub fn highlight_background<T: 'static>(
13857        &mut self,
13858        ranges: &[Range<Anchor>],
13859        color_fetcher: fn(&ThemeColors) -> Hsla,
13860        cx: &mut Context<Self>,
13861    ) {
13862        self.background_highlights
13863            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13864        self.scrollbar_marker_state.dirty = true;
13865        cx.notify();
13866    }
13867
13868    pub fn clear_background_highlights<T: 'static>(
13869        &mut self,
13870        cx: &mut Context<Self>,
13871    ) -> Option<BackgroundHighlight> {
13872        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13873        if !text_highlights.1.is_empty() {
13874            self.scrollbar_marker_state.dirty = true;
13875            cx.notify();
13876        }
13877        Some(text_highlights)
13878    }
13879
13880    pub fn highlight_gutter<T: 'static>(
13881        &mut self,
13882        ranges: &[Range<Anchor>],
13883        color_fetcher: fn(&App) -> Hsla,
13884        cx: &mut Context<Self>,
13885    ) {
13886        self.gutter_highlights
13887            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13888        cx.notify();
13889    }
13890
13891    pub fn clear_gutter_highlights<T: 'static>(
13892        &mut self,
13893        cx: &mut Context<Self>,
13894    ) -> Option<GutterHighlight> {
13895        cx.notify();
13896        self.gutter_highlights.remove(&TypeId::of::<T>())
13897    }
13898
13899    #[cfg(feature = "test-support")]
13900    pub fn all_text_background_highlights(
13901        &self,
13902        window: &mut Window,
13903        cx: &mut Context<Self>,
13904    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13905        let snapshot = self.snapshot(window, cx);
13906        let buffer = &snapshot.buffer_snapshot;
13907        let start = buffer.anchor_before(0);
13908        let end = buffer.anchor_after(buffer.len());
13909        let theme = cx.theme().colors();
13910        self.background_highlights_in_range(start..end, &snapshot, theme)
13911    }
13912
13913    #[cfg(feature = "test-support")]
13914    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13915        let snapshot = self.buffer().read(cx).snapshot(cx);
13916
13917        let highlights = self
13918            .background_highlights
13919            .get(&TypeId::of::<items::BufferSearchHighlights>());
13920
13921        if let Some((_color, ranges)) = highlights {
13922            ranges
13923                .iter()
13924                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13925                .collect_vec()
13926        } else {
13927            vec![]
13928        }
13929    }
13930
13931    fn document_highlights_for_position<'a>(
13932        &'a self,
13933        position: Anchor,
13934        buffer: &'a MultiBufferSnapshot,
13935    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13936        let read_highlights = self
13937            .background_highlights
13938            .get(&TypeId::of::<DocumentHighlightRead>())
13939            .map(|h| &h.1);
13940        let write_highlights = self
13941            .background_highlights
13942            .get(&TypeId::of::<DocumentHighlightWrite>())
13943            .map(|h| &h.1);
13944        let left_position = position.bias_left(buffer);
13945        let right_position = position.bias_right(buffer);
13946        read_highlights
13947            .into_iter()
13948            .chain(write_highlights)
13949            .flat_map(move |ranges| {
13950                let start_ix = match ranges.binary_search_by(|probe| {
13951                    let cmp = probe.end.cmp(&left_position, buffer);
13952                    if cmp.is_ge() {
13953                        Ordering::Greater
13954                    } else {
13955                        Ordering::Less
13956                    }
13957                }) {
13958                    Ok(i) | Err(i) => i,
13959                };
13960
13961                ranges[start_ix..]
13962                    .iter()
13963                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13964            })
13965    }
13966
13967    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13968        self.background_highlights
13969            .get(&TypeId::of::<T>())
13970            .map_or(false, |(_, highlights)| !highlights.is_empty())
13971    }
13972
13973    pub fn background_highlights_in_range(
13974        &self,
13975        search_range: Range<Anchor>,
13976        display_snapshot: &DisplaySnapshot,
13977        theme: &ThemeColors,
13978    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13979        let mut results = Vec::new();
13980        for (color_fetcher, ranges) in self.background_highlights.values() {
13981            let color = color_fetcher(theme);
13982            let start_ix = match ranges.binary_search_by(|probe| {
13983                let cmp = probe
13984                    .end
13985                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13986                if cmp.is_gt() {
13987                    Ordering::Greater
13988                } else {
13989                    Ordering::Less
13990                }
13991            }) {
13992                Ok(i) | Err(i) => i,
13993            };
13994            for range in &ranges[start_ix..] {
13995                if range
13996                    .start
13997                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13998                    .is_ge()
13999                {
14000                    break;
14001                }
14002
14003                let start = range.start.to_display_point(display_snapshot);
14004                let end = range.end.to_display_point(display_snapshot);
14005                results.push((start..end, color))
14006            }
14007        }
14008        results
14009    }
14010
14011    pub fn background_highlight_row_ranges<T: 'static>(
14012        &self,
14013        search_range: Range<Anchor>,
14014        display_snapshot: &DisplaySnapshot,
14015        count: usize,
14016    ) -> Vec<RangeInclusive<DisplayPoint>> {
14017        let mut results = Vec::new();
14018        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14019            return vec![];
14020        };
14021
14022        let start_ix = match ranges.binary_search_by(|probe| {
14023            let cmp = probe
14024                .end
14025                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14026            if cmp.is_gt() {
14027                Ordering::Greater
14028            } else {
14029                Ordering::Less
14030            }
14031        }) {
14032            Ok(i) | Err(i) => i,
14033        };
14034        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14035            if let (Some(start_display), Some(end_display)) = (start, end) {
14036                results.push(
14037                    start_display.to_display_point(display_snapshot)
14038                        ..=end_display.to_display_point(display_snapshot),
14039                );
14040            }
14041        };
14042        let mut start_row: Option<Point> = None;
14043        let mut end_row: Option<Point> = None;
14044        if ranges.len() > count {
14045            return Vec::new();
14046        }
14047        for range in &ranges[start_ix..] {
14048            if range
14049                .start
14050                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14051                .is_ge()
14052            {
14053                break;
14054            }
14055            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14056            if let Some(current_row) = &end_row {
14057                if end.row == current_row.row {
14058                    continue;
14059                }
14060            }
14061            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14062            if start_row.is_none() {
14063                assert_eq!(end_row, None);
14064                start_row = Some(start);
14065                end_row = Some(end);
14066                continue;
14067            }
14068            if let Some(current_end) = end_row.as_mut() {
14069                if start.row > current_end.row + 1 {
14070                    push_region(start_row, end_row);
14071                    start_row = Some(start);
14072                    end_row = Some(end);
14073                } else {
14074                    // Merge two hunks.
14075                    *current_end = end;
14076                }
14077            } else {
14078                unreachable!();
14079            }
14080        }
14081        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14082        push_region(start_row, end_row);
14083        results
14084    }
14085
14086    pub fn gutter_highlights_in_range(
14087        &self,
14088        search_range: Range<Anchor>,
14089        display_snapshot: &DisplaySnapshot,
14090        cx: &App,
14091    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14092        let mut results = Vec::new();
14093        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14094            let color = color_fetcher(cx);
14095            let start_ix = match ranges.binary_search_by(|probe| {
14096                let cmp = probe
14097                    .end
14098                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14099                if cmp.is_gt() {
14100                    Ordering::Greater
14101                } else {
14102                    Ordering::Less
14103                }
14104            }) {
14105                Ok(i) | Err(i) => i,
14106            };
14107            for range in &ranges[start_ix..] {
14108                if range
14109                    .start
14110                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14111                    .is_ge()
14112                {
14113                    break;
14114                }
14115
14116                let start = range.start.to_display_point(display_snapshot);
14117                let end = range.end.to_display_point(display_snapshot);
14118                results.push((start..end, color))
14119            }
14120        }
14121        results
14122    }
14123
14124    /// Get the text ranges corresponding to the redaction query
14125    pub fn redacted_ranges(
14126        &self,
14127        search_range: Range<Anchor>,
14128        display_snapshot: &DisplaySnapshot,
14129        cx: &App,
14130    ) -> Vec<Range<DisplayPoint>> {
14131        display_snapshot
14132            .buffer_snapshot
14133            .redacted_ranges(search_range, |file| {
14134                if let Some(file) = file {
14135                    file.is_private()
14136                        && EditorSettings::get(
14137                            Some(SettingsLocation {
14138                                worktree_id: file.worktree_id(cx),
14139                                path: file.path().as_ref(),
14140                            }),
14141                            cx,
14142                        )
14143                        .redact_private_values
14144                } else {
14145                    false
14146                }
14147            })
14148            .map(|range| {
14149                range.start.to_display_point(display_snapshot)
14150                    ..range.end.to_display_point(display_snapshot)
14151            })
14152            .collect()
14153    }
14154
14155    pub fn highlight_text<T: 'static>(
14156        &mut self,
14157        ranges: Vec<Range<Anchor>>,
14158        style: HighlightStyle,
14159        cx: &mut Context<Self>,
14160    ) {
14161        self.display_map.update(cx, |map, _| {
14162            map.highlight_text(TypeId::of::<T>(), ranges, style)
14163        });
14164        cx.notify();
14165    }
14166
14167    pub(crate) fn highlight_inlays<T: 'static>(
14168        &mut self,
14169        highlights: Vec<InlayHighlight>,
14170        style: HighlightStyle,
14171        cx: &mut Context<Self>,
14172    ) {
14173        self.display_map.update(cx, |map, _| {
14174            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14175        });
14176        cx.notify();
14177    }
14178
14179    pub fn text_highlights<'a, T: 'static>(
14180        &'a self,
14181        cx: &'a App,
14182    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14183        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14184    }
14185
14186    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14187        let cleared = self
14188            .display_map
14189            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14190        if cleared {
14191            cx.notify();
14192        }
14193    }
14194
14195    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14196        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14197            && self.focus_handle.is_focused(window)
14198    }
14199
14200    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14201        self.show_cursor_when_unfocused = is_enabled;
14202        cx.notify();
14203    }
14204
14205    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14206        cx.notify();
14207    }
14208
14209    fn on_buffer_event(
14210        &mut self,
14211        multibuffer: &Entity<MultiBuffer>,
14212        event: &multi_buffer::Event,
14213        window: &mut Window,
14214        cx: &mut Context<Self>,
14215    ) {
14216        match event {
14217            multi_buffer::Event::Edited {
14218                singleton_buffer_edited,
14219                edited_buffer: buffer_edited,
14220            } => {
14221                self.scrollbar_marker_state.dirty = true;
14222                self.active_indent_guides_state.dirty = true;
14223                self.refresh_active_diagnostics(cx);
14224                self.refresh_code_actions(window, cx);
14225                if self.has_active_inline_completion() {
14226                    self.update_visible_inline_completion(window, cx);
14227                }
14228                if let Some(buffer) = buffer_edited {
14229                    let buffer_id = buffer.read(cx).remote_id();
14230                    if !self.registered_buffers.contains_key(&buffer_id) {
14231                        if let Some(project) = self.project.as_ref() {
14232                            project.update(cx, |project, cx| {
14233                                self.registered_buffers.insert(
14234                                    buffer_id,
14235                                    project.register_buffer_with_language_servers(&buffer, cx),
14236                                );
14237                            })
14238                        }
14239                    }
14240                }
14241                cx.emit(EditorEvent::BufferEdited);
14242                cx.emit(SearchEvent::MatchesInvalidated);
14243                if *singleton_buffer_edited {
14244                    if let Some(project) = &self.project {
14245                        #[allow(clippy::mutable_key_type)]
14246                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14247                            multibuffer
14248                                .all_buffers()
14249                                .into_iter()
14250                                .filter_map(|buffer| {
14251                                    buffer.update(cx, |buffer, cx| {
14252                                        let language = buffer.language()?;
14253                                        let should_discard = project.update(cx, |project, cx| {
14254                                            project.is_local()
14255                                                && !project.has_language_servers_for(buffer, cx)
14256                                        });
14257                                        should_discard.not().then_some(language.clone())
14258                                    })
14259                                })
14260                                .collect::<HashSet<_>>()
14261                        });
14262                        if !languages_affected.is_empty() {
14263                            self.refresh_inlay_hints(
14264                                InlayHintRefreshReason::BufferEdited(languages_affected),
14265                                cx,
14266                            );
14267                        }
14268                    }
14269                }
14270
14271                let Some(project) = &self.project else { return };
14272                let (telemetry, is_via_ssh) = {
14273                    let project = project.read(cx);
14274                    let telemetry = project.client().telemetry().clone();
14275                    let is_via_ssh = project.is_via_ssh();
14276                    (telemetry, is_via_ssh)
14277                };
14278                refresh_linked_ranges(self, window, cx);
14279                telemetry.log_edit_event("editor", is_via_ssh);
14280            }
14281            multi_buffer::Event::ExcerptsAdded {
14282                buffer,
14283                predecessor,
14284                excerpts,
14285            } => {
14286                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14287                let buffer_id = buffer.read(cx).remote_id();
14288                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14289                    if let Some(project) = &self.project {
14290                        get_uncommitted_diff_for_buffer(
14291                            project,
14292                            [buffer.clone()],
14293                            self.buffer.clone(),
14294                            cx,
14295                        )
14296                        .detach();
14297                    }
14298                }
14299                cx.emit(EditorEvent::ExcerptsAdded {
14300                    buffer: buffer.clone(),
14301                    predecessor: *predecessor,
14302                    excerpts: excerpts.clone(),
14303                });
14304                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14305            }
14306            multi_buffer::Event::ExcerptsRemoved { ids } => {
14307                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14308                let buffer = self.buffer.read(cx);
14309                self.registered_buffers
14310                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14311                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14312            }
14313            multi_buffer::Event::ExcerptsEdited { ids } => {
14314                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14315            }
14316            multi_buffer::Event::ExcerptsExpanded { ids } => {
14317                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14318                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14319            }
14320            multi_buffer::Event::Reparsed(buffer_id) => {
14321                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14322
14323                cx.emit(EditorEvent::Reparsed(*buffer_id));
14324            }
14325            multi_buffer::Event::DiffHunksToggled => {
14326                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14327            }
14328            multi_buffer::Event::LanguageChanged(buffer_id) => {
14329                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14330                cx.emit(EditorEvent::Reparsed(*buffer_id));
14331                cx.notify();
14332            }
14333            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14334            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14335            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14336                cx.emit(EditorEvent::TitleChanged)
14337            }
14338            // multi_buffer::Event::DiffBaseChanged => {
14339            //     self.scrollbar_marker_state.dirty = true;
14340            //     cx.emit(EditorEvent::DiffBaseChanged);
14341            //     cx.notify();
14342            // }
14343            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14344            multi_buffer::Event::DiagnosticsUpdated => {
14345                self.refresh_active_diagnostics(cx);
14346                self.scrollbar_marker_state.dirty = true;
14347                cx.notify();
14348            }
14349            _ => {}
14350        };
14351    }
14352
14353    fn on_display_map_changed(
14354        &mut self,
14355        _: Entity<DisplayMap>,
14356        _: &mut Window,
14357        cx: &mut Context<Self>,
14358    ) {
14359        cx.notify();
14360    }
14361
14362    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14363        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14364        self.refresh_inline_completion(true, false, window, cx);
14365        self.refresh_inlay_hints(
14366            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14367                self.selections.newest_anchor().head(),
14368                &self.buffer.read(cx).snapshot(cx),
14369                cx,
14370            )),
14371            cx,
14372        );
14373
14374        let old_cursor_shape = self.cursor_shape;
14375
14376        {
14377            let editor_settings = EditorSettings::get_global(cx);
14378            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14379            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14380            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14381        }
14382
14383        if old_cursor_shape != self.cursor_shape {
14384            cx.emit(EditorEvent::CursorShapeChanged);
14385        }
14386
14387        let project_settings = ProjectSettings::get_global(cx);
14388        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14389
14390        if self.mode == EditorMode::Full {
14391            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14392            if self.git_blame_inline_enabled != inline_blame_enabled {
14393                self.toggle_git_blame_inline_internal(false, window, cx);
14394            }
14395        }
14396
14397        cx.notify();
14398    }
14399
14400    pub fn set_searchable(&mut self, searchable: bool) {
14401        self.searchable = searchable;
14402    }
14403
14404    pub fn searchable(&self) -> bool {
14405        self.searchable
14406    }
14407
14408    fn open_proposed_changes_editor(
14409        &mut self,
14410        _: &OpenProposedChangesEditor,
14411        window: &mut Window,
14412        cx: &mut Context<Self>,
14413    ) {
14414        let Some(workspace) = self.workspace() else {
14415            cx.propagate();
14416            return;
14417        };
14418
14419        let selections = self.selections.all::<usize>(cx);
14420        let multi_buffer = self.buffer.read(cx);
14421        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14422        let mut new_selections_by_buffer = HashMap::default();
14423        for selection in selections {
14424            for (buffer, range, _) in
14425                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14426            {
14427                let mut range = range.to_point(buffer);
14428                range.start.column = 0;
14429                range.end.column = buffer.line_len(range.end.row);
14430                new_selections_by_buffer
14431                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14432                    .or_insert(Vec::new())
14433                    .push(range)
14434            }
14435        }
14436
14437        let proposed_changes_buffers = new_selections_by_buffer
14438            .into_iter()
14439            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14440            .collect::<Vec<_>>();
14441        let proposed_changes_editor = cx.new(|cx| {
14442            ProposedChangesEditor::new(
14443                "Proposed changes",
14444                proposed_changes_buffers,
14445                self.project.clone(),
14446                window,
14447                cx,
14448            )
14449        });
14450
14451        window.defer(cx, move |window, cx| {
14452            workspace.update(cx, |workspace, cx| {
14453                workspace.active_pane().update(cx, |pane, cx| {
14454                    pane.add_item(
14455                        Box::new(proposed_changes_editor),
14456                        true,
14457                        true,
14458                        None,
14459                        window,
14460                        cx,
14461                    );
14462                });
14463            });
14464        });
14465    }
14466
14467    pub fn open_excerpts_in_split(
14468        &mut self,
14469        _: &OpenExcerptsSplit,
14470        window: &mut Window,
14471        cx: &mut Context<Self>,
14472    ) {
14473        self.open_excerpts_common(None, true, window, cx)
14474    }
14475
14476    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14477        self.open_excerpts_common(None, false, window, cx)
14478    }
14479
14480    fn open_excerpts_common(
14481        &mut self,
14482        jump_data: Option<JumpData>,
14483        split: bool,
14484        window: &mut Window,
14485        cx: &mut Context<Self>,
14486    ) {
14487        let Some(workspace) = self.workspace() else {
14488            cx.propagate();
14489            return;
14490        };
14491
14492        if self.buffer.read(cx).is_singleton() {
14493            cx.propagate();
14494            return;
14495        }
14496
14497        let mut new_selections_by_buffer = HashMap::default();
14498        match &jump_data {
14499            Some(JumpData::MultiBufferPoint {
14500                excerpt_id,
14501                position,
14502                anchor,
14503                line_offset_from_top,
14504            }) => {
14505                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14506                if let Some(buffer) = multi_buffer_snapshot
14507                    .buffer_id_for_excerpt(*excerpt_id)
14508                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14509                {
14510                    let buffer_snapshot = buffer.read(cx).snapshot();
14511                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14512                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14513                    } else {
14514                        buffer_snapshot.clip_point(*position, Bias::Left)
14515                    };
14516                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14517                    new_selections_by_buffer.insert(
14518                        buffer,
14519                        (
14520                            vec![jump_to_offset..jump_to_offset],
14521                            Some(*line_offset_from_top),
14522                        ),
14523                    );
14524                }
14525            }
14526            Some(JumpData::MultiBufferRow {
14527                row,
14528                line_offset_from_top,
14529            }) => {
14530                let point = MultiBufferPoint::new(row.0, 0);
14531                if let Some((buffer, buffer_point, _)) =
14532                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14533                {
14534                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14535                    new_selections_by_buffer
14536                        .entry(buffer)
14537                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14538                        .0
14539                        .push(buffer_offset..buffer_offset)
14540                }
14541            }
14542            None => {
14543                let selections = self.selections.all::<usize>(cx);
14544                let multi_buffer = self.buffer.read(cx);
14545                for selection in selections {
14546                    for (buffer, mut range, _) in multi_buffer
14547                        .snapshot(cx)
14548                        .range_to_buffer_ranges(selection.range())
14549                    {
14550                        // When editing branch buffers, jump to the corresponding location
14551                        // in their base buffer.
14552                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14553                        let buffer = buffer_handle.read(cx);
14554                        if let Some(base_buffer) = buffer.base_buffer() {
14555                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14556                            buffer_handle = base_buffer;
14557                        }
14558
14559                        if selection.reversed {
14560                            mem::swap(&mut range.start, &mut range.end);
14561                        }
14562                        new_selections_by_buffer
14563                            .entry(buffer_handle)
14564                            .or_insert((Vec::new(), None))
14565                            .0
14566                            .push(range)
14567                    }
14568                }
14569            }
14570        }
14571
14572        if new_selections_by_buffer.is_empty() {
14573            return;
14574        }
14575
14576        // We defer the pane interaction because we ourselves are a workspace item
14577        // and activating a new item causes the pane to call a method on us reentrantly,
14578        // which panics if we're on the stack.
14579        window.defer(cx, move |window, cx| {
14580            workspace.update(cx, |workspace, cx| {
14581                let pane = if split {
14582                    workspace.adjacent_pane(window, cx)
14583                } else {
14584                    workspace.active_pane().clone()
14585                };
14586
14587                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14588                    let editor = buffer
14589                        .read(cx)
14590                        .file()
14591                        .is_none()
14592                        .then(|| {
14593                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14594                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14595                            // Instead, we try to activate the existing editor in the pane first.
14596                            let (editor, pane_item_index) =
14597                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14598                                    let editor = item.downcast::<Editor>()?;
14599                                    let singleton_buffer =
14600                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14601                                    if singleton_buffer == buffer {
14602                                        Some((editor, i))
14603                                    } else {
14604                                        None
14605                                    }
14606                                })?;
14607                            pane.update(cx, |pane, cx| {
14608                                pane.activate_item(pane_item_index, true, true, window, cx)
14609                            });
14610                            Some(editor)
14611                        })
14612                        .flatten()
14613                        .unwrap_or_else(|| {
14614                            workspace.open_project_item::<Self>(
14615                                pane.clone(),
14616                                buffer,
14617                                true,
14618                                true,
14619                                window,
14620                                cx,
14621                            )
14622                        });
14623
14624                    editor.update(cx, |editor, cx| {
14625                        let autoscroll = match scroll_offset {
14626                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14627                            None => Autoscroll::newest(),
14628                        };
14629                        let nav_history = editor.nav_history.take();
14630                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14631                            s.select_ranges(ranges);
14632                        });
14633                        editor.nav_history = nav_history;
14634                    });
14635                }
14636            })
14637        });
14638    }
14639
14640    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14641        let snapshot = self.buffer.read(cx).read(cx);
14642        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14643        Some(
14644            ranges
14645                .iter()
14646                .map(move |range| {
14647                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14648                })
14649                .collect(),
14650        )
14651    }
14652
14653    fn selection_replacement_ranges(
14654        &self,
14655        range: Range<OffsetUtf16>,
14656        cx: &mut App,
14657    ) -> Vec<Range<OffsetUtf16>> {
14658        let selections = self.selections.all::<OffsetUtf16>(cx);
14659        let newest_selection = selections
14660            .iter()
14661            .max_by_key(|selection| selection.id)
14662            .unwrap();
14663        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14664        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14665        let snapshot = self.buffer.read(cx).read(cx);
14666        selections
14667            .into_iter()
14668            .map(|mut selection| {
14669                selection.start.0 =
14670                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14671                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14672                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14673                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14674            })
14675            .collect()
14676    }
14677
14678    fn report_editor_event(
14679        &self,
14680        event_type: &'static str,
14681        file_extension: Option<String>,
14682        cx: &App,
14683    ) {
14684        if cfg!(any(test, feature = "test-support")) {
14685            return;
14686        }
14687
14688        let Some(project) = &self.project else { return };
14689
14690        // If None, we are in a file without an extension
14691        let file = self
14692            .buffer
14693            .read(cx)
14694            .as_singleton()
14695            .and_then(|b| b.read(cx).file());
14696        let file_extension = file_extension.or(file
14697            .as_ref()
14698            .and_then(|file| Path::new(file.file_name(cx)).extension())
14699            .and_then(|e| e.to_str())
14700            .map(|a| a.to_string()));
14701
14702        let vim_mode = cx
14703            .global::<SettingsStore>()
14704            .raw_user_settings()
14705            .get("vim_mode")
14706            == Some(&serde_json::Value::Bool(true));
14707
14708        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14709        let copilot_enabled = edit_predictions_provider
14710            == language::language_settings::EditPredictionProvider::Copilot;
14711        let copilot_enabled_for_language = self
14712            .buffer
14713            .read(cx)
14714            .settings_at(0, cx)
14715            .show_edit_predictions;
14716
14717        let project = project.read(cx);
14718        telemetry::event!(
14719            event_type,
14720            file_extension,
14721            vim_mode,
14722            copilot_enabled,
14723            copilot_enabled_for_language,
14724            edit_predictions_provider,
14725            is_via_ssh = project.is_via_ssh(),
14726        );
14727    }
14728
14729    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14730    /// with each line being an array of {text, highlight} objects.
14731    fn copy_highlight_json(
14732        &mut self,
14733        _: &CopyHighlightJson,
14734        window: &mut Window,
14735        cx: &mut Context<Self>,
14736    ) {
14737        #[derive(Serialize)]
14738        struct Chunk<'a> {
14739            text: String,
14740            highlight: Option<&'a str>,
14741        }
14742
14743        let snapshot = self.buffer.read(cx).snapshot(cx);
14744        let range = self
14745            .selected_text_range(false, window, cx)
14746            .and_then(|selection| {
14747                if selection.range.is_empty() {
14748                    None
14749                } else {
14750                    Some(selection.range)
14751                }
14752            })
14753            .unwrap_or_else(|| 0..snapshot.len());
14754
14755        let chunks = snapshot.chunks(range, true);
14756        let mut lines = Vec::new();
14757        let mut line: VecDeque<Chunk> = VecDeque::new();
14758
14759        let Some(style) = self.style.as_ref() else {
14760            return;
14761        };
14762
14763        for chunk in chunks {
14764            let highlight = chunk
14765                .syntax_highlight_id
14766                .and_then(|id| id.name(&style.syntax));
14767            let mut chunk_lines = chunk.text.split('\n').peekable();
14768            while let Some(text) = chunk_lines.next() {
14769                let mut merged_with_last_token = false;
14770                if let Some(last_token) = line.back_mut() {
14771                    if last_token.highlight == highlight {
14772                        last_token.text.push_str(text);
14773                        merged_with_last_token = true;
14774                    }
14775                }
14776
14777                if !merged_with_last_token {
14778                    line.push_back(Chunk {
14779                        text: text.into(),
14780                        highlight,
14781                    });
14782                }
14783
14784                if chunk_lines.peek().is_some() {
14785                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14786                        line.pop_front();
14787                    }
14788                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14789                        line.pop_back();
14790                    }
14791
14792                    lines.push(mem::take(&mut line));
14793                }
14794            }
14795        }
14796
14797        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14798            return;
14799        };
14800        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14801    }
14802
14803    pub fn open_context_menu(
14804        &mut self,
14805        _: &OpenContextMenu,
14806        window: &mut Window,
14807        cx: &mut Context<Self>,
14808    ) {
14809        self.request_autoscroll(Autoscroll::newest(), cx);
14810        let position = self.selections.newest_display(cx).start;
14811        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14812    }
14813
14814    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14815        &self.inlay_hint_cache
14816    }
14817
14818    pub fn replay_insert_event(
14819        &mut self,
14820        text: &str,
14821        relative_utf16_range: Option<Range<isize>>,
14822        window: &mut Window,
14823        cx: &mut Context<Self>,
14824    ) {
14825        if !self.input_enabled {
14826            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14827            return;
14828        }
14829        if let Some(relative_utf16_range) = relative_utf16_range {
14830            let selections = self.selections.all::<OffsetUtf16>(cx);
14831            self.change_selections(None, window, cx, |s| {
14832                let new_ranges = selections.into_iter().map(|range| {
14833                    let start = OffsetUtf16(
14834                        range
14835                            .head()
14836                            .0
14837                            .saturating_add_signed(relative_utf16_range.start),
14838                    );
14839                    let end = OffsetUtf16(
14840                        range
14841                            .head()
14842                            .0
14843                            .saturating_add_signed(relative_utf16_range.end),
14844                    );
14845                    start..end
14846                });
14847                s.select_ranges(new_ranges);
14848            });
14849        }
14850
14851        self.handle_input(text, window, cx);
14852    }
14853
14854    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14855        let Some(provider) = self.semantics_provider.as_ref() else {
14856            return false;
14857        };
14858
14859        let mut supports = false;
14860        self.buffer().update(cx, |this, cx| {
14861            this.for_each_buffer(|buffer| {
14862                supports |= provider.supports_inlay_hints(buffer, cx);
14863            });
14864        });
14865
14866        supports
14867    }
14868
14869    pub fn is_focused(&self, window: &Window) -> bool {
14870        self.focus_handle.is_focused(window)
14871    }
14872
14873    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14874        cx.emit(EditorEvent::Focused);
14875
14876        if let Some(descendant) = self
14877            .last_focused_descendant
14878            .take()
14879            .and_then(|descendant| descendant.upgrade())
14880        {
14881            window.focus(&descendant);
14882        } else {
14883            if let Some(blame) = self.blame.as_ref() {
14884                blame.update(cx, GitBlame::focus)
14885            }
14886
14887            self.blink_manager.update(cx, BlinkManager::enable);
14888            self.show_cursor_names(window, cx);
14889            self.buffer.update(cx, |buffer, cx| {
14890                buffer.finalize_last_transaction(cx);
14891                if self.leader_peer_id.is_none() {
14892                    buffer.set_active_selections(
14893                        &self.selections.disjoint_anchors(),
14894                        self.selections.line_mode,
14895                        self.cursor_shape,
14896                        cx,
14897                    );
14898                }
14899            });
14900        }
14901    }
14902
14903    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14904        cx.emit(EditorEvent::FocusedIn)
14905    }
14906
14907    fn handle_focus_out(
14908        &mut self,
14909        event: FocusOutEvent,
14910        _window: &mut Window,
14911        _cx: &mut Context<Self>,
14912    ) {
14913        if event.blurred != self.focus_handle {
14914            self.last_focused_descendant = Some(event.blurred);
14915        }
14916    }
14917
14918    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14919        self.blink_manager.update(cx, BlinkManager::disable);
14920        self.buffer
14921            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14922
14923        if let Some(blame) = self.blame.as_ref() {
14924            blame.update(cx, GitBlame::blur)
14925        }
14926        if !self.hover_state.focused(window, cx) {
14927            hide_hover(self, cx);
14928        }
14929
14930        self.hide_context_menu(window, cx);
14931        self.discard_inline_completion(false, cx);
14932        cx.emit(EditorEvent::Blurred);
14933        cx.notify();
14934    }
14935
14936    pub fn register_action<A: Action>(
14937        &mut self,
14938        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14939    ) -> Subscription {
14940        let id = self.next_editor_action_id.post_inc();
14941        let listener = Arc::new(listener);
14942        self.editor_actions.borrow_mut().insert(
14943            id,
14944            Box::new(move |window, _| {
14945                let listener = listener.clone();
14946                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14947                    let action = action.downcast_ref().unwrap();
14948                    if phase == DispatchPhase::Bubble {
14949                        listener(action, window, cx)
14950                    }
14951                })
14952            }),
14953        );
14954
14955        let editor_actions = self.editor_actions.clone();
14956        Subscription::new(move || {
14957            editor_actions.borrow_mut().remove(&id);
14958        })
14959    }
14960
14961    pub fn file_header_size(&self) -> u32 {
14962        FILE_HEADER_HEIGHT
14963    }
14964
14965    pub fn revert(
14966        &mut self,
14967        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14968        window: &mut Window,
14969        cx: &mut Context<Self>,
14970    ) {
14971        self.buffer().update(cx, |multi_buffer, cx| {
14972            for (buffer_id, changes) in revert_changes {
14973                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14974                    buffer.update(cx, |buffer, cx| {
14975                        buffer.edit(
14976                            changes.into_iter().map(|(range, text)| {
14977                                (range, text.to_string().map(Arc::<str>::from))
14978                            }),
14979                            None,
14980                            cx,
14981                        );
14982                    });
14983                }
14984            }
14985        });
14986        self.change_selections(None, window, cx, |selections| selections.refresh());
14987    }
14988
14989    pub fn to_pixel_point(
14990        &self,
14991        source: multi_buffer::Anchor,
14992        editor_snapshot: &EditorSnapshot,
14993        window: &mut Window,
14994    ) -> Option<gpui::Point<Pixels>> {
14995        let source_point = source.to_display_point(editor_snapshot);
14996        self.display_to_pixel_point(source_point, editor_snapshot, window)
14997    }
14998
14999    pub fn display_to_pixel_point(
15000        &self,
15001        source: DisplayPoint,
15002        editor_snapshot: &EditorSnapshot,
15003        window: &mut Window,
15004    ) -> Option<gpui::Point<Pixels>> {
15005        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15006        let text_layout_details = self.text_layout_details(window);
15007        let scroll_top = text_layout_details
15008            .scroll_anchor
15009            .scroll_position(editor_snapshot)
15010            .y;
15011
15012        if source.row().as_f32() < scroll_top.floor() {
15013            return None;
15014        }
15015        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15016        let source_y = line_height * (source.row().as_f32() - scroll_top);
15017        Some(gpui::Point::new(source_x, source_y))
15018    }
15019
15020    pub fn has_visible_completions_menu(&self) -> bool {
15021        !self.edit_prediction_preview_is_active()
15022            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15023                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15024            })
15025    }
15026
15027    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15028        self.addons
15029            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15030    }
15031
15032    pub fn unregister_addon<T: Addon>(&mut self) {
15033        self.addons.remove(&std::any::TypeId::of::<T>());
15034    }
15035
15036    pub fn addon<T: Addon>(&self) -> Option<&T> {
15037        let type_id = std::any::TypeId::of::<T>();
15038        self.addons
15039            .get(&type_id)
15040            .and_then(|item| item.to_any().downcast_ref::<T>())
15041    }
15042
15043    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15044        let text_layout_details = self.text_layout_details(window);
15045        let style = &text_layout_details.editor_style;
15046        let font_id = window.text_system().resolve_font(&style.text.font());
15047        let font_size = style.text.font_size.to_pixels(window.rem_size());
15048        let line_height = style.text.line_height_in_pixels(window.rem_size());
15049        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15050
15051        gpui::Size::new(em_width, line_height)
15052    }
15053
15054    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15055        self.load_diff_task.clone()
15056    }
15057
15058    fn read_selections_from_db(
15059        &mut self,
15060        item_id: u64,
15061        workspace_id: WorkspaceId,
15062        window: &mut Window,
15063        cx: &mut Context<Editor>,
15064    ) {
15065        if WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None {
15066            return;
15067        }
15068        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15069            return;
15070        };
15071        if selections.is_empty() {
15072            return;
15073        }
15074
15075        let snapshot = self.buffer.read(cx).snapshot(cx);
15076        self.change_selections(None, window, cx, |s| {
15077            s.select_ranges(selections.into_iter().map(|(start, end)| {
15078                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15079            }));
15080        });
15081    }
15082}
15083
15084fn get_uncommitted_diff_for_buffer(
15085    project: &Entity<Project>,
15086    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15087    buffer: Entity<MultiBuffer>,
15088    cx: &mut App,
15089) -> Task<()> {
15090    let mut tasks = Vec::new();
15091    project.update(cx, |project, cx| {
15092        for buffer in buffers {
15093            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15094        }
15095    });
15096    cx.spawn(|mut cx| async move {
15097        let diffs = futures::future::join_all(tasks).await;
15098        buffer
15099            .update(&mut cx, |buffer, cx| {
15100                for diff in diffs.into_iter().flatten() {
15101                    buffer.add_diff(diff, cx);
15102                }
15103            })
15104            .ok();
15105    })
15106}
15107
15108fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15109    let tab_size = tab_size.get() as usize;
15110    let mut width = offset;
15111
15112    for ch in text.chars() {
15113        width += if ch == '\t' {
15114            tab_size - (width % tab_size)
15115        } else {
15116            1
15117        };
15118    }
15119
15120    width - offset
15121}
15122
15123#[cfg(test)]
15124mod tests {
15125    use super::*;
15126
15127    #[test]
15128    fn test_string_size_with_expanded_tabs() {
15129        let nz = |val| NonZeroU32::new(val).unwrap();
15130        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15131        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15132        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15133        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15134        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15135        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15136        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15137        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15138    }
15139}
15140
15141/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15142struct WordBreakingTokenizer<'a> {
15143    input: &'a str,
15144}
15145
15146impl<'a> WordBreakingTokenizer<'a> {
15147    fn new(input: &'a str) -> Self {
15148        Self { input }
15149    }
15150}
15151
15152fn is_char_ideographic(ch: char) -> bool {
15153    use unicode_script::Script::*;
15154    use unicode_script::UnicodeScript;
15155    matches!(ch.script(), Han | Tangut | Yi)
15156}
15157
15158fn is_grapheme_ideographic(text: &str) -> bool {
15159    text.chars().any(is_char_ideographic)
15160}
15161
15162fn is_grapheme_whitespace(text: &str) -> bool {
15163    text.chars().any(|x| x.is_whitespace())
15164}
15165
15166fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15167    text.chars().next().map_or(false, |ch| {
15168        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15169    })
15170}
15171
15172#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15173struct WordBreakToken<'a> {
15174    token: &'a str,
15175    grapheme_len: usize,
15176    is_whitespace: bool,
15177}
15178
15179impl<'a> Iterator for WordBreakingTokenizer<'a> {
15180    /// Yields a span, the count of graphemes in the token, and whether it was
15181    /// whitespace. Note that it also breaks at word boundaries.
15182    type Item = WordBreakToken<'a>;
15183
15184    fn next(&mut self) -> Option<Self::Item> {
15185        use unicode_segmentation::UnicodeSegmentation;
15186        if self.input.is_empty() {
15187            return None;
15188        }
15189
15190        let mut iter = self.input.graphemes(true).peekable();
15191        let mut offset = 0;
15192        let mut graphemes = 0;
15193        if let Some(first_grapheme) = iter.next() {
15194            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15195            offset += first_grapheme.len();
15196            graphemes += 1;
15197            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15198                if let Some(grapheme) = iter.peek().copied() {
15199                    if should_stay_with_preceding_ideograph(grapheme) {
15200                        offset += grapheme.len();
15201                        graphemes += 1;
15202                    }
15203                }
15204            } else {
15205                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15206                let mut next_word_bound = words.peek().copied();
15207                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15208                    next_word_bound = words.next();
15209                }
15210                while let Some(grapheme) = iter.peek().copied() {
15211                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15212                        break;
15213                    };
15214                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15215                        break;
15216                    };
15217                    offset += grapheme.len();
15218                    graphemes += 1;
15219                    iter.next();
15220                }
15221            }
15222            let token = &self.input[..offset];
15223            self.input = &self.input[offset..];
15224            if is_whitespace {
15225                Some(WordBreakToken {
15226                    token: " ",
15227                    grapheme_len: 1,
15228                    is_whitespace: true,
15229                })
15230            } else {
15231                Some(WordBreakToken {
15232                    token,
15233                    grapheme_len: graphemes,
15234                    is_whitespace: false,
15235                })
15236            }
15237        } else {
15238            None
15239        }
15240    }
15241}
15242
15243#[test]
15244fn test_word_breaking_tokenizer() {
15245    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15246        ("", &[]),
15247        ("  ", &[(" ", 1, true)]),
15248        ("Ʒ", &[("Ʒ", 1, false)]),
15249        ("Ǽ", &[("Ǽ", 1, false)]),
15250        ("", &[("", 1, false)]),
15251        ("⋑⋑", &[("⋑⋑", 2, false)]),
15252        (
15253            "原理,进而",
15254            &[
15255                ("", 1, false),
15256                ("理,", 2, false),
15257                ("", 1, false),
15258                ("", 1, false),
15259            ],
15260        ),
15261        (
15262            "hello world",
15263            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15264        ),
15265        (
15266            "hello, world",
15267            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15268        ),
15269        (
15270            "  hello world",
15271            &[
15272                (" ", 1, true),
15273                ("hello", 5, false),
15274                (" ", 1, true),
15275                ("world", 5, false),
15276            ],
15277        ),
15278        (
15279            "这是什么 \n 钢笔",
15280            &[
15281                ("", 1, false),
15282                ("", 1, false),
15283                ("", 1, false),
15284                ("", 1, false),
15285                (" ", 1, true),
15286                ("", 1, false),
15287                ("", 1, false),
15288            ],
15289        ),
15290        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15291    ];
15292
15293    for (input, result) in tests {
15294        assert_eq!(
15295            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15296            result
15297                .iter()
15298                .copied()
15299                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15300                    token,
15301                    grapheme_len,
15302                    is_whitespace,
15303                })
15304                .collect::<Vec<_>>()
15305        );
15306    }
15307}
15308
15309fn wrap_with_prefix(
15310    line_prefix: String,
15311    unwrapped_text: String,
15312    wrap_column: usize,
15313    tab_size: NonZeroU32,
15314) -> String {
15315    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15316    let mut wrapped_text = String::new();
15317    let mut current_line = line_prefix.clone();
15318
15319    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15320    let mut current_line_len = line_prefix_len;
15321    for WordBreakToken {
15322        token,
15323        grapheme_len,
15324        is_whitespace,
15325    } in tokenizer
15326    {
15327        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15328            wrapped_text.push_str(current_line.trim_end());
15329            wrapped_text.push('\n');
15330            current_line.truncate(line_prefix.len());
15331            current_line_len = line_prefix_len;
15332            if !is_whitespace {
15333                current_line.push_str(token);
15334                current_line_len += grapheme_len;
15335            }
15336        } else if !is_whitespace {
15337            current_line.push_str(token);
15338            current_line_len += grapheme_len;
15339        } else if current_line_len != line_prefix_len {
15340            current_line.push(' ');
15341            current_line_len += 1;
15342        }
15343    }
15344
15345    if !current_line.is_empty() {
15346        wrapped_text.push_str(&current_line);
15347    }
15348    wrapped_text
15349}
15350
15351#[test]
15352fn test_wrap_with_prefix() {
15353    assert_eq!(
15354        wrap_with_prefix(
15355            "# ".to_string(),
15356            "abcdefg".to_string(),
15357            4,
15358            NonZeroU32::new(4).unwrap()
15359        ),
15360        "# abcdefg"
15361    );
15362    assert_eq!(
15363        wrap_with_prefix(
15364            "".to_string(),
15365            "\thello world".to_string(),
15366            8,
15367            NonZeroU32::new(4).unwrap()
15368        ),
15369        "hello\nworld"
15370    );
15371    assert_eq!(
15372        wrap_with_prefix(
15373            "// ".to_string(),
15374            "xx \nyy zz aa bb cc".to_string(),
15375            12,
15376            NonZeroU32::new(4).unwrap()
15377        ),
15378        "// xx yy zz\n// aa bb cc"
15379    );
15380    assert_eq!(
15381        wrap_with_prefix(
15382            String::new(),
15383            "这是什么 \n 钢笔".to_string(),
15384            3,
15385            NonZeroU32::new(4).unwrap()
15386        ),
15387        "这是什\n么 钢\n"
15388    );
15389}
15390
15391pub trait CollaborationHub {
15392    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15393    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15394    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15395}
15396
15397impl CollaborationHub for Entity<Project> {
15398    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15399        self.read(cx).collaborators()
15400    }
15401
15402    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15403        self.read(cx).user_store().read(cx).participant_indices()
15404    }
15405
15406    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15407        let this = self.read(cx);
15408        let user_ids = this.collaborators().values().map(|c| c.user_id);
15409        this.user_store().read_with(cx, |user_store, cx| {
15410            user_store.participant_names(user_ids, cx)
15411        })
15412    }
15413}
15414
15415pub trait SemanticsProvider {
15416    fn hover(
15417        &self,
15418        buffer: &Entity<Buffer>,
15419        position: text::Anchor,
15420        cx: &mut App,
15421    ) -> Option<Task<Vec<project::Hover>>>;
15422
15423    fn inlay_hints(
15424        &self,
15425        buffer_handle: Entity<Buffer>,
15426        range: Range<text::Anchor>,
15427        cx: &mut App,
15428    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15429
15430    fn resolve_inlay_hint(
15431        &self,
15432        hint: InlayHint,
15433        buffer_handle: Entity<Buffer>,
15434        server_id: LanguageServerId,
15435        cx: &mut App,
15436    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15437
15438    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15439
15440    fn document_highlights(
15441        &self,
15442        buffer: &Entity<Buffer>,
15443        position: text::Anchor,
15444        cx: &mut App,
15445    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15446
15447    fn definitions(
15448        &self,
15449        buffer: &Entity<Buffer>,
15450        position: text::Anchor,
15451        kind: GotoDefinitionKind,
15452        cx: &mut App,
15453    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15454
15455    fn range_for_rename(
15456        &self,
15457        buffer: &Entity<Buffer>,
15458        position: text::Anchor,
15459        cx: &mut App,
15460    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15461
15462    fn perform_rename(
15463        &self,
15464        buffer: &Entity<Buffer>,
15465        position: text::Anchor,
15466        new_name: String,
15467        cx: &mut App,
15468    ) -> Option<Task<Result<ProjectTransaction>>>;
15469}
15470
15471pub trait CompletionProvider {
15472    fn completions(
15473        &self,
15474        buffer: &Entity<Buffer>,
15475        buffer_position: text::Anchor,
15476        trigger: CompletionContext,
15477        window: &mut Window,
15478        cx: &mut Context<Editor>,
15479    ) -> Task<Result<Vec<Completion>>>;
15480
15481    fn resolve_completions(
15482        &self,
15483        buffer: Entity<Buffer>,
15484        completion_indices: Vec<usize>,
15485        completions: Rc<RefCell<Box<[Completion]>>>,
15486        cx: &mut Context<Editor>,
15487    ) -> Task<Result<bool>>;
15488
15489    fn apply_additional_edits_for_completion(
15490        &self,
15491        _buffer: Entity<Buffer>,
15492        _completions: Rc<RefCell<Box<[Completion]>>>,
15493        _completion_index: usize,
15494        _push_to_history: bool,
15495        _cx: &mut Context<Editor>,
15496    ) -> Task<Result<Option<language::Transaction>>> {
15497        Task::ready(Ok(None))
15498    }
15499
15500    fn is_completion_trigger(
15501        &self,
15502        buffer: &Entity<Buffer>,
15503        position: language::Anchor,
15504        text: &str,
15505        trigger_in_words: bool,
15506        cx: &mut Context<Editor>,
15507    ) -> bool;
15508
15509    fn sort_completions(&self) -> bool {
15510        true
15511    }
15512}
15513
15514pub trait CodeActionProvider {
15515    fn id(&self) -> Arc<str>;
15516
15517    fn code_actions(
15518        &self,
15519        buffer: &Entity<Buffer>,
15520        range: Range<text::Anchor>,
15521        window: &mut Window,
15522        cx: &mut App,
15523    ) -> Task<Result<Vec<CodeAction>>>;
15524
15525    fn apply_code_action(
15526        &self,
15527        buffer_handle: Entity<Buffer>,
15528        action: CodeAction,
15529        excerpt_id: ExcerptId,
15530        push_to_history: bool,
15531        window: &mut Window,
15532        cx: &mut App,
15533    ) -> Task<Result<ProjectTransaction>>;
15534}
15535
15536impl CodeActionProvider for Entity<Project> {
15537    fn id(&self) -> Arc<str> {
15538        "project".into()
15539    }
15540
15541    fn code_actions(
15542        &self,
15543        buffer: &Entity<Buffer>,
15544        range: Range<text::Anchor>,
15545        _window: &mut Window,
15546        cx: &mut App,
15547    ) -> Task<Result<Vec<CodeAction>>> {
15548        self.update(cx, |project, cx| {
15549            project.code_actions(buffer, range, None, cx)
15550        })
15551    }
15552
15553    fn apply_code_action(
15554        &self,
15555        buffer_handle: Entity<Buffer>,
15556        action: CodeAction,
15557        _excerpt_id: ExcerptId,
15558        push_to_history: bool,
15559        _window: &mut Window,
15560        cx: &mut App,
15561    ) -> Task<Result<ProjectTransaction>> {
15562        self.update(cx, |project, cx| {
15563            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15564        })
15565    }
15566}
15567
15568fn snippet_completions(
15569    project: &Project,
15570    buffer: &Entity<Buffer>,
15571    buffer_position: text::Anchor,
15572    cx: &mut App,
15573) -> Task<Result<Vec<Completion>>> {
15574    let language = buffer.read(cx).language_at(buffer_position);
15575    let language_name = language.as_ref().map(|language| language.lsp_id());
15576    let snippet_store = project.snippets().read(cx);
15577    let snippets = snippet_store.snippets_for(language_name, cx);
15578
15579    if snippets.is_empty() {
15580        return Task::ready(Ok(vec![]));
15581    }
15582    let snapshot = buffer.read(cx).text_snapshot();
15583    let chars: String = snapshot
15584        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15585        .collect();
15586
15587    let scope = language.map(|language| language.default_scope());
15588    let executor = cx.background_executor().clone();
15589
15590    cx.background_spawn(async move {
15591        let classifier = CharClassifier::new(scope).for_completion(true);
15592        let mut last_word = chars
15593            .chars()
15594            .take_while(|c| classifier.is_word(*c))
15595            .collect::<String>();
15596        last_word = last_word.chars().rev().collect();
15597
15598        if last_word.is_empty() {
15599            return Ok(vec![]);
15600        }
15601
15602        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15603        let to_lsp = |point: &text::Anchor| {
15604            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15605            point_to_lsp(end)
15606        };
15607        let lsp_end = to_lsp(&buffer_position);
15608
15609        let candidates = snippets
15610            .iter()
15611            .enumerate()
15612            .flat_map(|(ix, snippet)| {
15613                snippet
15614                    .prefix
15615                    .iter()
15616                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15617            })
15618            .collect::<Vec<StringMatchCandidate>>();
15619
15620        let mut matches = fuzzy::match_strings(
15621            &candidates,
15622            &last_word,
15623            last_word.chars().any(|c| c.is_uppercase()),
15624            100,
15625            &Default::default(),
15626            executor,
15627        )
15628        .await;
15629
15630        // Remove all candidates where the query's start does not match the start of any word in the candidate
15631        if let Some(query_start) = last_word.chars().next() {
15632            matches.retain(|string_match| {
15633                split_words(&string_match.string).any(|word| {
15634                    // Check that the first codepoint of the word as lowercase matches the first
15635                    // codepoint of the query as lowercase
15636                    word.chars()
15637                        .flat_map(|codepoint| codepoint.to_lowercase())
15638                        .zip(query_start.to_lowercase())
15639                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15640                })
15641            });
15642        }
15643
15644        let matched_strings = matches
15645            .into_iter()
15646            .map(|m| m.string)
15647            .collect::<HashSet<_>>();
15648
15649        let result: Vec<Completion> = snippets
15650            .into_iter()
15651            .filter_map(|snippet| {
15652                let matching_prefix = snippet
15653                    .prefix
15654                    .iter()
15655                    .find(|prefix| matched_strings.contains(*prefix))?;
15656                let start = as_offset - last_word.len();
15657                let start = snapshot.anchor_before(start);
15658                let range = start..buffer_position;
15659                let lsp_start = to_lsp(&start);
15660                let lsp_range = lsp::Range {
15661                    start: lsp_start,
15662                    end: lsp_end,
15663                };
15664                Some(Completion {
15665                    old_range: range,
15666                    new_text: snippet.body.clone(),
15667                    resolved: false,
15668                    label: CodeLabel {
15669                        text: matching_prefix.clone(),
15670                        runs: vec![],
15671                        filter_range: 0..matching_prefix.len(),
15672                    },
15673                    server_id: LanguageServerId(usize::MAX),
15674                    documentation: snippet
15675                        .description
15676                        .clone()
15677                        .map(CompletionDocumentation::SingleLine),
15678                    lsp_completion: lsp::CompletionItem {
15679                        label: snippet.prefix.first().unwrap().clone(),
15680                        kind: Some(CompletionItemKind::SNIPPET),
15681                        label_details: snippet.description.as_ref().map(|description| {
15682                            lsp::CompletionItemLabelDetails {
15683                                detail: Some(description.clone()),
15684                                description: None,
15685                            }
15686                        }),
15687                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15688                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15689                            lsp::InsertReplaceEdit {
15690                                new_text: snippet.body.clone(),
15691                                insert: lsp_range,
15692                                replace: lsp_range,
15693                            },
15694                        )),
15695                        filter_text: Some(snippet.body.clone()),
15696                        sort_text: Some(char::MAX.to_string()),
15697                        ..Default::default()
15698                    },
15699                    confirm: None,
15700                })
15701            })
15702            .collect();
15703
15704        Ok(result)
15705    })
15706}
15707
15708impl CompletionProvider for Entity<Project> {
15709    fn completions(
15710        &self,
15711        buffer: &Entity<Buffer>,
15712        buffer_position: text::Anchor,
15713        options: CompletionContext,
15714        _window: &mut Window,
15715        cx: &mut Context<Editor>,
15716    ) -> Task<Result<Vec<Completion>>> {
15717        self.update(cx, |project, cx| {
15718            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15719            let project_completions = project.completions(buffer, buffer_position, options, cx);
15720            cx.background_spawn(async move {
15721                let mut completions = project_completions.await?;
15722                let snippets_completions = snippets.await?;
15723                completions.extend(snippets_completions);
15724                Ok(completions)
15725            })
15726        })
15727    }
15728
15729    fn resolve_completions(
15730        &self,
15731        buffer: Entity<Buffer>,
15732        completion_indices: Vec<usize>,
15733        completions: Rc<RefCell<Box<[Completion]>>>,
15734        cx: &mut Context<Editor>,
15735    ) -> Task<Result<bool>> {
15736        self.update(cx, |project, cx| {
15737            project.lsp_store().update(cx, |lsp_store, cx| {
15738                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15739            })
15740        })
15741    }
15742
15743    fn apply_additional_edits_for_completion(
15744        &self,
15745        buffer: Entity<Buffer>,
15746        completions: Rc<RefCell<Box<[Completion]>>>,
15747        completion_index: usize,
15748        push_to_history: bool,
15749        cx: &mut Context<Editor>,
15750    ) -> Task<Result<Option<language::Transaction>>> {
15751        self.update(cx, |project, cx| {
15752            project.lsp_store().update(cx, |lsp_store, cx| {
15753                lsp_store.apply_additional_edits_for_completion(
15754                    buffer,
15755                    completions,
15756                    completion_index,
15757                    push_to_history,
15758                    cx,
15759                )
15760            })
15761        })
15762    }
15763
15764    fn is_completion_trigger(
15765        &self,
15766        buffer: &Entity<Buffer>,
15767        position: language::Anchor,
15768        text: &str,
15769        trigger_in_words: bool,
15770        cx: &mut Context<Editor>,
15771    ) -> bool {
15772        let mut chars = text.chars();
15773        let char = if let Some(char) = chars.next() {
15774            char
15775        } else {
15776            return false;
15777        };
15778        if chars.next().is_some() {
15779            return false;
15780        }
15781
15782        let buffer = buffer.read(cx);
15783        let snapshot = buffer.snapshot();
15784        if !snapshot.settings_at(position, cx).show_completions_on_input {
15785            return false;
15786        }
15787        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15788        if trigger_in_words && classifier.is_word(char) {
15789            return true;
15790        }
15791
15792        buffer.completion_triggers().contains(text)
15793    }
15794}
15795
15796impl SemanticsProvider for Entity<Project> {
15797    fn hover(
15798        &self,
15799        buffer: &Entity<Buffer>,
15800        position: text::Anchor,
15801        cx: &mut App,
15802    ) -> Option<Task<Vec<project::Hover>>> {
15803        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15804    }
15805
15806    fn document_highlights(
15807        &self,
15808        buffer: &Entity<Buffer>,
15809        position: text::Anchor,
15810        cx: &mut App,
15811    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15812        Some(self.update(cx, |project, cx| {
15813            project.document_highlights(buffer, position, cx)
15814        }))
15815    }
15816
15817    fn definitions(
15818        &self,
15819        buffer: &Entity<Buffer>,
15820        position: text::Anchor,
15821        kind: GotoDefinitionKind,
15822        cx: &mut App,
15823    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15824        Some(self.update(cx, |project, cx| match kind {
15825            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15826            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15827            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15828            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15829        }))
15830    }
15831
15832    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15833        // TODO: make this work for remote projects
15834        self.update(cx, |this, cx| {
15835            buffer.update(cx, |buffer, cx| {
15836                this.any_language_server_supports_inlay_hints(buffer, cx)
15837            })
15838        })
15839    }
15840
15841    fn inlay_hints(
15842        &self,
15843        buffer_handle: Entity<Buffer>,
15844        range: Range<text::Anchor>,
15845        cx: &mut App,
15846    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15847        Some(self.update(cx, |project, cx| {
15848            project.inlay_hints(buffer_handle, range, cx)
15849        }))
15850    }
15851
15852    fn resolve_inlay_hint(
15853        &self,
15854        hint: InlayHint,
15855        buffer_handle: Entity<Buffer>,
15856        server_id: LanguageServerId,
15857        cx: &mut App,
15858    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15859        Some(self.update(cx, |project, cx| {
15860            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15861        }))
15862    }
15863
15864    fn range_for_rename(
15865        &self,
15866        buffer: &Entity<Buffer>,
15867        position: text::Anchor,
15868        cx: &mut App,
15869    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15870        Some(self.update(cx, |project, cx| {
15871            let buffer = buffer.clone();
15872            let task = project.prepare_rename(buffer.clone(), position, cx);
15873            cx.spawn(|_, mut cx| async move {
15874                Ok(match task.await? {
15875                    PrepareRenameResponse::Success(range) => Some(range),
15876                    PrepareRenameResponse::InvalidPosition => None,
15877                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15878                        // Fallback on using TreeSitter info to determine identifier range
15879                        buffer.update(&mut cx, |buffer, _| {
15880                            let snapshot = buffer.snapshot();
15881                            let (range, kind) = snapshot.surrounding_word(position);
15882                            if kind != Some(CharKind::Word) {
15883                                return None;
15884                            }
15885                            Some(
15886                                snapshot.anchor_before(range.start)
15887                                    ..snapshot.anchor_after(range.end),
15888                            )
15889                        })?
15890                    }
15891                })
15892            })
15893        }))
15894    }
15895
15896    fn perform_rename(
15897        &self,
15898        buffer: &Entity<Buffer>,
15899        position: text::Anchor,
15900        new_name: String,
15901        cx: &mut App,
15902    ) -> Option<Task<Result<ProjectTransaction>>> {
15903        Some(self.update(cx, |project, cx| {
15904            project.perform_rename(buffer.clone(), position, new_name, cx)
15905        }))
15906    }
15907}
15908
15909fn inlay_hint_settings(
15910    location: Anchor,
15911    snapshot: &MultiBufferSnapshot,
15912    cx: &mut Context<Editor>,
15913) -> InlayHintSettings {
15914    let file = snapshot.file_at(location);
15915    let language = snapshot.language_at(location).map(|l| l.name());
15916    language_settings(language, file, cx).inlay_hints
15917}
15918
15919fn consume_contiguous_rows(
15920    contiguous_row_selections: &mut Vec<Selection<Point>>,
15921    selection: &Selection<Point>,
15922    display_map: &DisplaySnapshot,
15923    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15924) -> (MultiBufferRow, MultiBufferRow) {
15925    contiguous_row_selections.push(selection.clone());
15926    let start_row = MultiBufferRow(selection.start.row);
15927    let mut end_row = ending_row(selection, display_map);
15928
15929    while let Some(next_selection) = selections.peek() {
15930        if next_selection.start.row <= end_row.0 {
15931            end_row = ending_row(next_selection, display_map);
15932            contiguous_row_selections.push(selections.next().unwrap().clone());
15933        } else {
15934            break;
15935        }
15936    }
15937    (start_row, end_row)
15938}
15939
15940fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15941    if next_selection.end.column > 0 || next_selection.is_empty() {
15942        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15943    } else {
15944        MultiBufferRow(next_selection.end.row)
15945    }
15946}
15947
15948impl EditorSnapshot {
15949    pub fn remote_selections_in_range<'a>(
15950        &'a self,
15951        range: &'a Range<Anchor>,
15952        collaboration_hub: &dyn CollaborationHub,
15953        cx: &'a App,
15954    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15955        let participant_names = collaboration_hub.user_names(cx);
15956        let participant_indices = collaboration_hub.user_participant_indices(cx);
15957        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15958        let collaborators_by_replica_id = collaborators_by_peer_id
15959            .iter()
15960            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15961            .collect::<HashMap<_, _>>();
15962        self.buffer_snapshot
15963            .selections_in_range(range, false)
15964            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15965                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15966                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15967                let user_name = participant_names.get(&collaborator.user_id).cloned();
15968                Some(RemoteSelection {
15969                    replica_id,
15970                    selection,
15971                    cursor_shape,
15972                    line_mode,
15973                    participant_index,
15974                    peer_id: collaborator.peer_id,
15975                    user_name,
15976                })
15977            })
15978    }
15979
15980    pub fn hunks_for_ranges(
15981        &self,
15982        ranges: impl Iterator<Item = Range<Point>>,
15983    ) -> Vec<MultiBufferDiffHunk> {
15984        let mut hunks = Vec::new();
15985        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15986            HashMap::default();
15987        for query_range in ranges {
15988            let query_rows =
15989                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15990            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15991                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15992            ) {
15993                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15994                // when the caret is just above or just below the deleted hunk.
15995                let allow_adjacent = hunk.status().is_removed();
15996                let related_to_selection = if allow_adjacent {
15997                    hunk.row_range.overlaps(&query_rows)
15998                        || hunk.row_range.start == query_rows.end
15999                        || hunk.row_range.end == query_rows.start
16000                } else {
16001                    hunk.row_range.overlaps(&query_rows)
16002                };
16003                if related_to_selection {
16004                    if !processed_buffer_rows
16005                        .entry(hunk.buffer_id)
16006                        .or_default()
16007                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16008                    {
16009                        continue;
16010                    }
16011                    hunks.push(hunk);
16012                }
16013            }
16014        }
16015
16016        hunks
16017    }
16018
16019    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16020        self.display_snapshot.buffer_snapshot.language_at(position)
16021    }
16022
16023    pub fn is_focused(&self) -> bool {
16024        self.is_focused
16025    }
16026
16027    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16028        self.placeholder_text.as_ref()
16029    }
16030
16031    pub fn scroll_position(&self) -> gpui::Point<f32> {
16032        self.scroll_anchor.scroll_position(&self.display_snapshot)
16033    }
16034
16035    fn gutter_dimensions(
16036        &self,
16037        font_id: FontId,
16038        font_size: Pixels,
16039        max_line_number_width: Pixels,
16040        cx: &App,
16041    ) -> Option<GutterDimensions> {
16042        if !self.show_gutter {
16043            return None;
16044        }
16045
16046        let descent = cx.text_system().descent(font_id, font_size);
16047        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16048        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16049
16050        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16051            matches!(
16052                ProjectSettings::get_global(cx).git.git_gutter,
16053                Some(GitGutterSetting::TrackedFiles)
16054            )
16055        });
16056        let gutter_settings = EditorSettings::get_global(cx).gutter;
16057        let show_line_numbers = self
16058            .show_line_numbers
16059            .unwrap_or(gutter_settings.line_numbers);
16060        let line_gutter_width = if show_line_numbers {
16061            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16062            let min_width_for_number_on_gutter = em_advance * 4.0;
16063            max_line_number_width.max(min_width_for_number_on_gutter)
16064        } else {
16065            0.0.into()
16066        };
16067
16068        let show_code_actions = self
16069            .show_code_actions
16070            .unwrap_or(gutter_settings.code_actions);
16071
16072        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16073
16074        let git_blame_entries_width =
16075            self.git_blame_gutter_max_author_length
16076                .map(|max_author_length| {
16077                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16078
16079                    /// The number of characters to dedicate to gaps and margins.
16080                    const SPACING_WIDTH: usize = 4;
16081
16082                    let max_char_count = max_author_length
16083                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16084                        + ::git::SHORT_SHA_LENGTH
16085                        + MAX_RELATIVE_TIMESTAMP.len()
16086                        + SPACING_WIDTH;
16087
16088                    em_advance * max_char_count
16089                });
16090
16091        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16092        left_padding += if show_code_actions || show_runnables {
16093            em_width * 3.0
16094        } else if show_git_gutter && show_line_numbers {
16095            em_width * 2.0
16096        } else if show_git_gutter || show_line_numbers {
16097            em_width
16098        } else {
16099            px(0.)
16100        };
16101
16102        let right_padding = if gutter_settings.folds && show_line_numbers {
16103            em_width * 4.0
16104        } else if gutter_settings.folds {
16105            em_width * 3.0
16106        } else if show_line_numbers {
16107            em_width
16108        } else {
16109            px(0.)
16110        };
16111
16112        Some(GutterDimensions {
16113            left_padding,
16114            right_padding,
16115            width: line_gutter_width + left_padding + right_padding,
16116            margin: -descent,
16117            git_blame_entries_width,
16118        })
16119    }
16120
16121    pub fn render_crease_toggle(
16122        &self,
16123        buffer_row: MultiBufferRow,
16124        row_contains_cursor: bool,
16125        editor: Entity<Editor>,
16126        window: &mut Window,
16127        cx: &mut App,
16128    ) -> Option<AnyElement> {
16129        let folded = self.is_line_folded(buffer_row);
16130        let mut is_foldable = false;
16131
16132        if let Some(crease) = self
16133            .crease_snapshot
16134            .query_row(buffer_row, &self.buffer_snapshot)
16135        {
16136            is_foldable = true;
16137            match crease {
16138                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16139                    if let Some(render_toggle) = render_toggle {
16140                        let toggle_callback =
16141                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16142                                if folded {
16143                                    editor.update(cx, |editor, cx| {
16144                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16145                                    });
16146                                } else {
16147                                    editor.update(cx, |editor, cx| {
16148                                        editor.unfold_at(
16149                                            &crate::UnfoldAt { buffer_row },
16150                                            window,
16151                                            cx,
16152                                        )
16153                                    });
16154                                }
16155                            });
16156                        return Some((render_toggle)(
16157                            buffer_row,
16158                            folded,
16159                            toggle_callback,
16160                            window,
16161                            cx,
16162                        ));
16163                    }
16164                }
16165            }
16166        }
16167
16168        is_foldable |= self.starts_indent(buffer_row);
16169
16170        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16171            Some(
16172                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16173                    .toggle_state(folded)
16174                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16175                        if folded {
16176                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16177                        } else {
16178                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16179                        }
16180                    }))
16181                    .into_any_element(),
16182            )
16183        } else {
16184            None
16185        }
16186    }
16187
16188    pub fn render_crease_trailer(
16189        &self,
16190        buffer_row: MultiBufferRow,
16191        window: &mut Window,
16192        cx: &mut App,
16193    ) -> Option<AnyElement> {
16194        let folded = self.is_line_folded(buffer_row);
16195        if let Crease::Inline { render_trailer, .. } = self
16196            .crease_snapshot
16197            .query_row(buffer_row, &self.buffer_snapshot)?
16198        {
16199            let render_trailer = render_trailer.as_ref()?;
16200            Some(render_trailer(buffer_row, folded, window, cx))
16201        } else {
16202            None
16203        }
16204    }
16205}
16206
16207impl Deref for EditorSnapshot {
16208    type Target = DisplaySnapshot;
16209
16210    fn deref(&self) -> &Self::Target {
16211        &self.display_snapshot
16212    }
16213}
16214
16215#[derive(Clone, Debug, PartialEq, Eq)]
16216pub enum EditorEvent {
16217    InputIgnored {
16218        text: Arc<str>,
16219    },
16220    InputHandled {
16221        utf16_range_to_replace: Option<Range<isize>>,
16222        text: Arc<str>,
16223    },
16224    ExcerptsAdded {
16225        buffer: Entity<Buffer>,
16226        predecessor: ExcerptId,
16227        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16228    },
16229    ExcerptsRemoved {
16230        ids: Vec<ExcerptId>,
16231    },
16232    BufferFoldToggled {
16233        ids: Vec<ExcerptId>,
16234        folded: bool,
16235    },
16236    ExcerptsEdited {
16237        ids: Vec<ExcerptId>,
16238    },
16239    ExcerptsExpanded {
16240        ids: Vec<ExcerptId>,
16241    },
16242    BufferEdited,
16243    Edited {
16244        transaction_id: clock::Lamport,
16245    },
16246    Reparsed(BufferId),
16247    Focused,
16248    FocusedIn,
16249    Blurred,
16250    DirtyChanged,
16251    Saved,
16252    TitleChanged,
16253    DiffBaseChanged,
16254    SelectionsChanged {
16255        local: bool,
16256    },
16257    ScrollPositionChanged {
16258        local: bool,
16259        autoscroll: bool,
16260    },
16261    Closed,
16262    TransactionUndone {
16263        transaction_id: clock::Lamport,
16264    },
16265    TransactionBegun {
16266        transaction_id: clock::Lamport,
16267    },
16268    Reloaded,
16269    CursorShapeChanged,
16270}
16271
16272impl EventEmitter<EditorEvent> for Editor {}
16273
16274impl Focusable for Editor {
16275    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16276        self.focus_handle.clone()
16277    }
16278}
16279
16280impl Render for Editor {
16281    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16282        let settings = ThemeSettings::get_global(cx);
16283
16284        let mut text_style = match self.mode {
16285            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16286                color: cx.theme().colors().editor_foreground,
16287                font_family: settings.ui_font.family.clone(),
16288                font_features: settings.ui_font.features.clone(),
16289                font_fallbacks: settings.ui_font.fallbacks.clone(),
16290                font_size: rems(0.875).into(),
16291                font_weight: settings.ui_font.weight,
16292                line_height: relative(settings.buffer_line_height.value()),
16293                ..Default::default()
16294            },
16295            EditorMode::Full => TextStyle {
16296                color: cx.theme().colors().editor_foreground,
16297                font_family: settings.buffer_font.family.clone(),
16298                font_features: settings.buffer_font.features.clone(),
16299                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16300                font_size: settings.buffer_font_size(cx).into(),
16301                font_weight: settings.buffer_font.weight,
16302                line_height: relative(settings.buffer_line_height.value()),
16303                ..Default::default()
16304            },
16305        };
16306        if let Some(text_style_refinement) = &self.text_style_refinement {
16307            text_style.refine(text_style_refinement)
16308        }
16309
16310        let background = match self.mode {
16311            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16312            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16313            EditorMode::Full => cx.theme().colors().editor_background,
16314        };
16315
16316        EditorElement::new(
16317            &cx.entity(),
16318            EditorStyle {
16319                background,
16320                local_player: cx.theme().players().local(),
16321                text: text_style,
16322                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16323                syntax: cx.theme().syntax().clone(),
16324                status: cx.theme().status().clone(),
16325                inlay_hints_style: make_inlay_hints_style(cx),
16326                inline_completion_styles: make_suggestion_styles(cx),
16327                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16328            },
16329        )
16330    }
16331}
16332
16333impl EntityInputHandler for Editor {
16334    fn text_for_range(
16335        &mut self,
16336        range_utf16: Range<usize>,
16337        adjusted_range: &mut Option<Range<usize>>,
16338        _: &mut Window,
16339        cx: &mut Context<Self>,
16340    ) -> Option<String> {
16341        let snapshot = self.buffer.read(cx).read(cx);
16342        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16343        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16344        if (start.0..end.0) != range_utf16 {
16345            adjusted_range.replace(start.0..end.0);
16346        }
16347        Some(snapshot.text_for_range(start..end).collect())
16348    }
16349
16350    fn selected_text_range(
16351        &mut self,
16352        ignore_disabled_input: bool,
16353        _: &mut Window,
16354        cx: &mut Context<Self>,
16355    ) -> Option<UTF16Selection> {
16356        // Prevent the IME menu from appearing when holding down an alphabetic key
16357        // while input is disabled.
16358        if !ignore_disabled_input && !self.input_enabled {
16359            return None;
16360        }
16361
16362        let selection = self.selections.newest::<OffsetUtf16>(cx);
16363        let range = selection.range();
16364
16365        Some(UTF16Selection {
16366            range: range.start.0..range.end.0,
16367            reversed: selection.reversed,
16368        })
16369    }
16370
16371    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16372        let snapshot = self.buffer.read(cx).read(cx);
16373        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16374        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16375    }
16376
16377    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16378        self.clear_highlights::<InputComposition>(cx);
16379        self.ime_transaction.take();
16380    }
16381
16382    fn replace_text_in_range(
16383        &mut self,
16384        range_utf16: Option<Range<usize>>,
16385        text: &str,
16386        window: &mut Window,
16387        cx: &mut Context<Self>,
16388    ) {
16389        if !self.input_enabled {
16390            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16391            return;
16392        }
16393
16394        self.transact(window, cx, |this, window, cx| {
16395            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16396                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16397                Some(this.selection_replacement_ranges(range_utf16, cx))
16398            } else {
16399                this.marked_text_ranges(cx)
16400            };
16401
16402            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16403                let newest_selection_id = this.selections.newest_anchor().id;
16404                this.selections
16405                    .all::<OffsetUtf16>(cx)
16406                    .iter()
16407                    .zip(ranges_to_replace.iter())
16408                    .find_map(|(selection, range)| {
16409                        if selection.id == newest_selection_id {
16410                            Some(
16411                                (range.start.0 as isize - selection.head().0 as isize)
16412                                    ..(range.end.0 as isize - selection.head().0 as isize),
16413                            )
16414                        } else {
16415                            None
16416                        }
16417                    })
16418            });
16419
16420            cx.emit(EditorEvent::InputHandled {
16421                utf16_range_to_replace: range_to_replace,
16422                text: text.into(),
16423            });
16424
16425            if let Some(new_selected_ranges) = new_selected_ranges {
16426                this.change_selections(None, window, cx, |selections| {
16427                    selections.select_ranges(new_selected_ranges)
16428                });
16429                this.backspace(&Default::default(), window, cx);
16430            }
16431
16432            this.handle_input(text, window, cx);
16433        });
16434
16435        if let Some(transaction) = self.ime_transaction {
16436            self.buffer.update(cx, |buffer, cx| {
16437                buffer.group_until_transaction(transaction, cx);
16438            });
16439        }
16440
16441        self.unmark_text(window, cx);
16442    }
16443
16444    fn replace_and_mark_text_in_range(
16445        &mut self,
16446        range_utf16: Option<Range<usize>>,
16447        text: &str,
16448        new_selected_range_utf16: Option<Range<usize>>,
16449        window: &mut Window,
16450        cx: &mut Context<Self>,
16451    ) {
16452        if !self.input_enabled {
16453            return;
16454        }
16455
16456        let transaction = self.transact(window, cx, |this, window, cx| {
16457            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16458                let snapshot = this.buffer.read(cx).read(cx);
16459                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16460                    for marked_range in &mut marked_ranges {
16461                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16462                        marked_range.start.0 += relative_range_utf16.start;
16463                        marked_range.start =
16464                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16465                        marked_range.end =
16466                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16467                    }
16468                }
16469                Some(marked_ranges)
16470            } else if let Some(range_utf16) = range_utf16 {
16471                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16472                Some(this.selection_replacement_ranges(range_utf16, cx))
16473            } else {
16474                None
16475            };
16476
16477            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16478                let newest_selection_id = this.selections.newest_anchor().id;
16479                this.selections
16480                    .all::<OffsetUtf16>(cx)
16481                    .iter()
16482                    .zip(ranges_to_replace.iter())
16483                    .find_map(|(selection, range)| {
16484                        if selection.id == newest_selection_id {
16485                            Some(
16486                                (range.start.0 as isize - selection.head().0 as isize)
16487                                    ..(range.end.0 as isize - selection.head().0 as isize),
16488                            )
16489                        } else {
16490                            None
16491                        }
16492                    })
16493            });
16494
16495            cx.emit(EditorEvent::InputHandled {
16496                utf16_range_to_replace: range_to_replace,
16497                text: text.into(),
16498            });
16499
16500            if let Some(ranges) = ranges_to_replace {
16501                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16502            }
16503
16504            let marked_ranges = {
16505                let snapshot = this.buffer.read(cx).read(cx);
16506                this.selections
16507                    .disjoint_anchors()
16508                    .iter()
16509                    .map(|selection| {
16510                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16511                    })
16512                    .collect::<Vec<_>>()
16513            };
16514
16515            if text.is_empty() {
16516                this.unmark_text(window, cx);
16517            } else {
16518                this.highlight_text::<InputComposition>(
16519                    marked_ranges.clone(),
16520                    HighlightStyle {
16521                        underline: Some(UnderlineStyle {
16522                            thickness: px(1.),
16523                            color: None,
16524                            wavy: false,
16525                        }),
16526                        ..Default::default()
16527                    },
16528                    cx,
16529                );
16530            }
16531
16532            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16533            let use_autoclose = this.use_autoclose;
16534            let use_auto_surround = this.use_auto_surround;
16535            this.set_use_autoclose(false);
16536            this.set_use_auto_surround(false);
16537            this.handle_input(text, window, cx);
16538            this.set_use_autoclose(use_autoclose);
16539            this.set_use_auto_surround(use_auto_surround);
16540
16541            if let Some(new_selected_range) = new_selected_range_utf16 {
16542                let snapshot = this.buffer.read(cx).read(cx);
16543                let new_selected_ranges = marked_ranges
16544                    .into_iter()
16545                    .map(|marked_range| {
16546                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16547                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16548                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16549                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16550                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16551                    })
16552                    .collect::<Vec<_>>();
16553
16554                drop(snapshot);
16555                this.change_selections(None, window, cx, |selections| {
16556                    selections.select_ranges(new_selected_ranges)
16557                });
16558            }
16559        });
16560
16561        self.ime_transaction = self.ime_transaction.or(transaction);
16562        if let Some(transaction) = self.ime_transaction {
16563            self.buffer.update(cx, |buffer, cx| {
16564                buffer.group_until_transaction(transaction, cx);
16565            });
16566        }
16567
16568        if self.text_highlights::<InputComposition>(cx).is_none() {
16569            self.ime_transaction.take();
16570        }
16571    }
16572
16573    fn bounds_for_range(
16574        &mut self,
16575        range_utf16: Range<usize>,
16576        element_bounds: gpui::Bounds<Pixels>,
16577        window: &mut Window,
16578        cx: &mut Context<Self>,
16579    ) -> Option<gpui::Bounds<Pixels>> {
16580        let text_layout_details = self.text_layout_details(window);
16581        let gpui::Size {
16582            width: em_width,
16583            height: line_height,
16584        } = self.character_size(window);
16585
16586        let snapshot = self.snapshot(window, cx);
16587        let scroll_position = snapshot.scroll_position();
16588        let scroll_left = scroll_position.x * em_width;
16589
16590        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16591        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16592            + self.gutter_dimensions.width
16593            + self.gutter_dimensions.margin;
16594        let y = line_height * (start.row().as_f32() - scroll_position.y);
16595
16596        Some(Bounds {
16597            origin: element_bounds.origin + point(x, y),
16598            size: size(em_width, line_height),
16599        })
16600    }
16601
16602    fn character_index_for_point(
16603        &mut self,
16604        point: gpui::Point<Pixels>,
16605        _window: &mut Window,
16606        _cx: &mut Context<Self>,
16607    ) -> Option<usize> {
16608        let position_map = self.last_position_map.as_ref()?;
16609        if !position_map.text_hitbox.contains(&point) {
16610            return None;
16611        }
16612        let display_point = position_map.point_for_position(point).previous_valid;
16613        let anchor = position_map
16614            .snapshot
16615            .display_point_to_anchor(display_point, Bias::Left);
16616        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16617        Some(utf16_offset.0)
16618    }
16619}
16620
16621trait SelectionExt {
16622    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16623    fn spanned_rows(
16624        &self,
16625        include_end_if_at_line_start: bool,
16626        map: &DisplaySnapshot,
16627    ) -> Range<MultiBufferRow>;
16628}
16629
16630impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16631    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16632        let start = self
16633            .start
16634            .to_point(&map.buffer_snapshot)
16635            .to_display_point(map);
16636        let end = self
16637            .end
16638            .to_point(&map.buffer_snapshot)
16639            .to_display_point(map);
16640        if self.reversed {
16641            end..start
16642        } else {
16643            start..end
16644        }
16645    }
16646
16647    fn spanned_rows(
16648        &self,
16649        include_end_if_at_line_start: bool,
16650        map: &DisplaySnapshot,
16651    ) -> Range<MultiBufferRow> {
16652        let start = self.start.to_point(&map.buffer_snapshot);
16653        let mut end = self.end.to_point(&map.buffer_snapshot);
16654        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16655            end.row -= 1;
16656        }
16657
16658        let buffer_start = map.prev_line_boundary(start).0;
16659        let buffer_end = map.next_line_boundary(end).0;
16660        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16661    }
16662}
16663
16664impl<T: InvalidationRegion> InvalidationStack<T> {
16665    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16666    where
16667        S: Clone + ToOffset,
16668    {
16669        while let Some(region) = self.last() {
16670            let all_selections_inside_invalidation_ranges =
16671                if selections.len() == region.ranges().len() {
16672                    selections
16673                        .iter()
16674                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16675                        .all(|(selection, invalidation_range)| {
16676                            let head = selection.head().to_offset(buffer);
16677                            invalidation_range.start <= head && invalidation_range.end >= head
16678                        })
16679                } else {
16680                    false
16681                };
16682
16683            if all_selections_inside_invalidation_ranges {
16684                break;
16685            } else {
16686                self.pop();
16687            }
16688        }
16689    }
16690}
16691
16692impl<T> Default for InvalidationStack<T> {
16693    fn default() -> Self {
16694        Self(Default::default())
16695    }
16696}
16697
16698impl<T> Deref for InvalidationStack<T> {
16699    type Target = Vec<T>;
16700
16701    fn deref(&self) -> &Self::Target {
16702        &self.0
16703    }
16704}
16705
16706impl<T> DerefMut for InvalidationStack<T> {
16707    fn deref_mut(&mut self) -> &mut Self::Target {
16708        &mut self.0
16709    }
16710}
16711
16712impl InvalidationRegion for SnippetState {
16713    fn ranges(&self) -> &[Range<Anchor>] {
16714        &self.ranges[self.active_index]
16715    }
16716}
16717
16718pub fn diagnostic_block_renderer(
16719    diagnostic: Diagnostic,
16720    max_message_rows: Option<u8>,
16721    allow_closing: bool,
16722    _is_valid: bool,
16723) -> RenderBlock {
16724    let (text_without_backticks, code_ranges) =
16725        highlight_diagnostic_message(&diagnostic, max_message_rows);
16726
16727    Arc::new(move |cx: &mut BlockContext| {
16728        let group_id: SharedString = cx.block_id.to_string().into();
16729
16730        let mut text_style = cx.window.text_style().clone();
16731        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16732        let theme_settings = ThemeSettings::get_global(cx);
16733        text_style.font_family = theme_settings.buffer_font.family.clone();
16734        text_style.font_style = theme_settings.buffer_font.style;
16735        text_style.font_features = theme_settings.buffer_font.features.clone();
16736        text_style.font_weight = theme_settings.buffer_font.weight;
16737
16738        let multi_line_diagnostic = diagnostic.message.contains('\n');
16739
16740        let buttons = |diagnostic: &Diagnostic| {
16741            if multi_line_diagnostic {
16742                v_flex()
16743            } else {
16744                h_flex()
16745            }
16746            .when(allow_closing, |div| {
16747                div.children(diagnostic.is_primary.then(|| {
16748                    IconButton::new("close-block", IconName::XCircle)
16749                        .icon_color(Color::Muted)
16750                        .size(ButtonSize::Compact)
16751                        .style(ButtonStyle::Transparent)
16752                        .visible_on_hover(group_id.clone())
16753                        .on_click(move |_click, window, cx| {
16754                            window.dispatch_action(Box::new(Cancel), cx)
16755                        })
16756                        .tooltip(|window, cx| {
16757                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16758                        })
16759                }))
16760            })
16761            .child(
16762                IconButton::new("copy-block", IconName::Copy)
16763                    .icon_color(Color::Muted)
16764                    .size(ButtonSize::Compact)
16765                    .style(ButtonStyle::Transparent)
16766                    .visible_on_hover(group_id.clone())
16767                    .on_click({
16768                        let message = diagnostic.message.clone();
16769                        move |_click, _, cx| {
16770                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16771                        }
16772                    })
16773                    .tooltip(Tooltip::text("Copy diagnostic message")),
16774            )
16775        };
16776
16777        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16778            AvailableSpace::min_size(),
16779            cx.window,
16780            cx.app,
16781        );
16782
16783        h_flex()
16784            .id(cx.block_id)
16785            .group(group_id.clone())
16786            .relative()
16787            .size_full()
16788            .block_mouse_down()
16789            .pl(cx.gutter_dimensions.width)
16790            .w(cx.max_width - cx.gutter_dimensions.full_width())
16791            .child(
16792                div()
16793                    .flex()
16794                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16795                    .flex_shrink(),
16796            )
16797            .child(buttons(&diagnostic))
16798            .child(div().flex().flex_shrink_0().child(
16799                StyledText::new(text_without_backticks.clone()).with_highlights(
16800                    &text_style,
16801                    code_ranges.iter().map(|range| {
16802                        (
16803                            range.clone(),
16804                            HighlightStyle {
16805                                font_weight: Some(FontWeight::BOLD),
16806                                ..Default::default()
16807                            },
16808                        )
16809                    }),
16810                ),
16811            ))
16812            .into_any_element()
16813    })
16814}
16815
16816fn inline_completion_edit_text(
16817    current_snapshot: &BufferSnapshot,
16818    edits: &[(Range<Anchor>, String)],
16819    edit_preview: &EditPreview,
16820    include_deletions: bool,
16821    cx: &App,
16822) -> HighlightedText {
16823    let edits = edits
16824        .iter()
16825        .map(|(anchor, text)| {
16826            (
16827                anchor.start.text_anchor..anchor.end.text_anchor,
16828                text.clone(),
16829            )
16830        })
16831        .collect::<Vec<_>>();
16832
16833    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16834}
16835
16836pub fn highlight_diagnostic_message(
16837    diagnostic: &Diagnostic,
16838    mut max_message_rows: Option<u8>,
16839) -> (SharedString, Vec<Range<usize>>) {
16840    let mut text_without_backticks = String::new();
16841    let mut code_ranges = Vec::new();
16842
16843    if let Some(source) = &diagnostic.source {
16844        text_without_backticks.push_str(source);
16845        code_ranges.push(0..source.len());
16846        text_without_backticks.push_str(": ");
16847    }
16848
16849    let mut prev_offset = 0;
16850    let mut in_code_block = false;
16851    let has_row_limit = max_message_rows.is_some();
16852    let mut newline_indices = diagnostic
16853        .message
16854        .match_indices('\n')
16855        .filter(|_| has_row_limit)
16856        .map(|(ix, _)| ix)
16857        .fuse()
16858        .peekable();
16859
16860    for (quote_ix, _) in diagnostic
16861        .message
16862        .match_indices('`')
16863        .chain([(diagnostic.message.len(), "")])
16864    {
16865        let mut first_newline_ix = None;
16866        let mut last_newline_ix = None;
16867        while let Some(newline_ix) = newline_indices.peek() {
16868            if *newline_ix < quote_ix {
16869                if first_newline_ix.is_none() {
16870                    first_newline_ix = Some(*newline_ix);
16871                }
16872                last_newline_ix = Some(*newline_ix);
16873
16874                if let Some(rows_left) = &mut max_message_rows {
16875                    if *rows_left == 0 {
16876                        break;
16877                    } else {
16878                        *rows_left -= 1;
16879                    }
16880                }
16881                let _ = newline_indices.next();
16882            } else {
16883                break;
16884            }
16885        }
16886        let prev_len = text_without_backticks.len();
16887        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16888        text_without_backticks.push_str(new_text);
16889        if in_code_block {
16890            code_ranges.push(prev_len..text_without_backticks.len());
16891        }
16892        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16893        in_code_block = !in_code_block;
16894        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16895            text_without_backticks.push_str("...");
16896            break;
16897        }
16898    }
16899
16900    (text_without_backticks.into(), code_ranges)
16901}
16902
16903fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16904    match severity {
16905        DiagnosticSeverity::ERROR => colors.error,
16906        DiagnosticSeverity::WARNING => colors.warning,
16907        DiagnosticSeverity::INFORMATION => colors.info,
16908        DiagnosticSeverity::HINT => colors.info,
16909        _ => colors.ignored,
16910    }
16911}
16912
16913pub fn styled_runs_for_code_label<'a>(
16914    label: &'a CodeLabel,
16915    syntax_theme: &'a theme::SyntaxTheme,
16916) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16917    let fade_out = HighlightStyle {
16918        fade_out: Some(0.35),
16919        ..Default::default()
16920    };
16921
16922    let mut prev_end = label.filter_range.end;
16923    label
16924        .runs
16925        .iter()
16926        .enumerate()
16927        .flat_map(move |(ix, (range, highlight_id))| {
16928            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16929                style
16930            } else {
16931                return Default::default();
16932            };
16933            let mut muted_style = style;
16934            muted_style.highlight(fade_out);
16935
16936            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16937            if range.start >= label.filter_range.end {
16938                if range.start > prev_end {
16939                    runs.push((prev_end..range.start, fade_out));
16940                }
16941                runs.push((range.clone(), muted_style));
16942            } else if range.end <= label.filter_range.end {
16943                runs.push((range.clone(), style));
16944            } else {
16945                runs.push((range.start..label.filter_range.end, style));
16946                runs.push((label.filter_range.end..range.end, muted_style));
16947            }
16948            prev_end = cmp::max(prev_end, range.end);
16949
16950            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16951                runs.push((prev_end..label.text.len(), fade_out));
16952            }
16953
16954            runs
16955        })
16956}
16957
16958pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16959    let mut prev_index = 0;
16960    let mut prev_codepoint: Option<char> = None;
16961    text.char_indices()
16962        .chain([(text.len(), '\0')])
16963        .filter_map(move |(index, codepoint)| {
16964            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16965            let is_boundary = index == text.len()
16966                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16967                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16968            if is_boundary {
16969                let chunk = &text[prev_index..index];
16970                prev_index = index;
16971                Some(chunk)
16972            } else {
16973                None
16974            }
16975        })
16976}
16977
16978pub trait RangeToAnchorExt: Sized {
16979    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16980
16981    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16982        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16983        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16984    }
16985}
16986
16987impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16988    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16989        let start_offset = self.start.to_offset(snapshot);
16990        let end_offset = self.end.to_offset(snapshot);
16991        if start_offset == end_offset {
16992            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16993        } else {
16994            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16995        }
16996    }
16997}
16998
16999pub trait RowExt {
17000    fn as_f32(&self) -> f32;
17001
17002    fn next_row(&self) -> Self;
17003
17004    fn previous_row(&self) -> Self;
17005
17006    fn minus(&self, other: Self) -> u32;
17007}
17008
17009impl RowExt for DisplayRow {
17010    fn as_f32(&self) -> f32 {
17011        self.0 as f32
17012    }
17013
17014    fn next_row(&self) -> Self {
17015        Self(self.0 + 1)
17016    }
17017
17018    fn previous_row(&self) -> Self {
17019        Self(self.0.saturating_sub(1))
17020    }
17021
17022    fn minus(&self, other: Self) -> u32 {
17023        self.0 - other.0
17024    }
17025}
17026
17027impl RowExt for MultiBufferRow {
17028    fn as_f32(&self) -> f32 {
17029        self.0 as f32
17030    }
17031
17032    fn next_row(&self) -> Self {
17033        Self(self.0 + 1)
17034    }
17035
17036    fn previous_row(&self) -> Self {
17037        Self(self.0.saturating_sub(1))
17038    }
17039
17040    fn minus(&self, other: Self) -> u32 {
17041        self.0 - other.0
17042    }
17043}
17044
17045trait RowRangeExt {
17046    type Row;
17047
17048    fn len(&self) -> usize;
17049
17050    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17051}
17052
17053impl RowRangeExt for Range<MultiBufferRow> {
17054    type Row = MultiBufferRow;
17055
17056    fn len(&self) -> usize {
17057        (self.end.0 - self.start.0) as usize
17058    }
17059
17060    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17061        (self.start.0..self.end.0).map(MultiBufferRow)
17062    }
17063}
17064
17065impl RowRangeExt for Range<DisplayRow> {
17066    type Row = DisplayRow;
17067
17068    fn len(&self) -> usize {
17069        (self.end.0 - self.start.0) as usize
17070    }
17071
17072    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17073        (self.start.0..self.end.0).map(DisplayRow)
17074    }
17075}
17076
17077/// If select range has more than one line, we
17078/// just point the cursor to range.start.
17079fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17080    if range.start.row == range.end.row {
17081        range
17082    } else {
17083        range.start..range.start
17084    }
17085}
17086pub struct KillRing(ClipboardItem);
17087impl Global for KillRing {}
17088
17089const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17090
17091fn all_edits_insertions_or_deletions(
17092    edits: &Vec<(Range<Anchor>, String)>,
17093    snapshot: &MultiBufferSnapshot,
17094) -> bool {
17095    let mut all_insertions = true;
17096    let mut all_deletions = true;
17097
17098    for (range, new_text) in edits.iter() {
17099        let range_is_empty = range.to_offset(&snapshot).is_empty();
17100        let text_is_empty = new_text.is_empty();
17101
17102        if range_is_empty != text_is_empty {
17103            if range_is_empty {
17104                all_deletions = false;
17105            } else {
17106                all_insertions = false;
17107            }
17108        } else {
17109            return false;
17110        }
17111
17112        if !all_insertions && !all_deletions {
17113            return false;
17114        }
17115    }
17116    all_insertions || all_deletions
17117}