editor.rs

    1#![allow(rustdoc::private_intra_doc_links)]
    2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
    3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
    4//! It comes in different flavors: single line, multiline and a fixed height one.
    5//!
    6//! Editor contains of multiple large submodules:
    7//! * [`element`] — the place where all rendering happens
    8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
    9//!   Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
   10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
   11//!
   12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
   13//!
   14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
   15pub mod actions;
   16mod blink_manager;
   17mod clangd_ext;
   18mod code_context_menus;
   19pub mod commit_tooltip;
   20pub mod display_map;
   21mod editor_settings;
   22mod editor_settings_controls;
   23mod element;
   24mod git;
   25mod highlight_matching_bracket;
   26mod hover_links;
   27mod hover_popover;
   28mod indent_guides;
   29mod inlay_hint_cache;
   30pub mod items;
   31mod linked_editing_ranges;
   32mod lsp_ext;
   33mod mouse_context_menu;
   34pub mod movement;
   35mod persistence;
   36mod proposed_changes_editor;
   37mod rust_analyzer_ext;
   38pub mod scroll;
   39mod selections_collection;
   40pub mod tasks;
   41
   42#[cfg(test)]
   43mod editor_tests;
   44#[cfg(test)]
   45mod inline_completion_tests;
   46mod signature_help;
   47#[cfg(any(test, feature = "test-support"))]
   48pub mod test;
   49
   50pub(crate) use actions::*;
   51pub use actions::{AcceptEditPrediction, OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use buffer_diff::DiffHunkSecondaryStatus;
   56use client::{Collaborator, ParticipantIndex};
   57use clock::ReplicaId;
   58use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   59use convert_case::{Case, Casing};
   60use display_map::*;
   61pub use display_map::{DisplayPoint, FoldPlaceholder};
   62pub use editor_settings::{
   63    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   64};
   65pub use editor_settings_controls::*;
   66use element::{AcceptEditPredictionBinding, LineWithInvisibles, PositionMap};
   67pub use element::{
   68    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   69};
   70use futures::{
   71    future::{self, Shared},
   72    FutureExt,
   73};
   74use fuzzy::StringMatchCandidate;
   75
   76use code_context_menus::{
   77    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   78    CompletionsMenu, ContextMenuOrigin,
   79};
   80use git::blame::GitBlame;
   81use gpui::{
   82    div, impl_actions, point, prelude::*, pulsating_between, px, relative, size, Action, Animation,
   83    AnimationExt, AnyElement, App, AsyncWindowContext, AvailableSpace, Background, Bounds,
   84    ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId, Entity, EntityInputHandler,
   85    EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId, FontWeight, Global,
   86    HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton, MouseDownEvent,
   87    PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText, Subscription,
   88    Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle,
   89    WeakEntity, WeakFocusHandle, Window,
   90};
   91use highlight_matching_bracket::refresh_matching_bracket_highlights;
   92use hover_popover::{hide_hover, HoverState};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{EditPredictionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, DiskState, EditPredictionsMode, EditPreview, HighlightedText,
  103    IndentKind, IndentSize, Language, OffsetRangeExt, Point, Selection, SelectionGoal, TextObject,
  104    TransactionId, TreeSitterOptions,
  105};
  106use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  107use linked_editing_ranges::refresh_linked_ranges;
  108use mouse_context_menu::MouseContextMenu;
  109use persistence::DB;
  110pub use proposed_changes_editor::{
  111    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  112};
  113use similar::{ChangeTag, TextDiff};
  114use std::iter::Peekable;
  115use task::{ResolvedTask, TaskTemplate, TaskVariables};
  116
  117use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  118pub use lsp::CompletionContext;
  119use lsp::{
  120    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  121    LanguageServerId, LanguageServerName,
  122};
  123
  124use language::BufferSnapshot;
  125use movement::TextLayoutDetails;
  126pub use multi_buffer::{
  127    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  128    ToOffset, ToPoint,
  129};
  130use multi_buffer::{
  131    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  132    ToOffsetUtf16,
  133};
  134use project::{
  135    lsp_store::{CompletionDocumentation, FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  136    project_settings::{GitGutterSetting, ProjectSettings},
  137    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  138    PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  139};
  140use rand::prelude::*;
  141use rpc::{proto::*, ErrorExt};
  142use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  143use selections_collection::{
  144    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  145};
  146use serde::{Deserialize, Serialize};
  147use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  148use smallvec::SmallVec;
  149use snippet::Snippet;
  150use std::{
  151    any::TypeId,
  152    borrow::Cow,
  153    cell::RefCell,
  154    cmp::{self, Ordering, Reverse},
  155    mem,
  156    num::NonZeroU32,
  157    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  158    path::{Path, PathBuf},
  159    rc::Rc,
  160    sync::Arc,
  161    time::{Duration, Instant},
  162};
  163pub use sum_tree::Bias;
  164use sum_tree::TreeMap;
  165use text::{BufferId, OffsetUtf16, Rope};
  166use theme::{
  167    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  168    ThemeColors, ThemeSettings,
  169};
  170use ui::{
  171    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize, Key,
  172    Tooltip,
  173};
  174use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  175use workspace::{
  176    item::{ItemHandle, PreviewTabsSettings},
  177    ItemId, RestoreOnStartupBehavior,
  178};
  179use workspace::{
  180    notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt},
  181    WorkspaceSettings,
  182};
  183use workspace::{
  184    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  185};
  186use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  187
  188use crate::hover_links::{find_url, find_url_from_range};
  189use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  190
  191pub const FILE_HEADER_HEIGHT: u32 = 2;
  192pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  193pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  194pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  195const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  196const MAX_LINE_LEN: usize = 1024;
  197const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  198const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  199pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  200#[doc(hidden)]
  201pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  202
  203pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  204pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  205
  206pub(crate) const EDIT_PREDICTION_KEY_CONTEXT: &str = "edit_prediction";
  207pub(crate) const EDIT_PREDICTION_CONFLICT_KEY_CONTEXT: &str = "edit_prediction_conflict";
  208
  209const COLUMNAR_SELECTION_MODIFIERS: Modifiers = Modifiers {
  210    alt: true,
  211    shift: true,
  212    control: false,
  213    platform: false,
  214    function: false,
  215};
  216
  217pub fn render_parsed_markdown(
  218    element_id: impl Into<ElementId>,
  219    parsed: &language::ParsedMarkdown,
  220    editor_style: &EditorStyle,
  221    workspace: Option<WeakEntity<Workspace>>,
  222    cx: &mut App,
  223) -> InteractiveText {
  224    let code_span_background_color = cx
  225        .theme()
  226        .colors()
  227        .editor_document_highlight_read_background;
  228
  229    let highlights = gpui::combine_highlights(
  230        parsed.highlights.iter().filter_map(|(range, highlight)| {
  231            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  232            Some((range.clone(), highlight))
  233        }),
  234        parsed
  235            .regions
  236            .iter()
  237            .zip(&parsed.region_ranges)
  238            .filter_map(|(region, range)| {
  239                if region.code {
  240                    Some((
  241                        range.clone(),
  242                        HighlightStyle {
  243                            background_color: Some(code_span_background_color),
  244                            ..Default::default()
  245                        },
  246                    ))
  247                } else {
  248                    None
  249                }
  250            }),
  251    );
  252
  253    let mut links = Vec::new();
  254    let mut link_ranges = Vec::new();
  255    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  256        if let Some(link) = region.link.clone() {
  257            links.push(link);
  258            link_ranges.push(range.clone());
  259        }
  260    }
  261
  262    InteractiveText::new(
  263        element_id,
  264        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  265    )
  266    .on_click(
  267        link_ranges,
  268        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  269            markdown::Link::Web { url } => cx.open_url(url),
  270            markdown::Link::Path { path } => {
  271                if let Some(workspace) = &workspace {
  272                    _ = workspace.update(cx, |workspace, cx| {
  273                        workspace
  274                            .open_abs_path(path.clone(), false, window, cx)
  275                            .detach();
  276                    });
  277                }
  278            }
  279        },
  280    )
  281}
  282
  283#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  284pub enum InlayId {
  285    InlineCompletion(usize),
  286    Hint(usize),
  287}
  288
  289impl InlayId {
  290    fn id(&self) -> usize {
  291        match self {
  292            Self::InlineCompletion(id) => *id,
  293            Self::Hint(id) => *id,
  294        }
  295    }
  296}
  297
  298enum DocumentHighlightRead {}
  299enum DocumentHighlightWrite {}
  300enum InputComposition {}
  301enum SelectedTextHighlight {}
  302
  303#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  304pub enum Navigated {
  305    Yes,
  306    No,
  307}
  308
  309impl Navigated {
  310    pub fn from_bool(yes: bool) -> Navigated {
  311        if yes {
  312            Navigated::Yes
  313        } else {
  314            Navigated::No
  315        }
  316    }
  317}
  318
  319pub fn init_settings(cx: &mut App) {
  320    EditorSettings::register(cx);
  321}
  322
  323pub fn init(cx: &mut App) {
  324    init_settings(cx);
  325
  326    workspace::register_project_item::<Editor>(cx);
  327    workspace::FollowableViewRegistry::register::<Editor>(cx);
  328    workspace::register_serializable_item::<Editor>(cx);
  329
  330    cx.observe_new(
  331        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  332            workspace.register_action(Editor::new_file);
  333            workspace.register_action(Editor::new_file_vertical);
  334            workspace.register_action(Editor::new_file_horizontal);
  335            workspace.register_action(Editor::cancel_language_server_work);
  336        },
  337    )
  338    .detach();
  339
  340    cx.on_action(move |_: &workspace::NewFile, cx| {
  341        let app_state = workspace::AppState::global(cx);
  342        if let Some(app_state) = app_state.upgrade() {
  343            workspace::open_new(
  344                Default::default(),
  345                app_state,
  346                cx,
  347                |workspace, window, cx| {
  348                    Editor::new_file(workspace, &Default::default(), window, cx)
  349                },
  350            )
  351            .detach();
  352        }
  353    });
  354    cx.on_action(move |_: &workspace::NewWindow, cx| {
  355        let app_state = workspace::AppState::global(cx);
  356        if let Some(app_state) = app_state.upgrade() {
  357            workspace::open_new(
  358                Default::default(),
  359                app_state,
  360                cx,
  361                |workspace, window, cx| {
  362                    cx.activate(true);
  363                    Editor::new_file(workspace, &Default::default(), window, cx)
  364                },
  365            )
  366            .detach();
  367        }
  368    });
  369}
  370
  371pub struct SearchWithinRange;
  372
  373trait InvalidationRegion {
  374    fn ranges(&self) -> &[Range<Anchor>];
  375}
  376
  377#[derive(Clone, Debug, PartialEq)]
  378pub enum SelectPhase {
  379    Begin {
  380        position: DisplayPoint,
  381        add: bool,
  382        click_count: usize,
  383    },
  384    BeginColumnar {
  385        position: DisplayPoint,
  386        reset: bool,
  387        goal_column: u32,
  388    },
  389    Extend {
  390        position: DisplayPoint,
  391        click_count: usize,
  392    },
  393    Update {
  394        position: DisplayPoint,
  395        goal_column: u32,
  396        scroll_delta: gpui::Point<f32>,
  397    },
  398    End,
  399}
  400
  401#[derive(Clone, Debug)]
  402pub enum SelectMode {
  403    Character,
  404    Word(Range<Anchor>),
  405    Line(Range<Anchor>),
  406    All,
  407}
  408
  409#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  410pub enum EditorMode {
  411    SingleLine { auto_width: bool },
  412    AutoHeight { max_lines: usize },
  413    Full,
  414}
  415
  416#[derive(Copy, Clone, Debug)]
  417pub enum SoftWrap {
  418    /// Prefer not to wrap at all.
  419    ///
  420    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  421    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  422    GitDiff,
  423    /// Prefer a single line generally, unless an overly long line is encountered.
  424    None,
  425    /// Soft wrap lines that exceed the editor width.
  426    EditorWidth,
  427    /// Soft wrap lines at the preferred line length.
  428    Column(u32),
  429    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  430    Bounded(u32),
  431}
  432
  433#[derive(Clone)]
  434pub struct EditorStyle {
  435    pub background: Hsla,
  436    pub local_player: PlayerColor,
  437    pub text: TextStyle,
  438    pub scrollbar_width: Pixels,
  439    pub syntax: Arc<SyntaxTheme>,
  440    pub status: StatusColors,
  441    pub inlay_hints_style: HighlightStyle,
  442    pub inline_completion_styles: InlineCompletionStyles,
  443    pub unnecessary_code_fade: f32,
  444}
  445
  446impl Default for EditorStyle {
  447    fn default() -> Self {
  448        Self {
  449            background: Hsla::default(),
  450            local_player: PlayerColor::default(),
  451            text: TextStyle::default(),
  452            scrollbar_width: Pixels::default(),
  453            syntax: Default::default(),
  454            // HACK: Status colors don't have a real default.
  455            // We should look into removing the status colors from the editor
  456            // style and retrieve them directly from the theme.
  457            status: StatusColors::dark(),
  458            inlay_hints_style: HighlightStyle::default(),
  459            inline_completion_styles: InlineCompletionStyles {
  460                insertion: HighlightStyle::default(),
  461                whitespace: HighlightStyle::default(),
  462            },
  463            unnecessary_code_fade: Default::default(),
  464        }
  465    }
  466}
  467
  468pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  469    let show_background = language_settings::language_settings(None, None, cx)
  470        .inlay_hints
  471        .show_background;
  472
  473    HighlightStyle {
  474        color: Some(cx.theme().status().hint),
  475        background_color: show_background.then(|| cx.theme().status().hint_background),
  476        ..HighlightStyle::default()
  477    }
  478}
  479
  480pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  481    InlineCompletionStyles {
  482        insertion: HighlightStyle {
  483            color: Some(cx.theme().status().predictive),
  484            ..HighlightStyle::default()
  485        },
  486        whitespace: HighlightStyle {
  487            background_color: Some(cx.theme().status().created_background),
  488            ..HighlightStyle::default()
  489        },
  490    }
  491}
  492
  493type CompletionId = usize;
  494
  495pub(crate) enum EditDisplayMode {
  496    TabAccept,
  497    DiffPopover,
  498    Inline,
  499}
  500
  501enum InlineCompletion {
  502    Edit {
  503        edits: Vec<(Range<Anchor>, String)>,
  504        edit_preview: Option<EditPreview>,
  505        display_mode: EditDisplayMode,
  506        snapshot: BufferSnapshot,
  507    },
  508    Move {
  509        target: Anchor,
  510        snapshot: BufferSnapshot,
  511    },
  512}
  513
  514struct InlineCompletionState {
  515    inlay_ids: Vec<InlayId>,
  516    completion: InlineCompletion,
  517    completion_id: Option<SharedString>,
  518    invalidation_range: Range<Anchor>,
  519}
  520
  521enum EditPredictionSettings {
  522    Disabled,
  523    Enabled {
  524        show_in_menu: bool,
  525        preview_requires_modifier: bool,
  526    },
  527}
  528
  529enum InlineCompletionHighlight {}
  530
  531pub enum MenuInlineCompletionsPolicy {
  532    Never,
  533    ByProvider,
  534}
  535
  536pub enum EditPredictionPreview {
  537    /// Modifier is not pressed
  538    Inactive,
  539    /// Modifier pressed
  540    Active {
  541        previous_scroll_position: Option<ScrollAnchor>,
  542    },
  543}
  544
  545#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  546struct EditorActionId(usize);
  547
  548impl EditorActionId {
  549    pub fn post_inc(&mut self) -> Self {
  550        let answer = self.0;
  551
  552        *self = Self(answer + 1);
  553
  554        Self(answer)
  555    }
  556}
  557
  558// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  559// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  560
  561type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  562type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  563
  564#[derive(Default)]
  565struct ScrollbarMarkerState {
  566    scrollbar_size: Size<Pixels>,
  567    dirty: bool,
  568    markers: Arc<[PaintQuad]>,
  569    pending_refresh: Option<Task<Result<()>>>,
  570}
  571
  572impl ScrollbarMarkerState {
  573    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  574        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  575    }
  576}
  577
  578#[derive(Clone, Debug)]
  579struct RunnableTasks {
  580    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  581    offset: MultiBufferOffset,
  582    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  583    column: u32,
  584    // Values of all named captures, including those starting with '_'
  585    extra_variables: HashMap<String, String>,
  586    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  587    context_range: Range<BufferOffset>,
  588}
  589
  590impl RunnableTasks {
  591    fn resolve<'a>(
  592        &'a self,
  593        cx: &'a task::TaskContext,
  594    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  595        self.templates.iter().filter_map(|(kind, template)| {
  596            template
  597                .resolve_task(&kind.to_id_base(), cx)
  598                .map(|task| (kind.clone(), task))
  599        })
  600    }
  601}
  602
  603#[derive(Clone)]
  604struct ResolvedTasks {
  605    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  606    position: Anchor,
  607}
  608#[derive(Copy, Clone, Debug)]
  609struct MultiBufferOffset(usize);
  610#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  611struct BufferOffset(usize);
  612
  613// Addons allow storing per-editor state in other crates (e.g. Vim)
  614pub trait Addon: 'static {
  615    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  616
  617    fn render_buffer_header_controls(
  618        &self,
  619        _: &ExcerptInfo,
  620        _: &Window,
  621        _: &App,
  622    ) -> Option<AnyElement> {
  623        None
  624    }
  625
  626    fn to_any(&self) -> &dyn std::any::Any;
  627}
  628
  629#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  630pub enum IsVimMode {
  631    Yes,
  632    No,
  633}
  634
  635/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  636///
  637/// See the [module level documentation](self) for more information.
  638pub struct Editor {
  639    focus_handle: FocusHandle,
  640    last_focused_descendant: Option<WeakFocusHandle>,
  641    /// The text buffer being edited
  642    buffer: Entity<MultiBuffer>,
  643    /// Map of how text in the buffer should be displayed.
  644    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  645    pub display_map: Entity<DisplayMap>,
  646    pub selections: SelectionsCollection,
  647    pub scroll_manager: ScrollManager,
  648    /// When inline assist editors are linked, they all render cursors because
  649    /// typing enters text into each of them, even the ones that aren't focused.
  650    pub(crate) show_cursor_when_unfocused: bool,
  651    columnar_selection_tail: Option<Anchor>,
  652    add_selections_state: Option<AddSelectionsState>,
  653    select_next_state: Option<SelectNextState>,
  654    select_prev_state: Option<SelectNextState>,
  655    selection_history: SelectionHistory,
  656    autoclose_regions: Vec<AutocloseRegion>,
  657    snippet_stack: InvalidationStack<SnippetState>,
  658    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  659    ime_transaction: Option<TransactionId>,
  660    active_diagnostics: Option<ActiveDiagnosticGroup>,
  661    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  662
  663    // TODO: make this a access method
  664    pub project: Option<Entity<Project>>,
  665    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  666    completion_provider: Option<Box<dyn CompletionProvider>>,
  667    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  668    blink_manager: Entity<BlinkManager>,
  669    show_cursor_names: bool,
  670    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  671    pub show_local_selections: bool,
  672    mode: EditorMode,
  673    show_breadcrumbs: bool,
  674    show_gutter: bool,
  675    show_scrollbars: bool,
  676    show_line_numbers: Option<bool>,
  677    use_relative_line_numbers: Option<bool>,
  678    show_git_diff_gutter: Option<bool>,
  679    show_code_actions: Option<bool>,
  680    show_runnables: Option<bool>,
  681    show_wrap_guides: Option<bool>,
  682    show_indent_guides: Option<bool>,
  683    placeholder_text: Option<Arc<str>>,
  684    highlight_order: usize,
  685    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  686    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  687    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  688    scrollbar_marker_state: ScrollbarMarkerState,
  689    active_indent_guides_state: ActiveIndentGuidesState,
  690    nav_history: Option<ItemNavHistory>,
  691    context_menu: RefCell<Option<CodeContextMenu>>,
  692    mouse_context_menu: Option<MouseContextMenu>,
  693    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  694    signature_help_state: SignatureHelpState,
  695    auto_signature_help: Option<bool>,
  696    find_all_references_task_sources: Vec<Anchor>,
  697    next_completion_id: CompletionId,
  698    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  699    code_actions_task: Option<Task<Result<()>>>,
  700    selection_highlight_task: Option<Task<()>>,
  701    document_highlights_task: Option<Task<()>>,
  702    linked_editing_range_task: Option<Task<Option<()>>>,
  703    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  704    pending_rename: Option<RenameState>,
  705    searchable: bool,
  706    cursor_shape: CursorShape,
  707    current_line_highlight: Option<CurrentLineHighlight>,
  708    collapse_matches: bool,
  709    autoindent_mode: Option<AutoindentMode>,
  710    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  711    input_enabled: bool,
  712    use_modal_editing: bool,
  713    read_only: bool,
  714    leader_peer_id: Option<PeerId>,
  715    remote_id: Option<ViewId>,
  716    hover_state: HoverState,
  717    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  718    gutter_hovered: bool,
  719    hovered_link_state: Option<HoveredLinkState>,
  720    edit_prediction_provider: Option<RegisteredInlineCompletionProvider>,
  721    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  722    active_inline_completion: Option<InlineCompletionState>,
  723    /// Used to prevent flickering as the user types while the menu is open
  724    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  725    edit_prediction_settings: EditPredictionSettings,
  726    inline_completions_hidden_for_vim_mode: bool,
  727    show_inline_completions_override: Option<bool>,
  728    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  729    edit_prediction_preview: EditPredictionPreview,
  730    edit_prediction_cursor_on_leading_whitespace: bool,
  731    edit_prediction_requires_modifier_in_leading_space: bool,
  732    inlay_hint_cache: InlayHintCache,
  733    next_inlay_id: usize,
  734    _subscriptions: Vec<Subscription>,
  735    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  736    gutter_dimensions: GutterDimensions,
  737    style: Option<EditorStyle>,
  738    text_style_refinement: Option<TextStyleRefinement>,
  739    next_editor_action_id: EditorActionId,
  740    editor_actions:
  741        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  742    use_autoclose: bool,
  743    use_auto_surround: bool,
  744    auto_replace_emoji_shortcode: bool,
  745    show_git_blame_gutter: bool,
  746    show_git_blame_inline: bool,
  747    show_git_blame_inline_delay_task: Option<Task<()>>,
  748    distinguish_unstaged_diff_hunks: bool,
  749    git_blame_inline_enabled: bool,
  750    serialize_dirty_buffers: bool,
  751    show_selection_menu: Option<bool>,
  752    blame: Option<Entity<GitBlame>>,
  753    blame_subscription: Option<Subscription>,
  754    custom_context_menu: Option<
  755        Box<
  756            dyn 'static
  757                + Fn(
  758                    &mut Self,
  759                    DisplayPoint,
  760                    &mut Window,
  761                    &mut Context<Self>,
  762                ) -> Option<Entity<ui::ContextMenu>>,
  763        >,
  764    >,
  765    last_bounds: Option<Bounds<Pixels>>,
  766    last_position_map: Option<Rc<PositionMap>>,
  767    expect_bounds_change: Option<Bounds<Pixels>>,
  768    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  769    tasks_update_task: Option<Task<()>>,
  770    in_project_search: bool,
  771    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  772    breadcrumb_header: Option<String>,
  773    focused_block: Option<FocusedBlock>,
  774    next_scroll_position: NextScrollCursorCenterTopBottom,
  775    addons: HashMap<TypeId, Box<dyn Addon>>,
  776    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  777    load_diff_task: Option<Shared<Task<()>>>,
  778    selection_mark_mode: bool,
  779    toggle_fold_multiple_buffers: Task<()>,
  780    _scroll_cursor_center_top_bottom_task: Task<()>,
  781    serialize_selections: Task<()>,
  782}
  783
  784#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  785enum NextScrollCursorCenterTopBottom {
  786    #[default]
  787    Center,
  788    Top,
  789    Bottom,
  790}
  791
  792impl NextScrollCursorCenterTopBottom {
  793    fn next(&self) -> Self {
  794        match self {
  795            Self::Center => Self::Top,
  796            Self::Top => Self::Bottom,
  797            Self::Bottom => Self::Center,
  798        }
  799    }
  800}
  801
  802#[derive(Clone)]
  803pub struct EditorSnapshot {
  804    pub mode: EditorMode,
  805    show_gutter: bool,
  806    show_line_numbers: Option<bool>,
  807    show_git_diff_gutter: Option<bool>,
  808    show_code_actions: Option<bool>,
  809    show_runnables: Option<bool>,
  810    git_blame_gutter_max_author_length: Option<usize>,
  811    pub display_snapshot: DisplaySnapshot,
  812    pub placeholder_text: Option<Arc<str>>,
  813    is_focused: bool,
  814    scroll_anchor: ScrollAnchor,
  815    ongoing_scroll: OngoingScroll,
  816    current_line_highlight: CurrentLineHighlight,
  817    gutter_hovered: bool,
  818}
  819
  820const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  821
  822#[derive(Default, Debug, Clone, Copy)]
  823pub struct GutterDimensions {
  824    pub left_padding: Pixels,
  825    pub right_padding: Pixels,
  826    pub width: Pixels,
  827    pub margin: Pixels,
  828    pub git_blame_entries_width: Option<Pixels>,
  829}
  830
  831impl GutterDimensions {
  832    /// The full width of the space taken up by the gutter.
  833    pub fn full_width(&self) -> Pixels {
  834        self.margin + self.width
  835    }
  836
  837    /// The width of the space reserved for the fold indicators,
  838    /// use alongside 'justify_end' and `gutter_width` to
  839    /// right align content with the line numbers
  840    pub fn fold_area_width(&self) -> Pixels {
  841        self.margin + self.right_padding
  842    }
  843}
  844
  845#[derive(Debug)]
  846pub struct RemoteSelection {
  847    pub replica_id: ReplicaId,
  848    pub selection: Selection<Anchor>,
  849    pub cursor_shape: CursorShape,
  850    pub peer_id: PeerId,
  851    pub line_mode: bool,
  852    pub participant_index: Option<ParticipantIndex>,
  853    pub user_name: Option<SharedString>,
  854}
  855
  856#[derive(Clone, Debug)]
  857struct SelectionHistoryEntry {
  858    selections: Arc<[Selection<Anchor>]>,
  859    select_next_state: Option<SelectNextState>,
  860    select_prev_state: Option<SelectNextState>,
  861    add_selections_state: Option<AddSelectionsState>,
  862}
  863
  864enum SelectionHistoryMode {
  865    Normal,
  866    Undoing,
  867    Redoing,
  868}
  869
  870#[derive(Clone, PartialEq, Eq, Hash)]
  871struct HoveredCursor {
  872    replica_id: u16,
  873    selection_id: usize,
  874}
  875
  876impl Default for SelectionHistoryMode {
  877    fn default() -> Self {
  878        Self::Normal
  879    }
  880}
  881
  882#[derive(Default)]
  883struct SelectionHistory {
  884    #[allow(clippy::type_complexity)]
  885    selections_by_transaction:
  886        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  887    mode: SelectionHistoryMode,
  888    undo_stack: VecDeque<SelectionHistoryEntry>,
  889    redo_stack: VecDeque<SelectionHistoryEntry>,
  890}
  891
  892impl SelectionHistory {
  893    fn insert_transaction(
  894        &mut self,
  895        transaction_id: TransactionId,
  896        selections: Arc<[Selection<Anchor>]>,
  897    ) {
  898        self.selections_by_transaction
  899            .insert(transaction_id, (selections, None));
  900    }
  901
  902    #[allow(clippy::type_complexity)]
  903    fn transaction(
  904        &self,
  905        transaction_id: TransactionId,
  906    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  907        self.selections_by_transaction.get(&transaction_id)
  908    }
  909
  910    #[allow(clippy::type_complexity)]
  911    fn transaction_mut(
  912        &mut self,
  913        transaction_id: TransactionId,
  914    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  915        self.selections_by_transaction.get_mut(&transaction_id)
  916    }
  917
  918    fn push(&mut self, entry: SelectionHistoryEntry) {
  919        if !entry.selections.is_empty() {
  920            match self.mode {
  921                SelectionHistoryMode::Normal => {
  922                    self.push_undo(entry);
  923                    self.redo_stack.clear();
  924                }
  925                SelectionHistoryMode::Undoing => self.push_redo(entry),
  926                SelectionHistoryMode::Redoing => self.push_undo(entry),
  927            }
  928        }
  929    }
  930
  931    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  932        if self
  933            .undo_stack
  934            .back()
  935            .map_or(true, |e| e.selections != entry.selections)
  936        {
  937            self.undo_stack.push_back(entry);
  938            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  939                self.undo_stack.pop_front();
  940            }
  941        }
  942    }
  943
  944    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  945        if self
  946            .redo_stack
  947            .back()
  948            .map_or(true, |e| e.selections != entry.selections)
  949        {
  950            self.redo_stack.push_back(entry);
  951            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  952                self.redo_stack.pop_front();
  953            }
  954        }
  955    }
  956}
  957
  958struct RowHighlight {
  959    index: usize,
  960    range: Range<Anchor>,
  961    color: Hsla,
  962    should_autoscroll: bool,
  963}
  964
  965#[derive(Clone, Debug)]
  966struct AddSelectionsState {
  967    above: bool,
  968    stack: Vec<usize>,
  969}
  970
  971#[derive(Clone)]
  972struct SelectNextState {
  973    query: AhoCorasick,
  974    wordwise: bool,
  975    done: bool,
  976}
  977
  978impl std::fmt::Debug for SelectNextState {
  979    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  980        f.debug_struct(std::any::type_name::<Self>())
  981            .field("wordwise", &self.wordwise)
  982            .field("done", &self.done)
  983            .finish()
  984    }
  985}
  986
  987#[derive(Debug)]
  988struct AutocloseRegion {
  989    selection_id: usize,
  990    range: Range<Anchor>,
  991    pair: BracketPair,
  992}
  993
  994#[derive(Debug)]
  995struct SnippetState {
  996    ranges: Vec<Vec<Range<Anchor>>>,
  997    active_index: usize,
  998    choices: Vec<Option<Vec<String>>>,
  999}
 1000
 1001#[doc(hidden)]
 1002pub struct RenameState {
 1003    pub range: Range<Anchor>,
 1004    pub old_name: Arc<str>,
 1005    pub editor: Entity<Editor>,
 1006    block_id: CustomBlockId,
 1007}
 1008
 1009struct InvalidationStack<T>(Vec<T>);
 1010
 1011struct RegisteredInlineCompletionProvider {
 1012    provider: Arc<dyn InlineCompletionProviderHandle>,
 1013    _subscription: Subscription,
 1014}
 1015
 1016#[derive(Debug)]
 1017struct ActiveDiagnosticGroup {
 1018    primary_range: Range<Anchor>,
 1019    primary_message: String,
 1020    group_id: usize,
 1021    blocks: HashMap<CustomBlockId, Diagnostic>,
 1022    is_valid: bool,
 1023}
 1024
 1025#[derive(Serialize, Deserialize, Clone, Debug)]
 1026pub struct ClipboardSelection {
 1027    pub len: usize,
 1028    pub is_entire_line: bool,
 1029    pub first_line_indent: u32,
 1030}
 1031
 1032#[derive(Debug)]
 1033pub(crate) struct NavigationData {
 1034    cursor_anchor: Anchor,
 1035    cursor_position: Point,
 1036    scroll_anchor: ScrollAnchor,
 1037    scroll_top_row: u32,
 1038}
 1039
 1040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 1041pub enum GotoDefinitionKind {
 1042    Symbol,
 1043    Declaration,
 1044    Type,
 1045    Implementation,
 1046}
 1047
 1048#[derive(Debug, Clone)]
 1049enum InlayHintRefreshReason {
 1050    Toggle(bool),
 1051    SettingsChange(InlayHintSettings),
 1052    NewLinesShown,
 1053    BufferEdited(HashSet<Arc<Language>>),
 1054    RefreshRequested,
 1055    ExcerptsRemoved(Vec<ExcerptId>),
 1056}
 1057
 1058impl InlayHintRefreshReason {
 1059    fn description(&self) -> &'static str {
 1060        match self {
 1061            Self::Toggle(_) => "toggle",
 1062            Self::SettingsChange(_) => "settings change",
 1063            Self::NewLinesShown => "new lines shown",
 1064            Self::BufferEdited(_) => "buffer edited",
 1065            Self::RefreshRequested => "refresh requested",
 1066            Self::ExcerptsRemoved(_) => "excerpts removed",
 1067        }
 1068    }
 1069}
 1070
 1071pub enum FormatTarget {
 1072    Buffers,
 1073    Ranges(Vec<Range<MultiBufferPoint>>),
 1074}
 1075
 1076pub(crate) struct FocusedBlock {
 1077    id: BlockId,
 1078    focus_handle: WeakFocusHandle,
 1079}
 1080
 1081#[derive(Clone)]
 1082enum JumpData {
 1083    MultiBufferRow {
 1084        row: MultiBufferRow,
 1085        line_offset_from_top: u32,
 1086    },
 1087    MultiBufferPoint {
 1088        excerpt_id: ExcerptId,
 1089        position: Point,
 1090        anchor: text::Anchor,
 1091        line_offset_from_top: u32,
 1092    },
 1093}
 1094
 1095pub enum MultibufferSelectionMode {
 1096    First,
 1097    All,
 1098}
 1099
 1100impl Editor {
 1101    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1102        let buffer = cx.new(|cx| Buffer::local("", cx));
 1103        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1104        Self::new(
 1105            EditorMode::SingleLine { auto_width: false },
 1106            buffer,
 1107            None,
 1108            false,
 1109            window,
 1110            cx,
 1111        )
 1112    }
 1113
 1114    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1115        let buffer = cx.new(|cx| Buffer::local("", cx));
 1116        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1117        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1118    }
 1119
 1120    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1121        let buffer = cx.new(|cx| Buffer::local("", cx));
 1122        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1123        Self::new(
 1124            EditorMode::SingleLine { auto_width: true },
 1125            buffer,
 1126            None,
 1127            false,
 1128            window,
 1129            cx,
 1130        )
 1131    }
 1132
 1133    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1134        let buffer = cx.new(|cx| Buffer::local("", cx));
 1135        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1136        Self::new(
 1137            EditorMode::AutoHeight { max_lines },
 1138            buffer,
 1139            None,
 1140            false,
 1141            window,
 1142            cx,
 1143        )
 1144    }
 1145
 1146    pub fn for_buffer(
 1147        buffer: Entity<Buffer>,
 1148        project: Option<Entity<Project>>,
 1149        window: &mut Window,
 1150        cx: &mut Context<Self>,
 1151    ) -> Self {
 1152        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1153        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1154    }
 1155
 1156    pub fn for_multibuffer(
 1157        buffer: Entity<MultiBuffer>,
 1158        project: Option<Entity<Project>>,
 1159        show_excerpt_controls: bool,
 1160        window: &mut Window,
 1161        cx: &mut Context<Self>,
 1162    ) -> Self {
 1163        Self::new(
 1164            EditorMode::Full,
 1165            buffer,
 1166            project,
 1167            show_excerpt_controls,
 1168            window,
 1169            cx,
 1170        )
 1171    }
 1172
 1173    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1174        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1175        let mut clone = Self::new(
 1176            self.mode,
 1177            self.buffer.clone(),
 1178            self.project.clone(),
 1179            show_excerpt_controls,
 1180            window,
 1181            cx,
 1182        );
 1183        self.display_map.update(cx, |display_map, cx| {
 1184            let snapshot = display_map.snapshot(cx);
 1185            clone.display_map.update(cx, |display_map, cx| {
 1186                display_map.set_state(&snapshot, cx);
 1187            });
 1188        });
 1189        clone.selections.clone_state(&self.selections);
 1190        clone.scroll_manager.clone_state(&self.scroll_manager);
 1191        clone.searchable = self.searchable;
 1192        clone
 1193    }
 1194
 1195    pub fn new(
 1196        mode: EditorMode,
 1197        buffer: Entity<MultiBuffer>,
 1198        project: Option<Entity<Project>>,
 1199        show_excerpt_controls: bool,
 1200        window: &mut Window,
 1201        cx: &mut Context<Self>,
 1202    ) -> Self {
 1203        let style = window.text_style();
 1204        let font_size = style.font_size.to_pixels(window.rem_size());
 1205        let editor = cx.entity().downgrade();
 1206        let fold_placeholder = FoldPlaceholder {
 1207            constrain_width: true,
 1208            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1209                let editor = editor.clone();
 1210                div()
 1211                    .id(fold_id)
 1212                    .bg(cx.theme().colors().ghost_element_background)
 1213                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1214                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1215                    .rounded_sm()
 1216                    .size_full()
 1217                    .cursor_pointer()
 1218                    .child("")
 1219                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1220                    .on_click(move |_, _window, cx| {
 1221                        editor
 1222                            .update(cx, |editor, cx| {
 1223                                editor.unfold_ranges(
 1224                                    &[fold_range.start..fold_range.end],
 1225                                    true,
 1226                                    false,
 1227                                    cx,
 1228                                );
 1229                                cx.stop_propagation();
 1230                            })
 1231                            .ok();
 1232                    })
 1233                    .into_any()
 1234            }),
 1235            merge_adjacent: true,
 1236            ..Default::default()
 1237        };
 1238        let display_map = cx.new(|cx| {
 1239            DisplayMap::new(
 1240                buffer.clone(),
 1241                style.font(),
 1242                font_size,
 1243                None,
 1244                show_excerpt_controls,
 1245                FILE_HEADER_HEIGHT,
 1246                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1247                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1248                fold_placeholder,
 1249                cx,
 1250            )
 1251        });
 1252
 1253        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1254
 1255        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1256
 1257        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1258            .then(|| language_settings::SoftWrap::None);
 1259
 1260        let mut project_subscriptions = Vec::new();
 1261        if mode == EditorMode::Full {
 1262            if let Some(project) = project.as_ref() {
 1263                if buffer.read(cx).is_singleton() {
 1264                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1265                        cx.emit(EditorEvent::TitleChanged);
 1266                    }));
 1267                }
 1268                project_subscriptions.push(cx.subscribe_in(
 1269                    project,
 1270                    window,
 1271                    |editor, _, event, window, cx| {
 1272                        if let project::Event::RefreshInlayHints = event {
 1273                            editor
 1274                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1275                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1276                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1277                                let focus_handle = editor.focus_handle(cx);
 1278                                if focus_handle.is_focused(window) {
 1279                                    let snapshot = buffer.read(cx).snapshot();
 1280                                    for (range, snippet) in snippet_edits {
 1281                                        let editor_range =
 1282                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1283                                        editor
 1284                                            .insert_snippet(
 1285                                                &[editor_range],
 1286                                                snippet.clone(),
 1287                                                window,
 1288                                                cx,
 1289                                            )
 1290                                            .ok();
 1291                                    }
 1292                                }
 1293                            }
 1294                        }
 1295                    },
 1296                ));
 1297                if let Some(task_inventory) = project
 1298                    .read(cx)
 1299                    .task_store()
 1300                    .read(cx)
 1301                    .task_inventory()
 1302                    .cloned()
 1303                {
 1304                    project_subscriptions.push(cx.observe_in(
 1305                        &task_inventory,
 1306                        window,
 1307                        |editor, _, window, cx| {
 1308                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1309                        },
 1310                    ));
 1311                }
 1312            }
 1313        }
 1314
 1315        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1316
 1317        let inlay_hint_settings =
 1318            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1319        let focus_handle = cx.focus_handle();
 1320        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1321            .detach();
 1322        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1323            .detach();
 1324        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1325            .detach();
 1326        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1327            .detach();
 1328
 1329        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1330            Some(false)
 1331        } else {
 1332            None
 1333        };
 1334
 1335        let mut code_action_providers = Vec::new();
 1336        let mut load_uncommitted_diff = None;
 1337        if let Some(project) = project.clone() {
 1338            load_uncommitted_diff = Some(
 1339                get_uncommitted_diff_for_buffer(
 1340                    &project,
 1341                    buffer.read(cx).all_buffers(),
 1342                    buffer.clone(),
 1343                    cx,
 1344                )
 1345                .shared(),
 1346            );
 1347            code_action_providers.push(Rc::new(project) as Rc<_>);
 1348        }
 1349
 1350        let mut this = Self {
 1351            focus_handle,
 1352            show_cursor_when_unfocused: false,
 1353            last_focused_descendant: None,
 1354            buffer: buffer.clone(),
 1355            display_map: display_map.clone(),
 1356            selections,
 1357            scroll_manager: ScrollManager::new(cx),
 1358            columnar_selection_tail: None,
 1359            add_selections_state: None,
 1360            select_next_state: None,
 1361            select_prev_state: None,
 1362            selection_history: Default::default(),
 1363            autoclose_regions: Default::default(),
 1364            snippet_stack: Default::default(),
 1365            select_larger_syntax_node_stack: Vec::new(),
 1366            ime_transaction: Default::default(),
 1367            active_diagnostics: None,
 1368            soft_wrap_mode_override,
 1369            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1370            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1371            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1372            project,
 1373            blink_manager: blink_manager.clone(),
 1374            show_local_selections: true,
 1375            show_scrollbars: true,
 1376            mode,
 1377            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1378            show_gutter: mode == EditorMode::Full,
 1379            show_line_numbers: None,
 1380            use_relative_line_numbers: None,
 1381            show_git_diff_gutter: None,
 1382            show_code_actions: None,
 1383            show_runnables: None,
 1384            show_wrap_guides: None,
 1385            show_indent_guides,
 1386            placeholder_text: None,
 1387            highlight_order: 0,
 1388            highlighted_rows: HashMap::default(),
 1389            background_highlights: Default::default(),
 1390            gutter_highlights: TreeMap::default(),
 1391            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1392            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1393            nav_history: None,
 1394            context_menu: RefCell::new(None),
 1395            mouse_context_menu: None,
 1396            completion_tasks: Default::default(),
 1397            signature_help_state: SignatureHelpState::default(),
 1398            auto_signature_help: None,
 1399            find_all_references_task_sources: Vec::new(),
 1400            next_completion_id: 0,
 1401            next_inlay_id: 0,
 1402            code_action_providers,
 1403            available_code_actions: Default::default(),
 1404            code_actions_task: Default::default(),
 1405            selection_highlight_task: Default::default(),
 1406            document_highlights_task: Default::default(),
 1407            linked_editing_range_task: Default::default(),
 1408            pending_rename: Default::default(),
 1409            searchable: true,
 1410            cursor_shape: EditorSettings::get_global(cx)
 1411                .cursor_shape
 1412                .unwrap_or_default(),
 1413            current_line_highlight: None,
 1414            autoindent_mode: Some(AutoindentMode::EachLine),
 1415            collapse_matches: false,
 1416            workspace: None,
 1417            input_enabled: true,
 1418            use_modal_editing: mode == EditorMode::Full,
 1419            read_only: false,
 1420            use_autoclose: true,
 1421            use_auto_surround: true,
 1422            auto_replace_emoji_shortcode: false,
 1423            leader_peer_id: None,
 1424            remote_id: None,
 1425            hover_state: Default::default(),
 1426            pending_mouse_down: None,
 1427            hovered_link_state: Default::default(),
 1428            edit_prediction_provider: None,
 1429            active_inline_completion: None,
 1430            stale_inline_completion_in_menu: None,
 1431            edit_prediction_preview: EditPredictionPreview::Inactive,
 1432            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1433
 1434            gutter_hovered: false,
 1435            pixel_position_of_newest_cursor: None,
 1436            last_bounds: None,
 1437            last_position_map: None,
 1438            expect_bounds_change: None,
 1439            gutter_dimensions: GutterDimensions::default(),
 1440            style: None,
 1441            show_cursor_names: false,
 1442            hovered_cursors: Default::default(),
 1443            next_editor_action_id: EditorActionId::default(),
 1444            editor_actions: Rc::default(),
 1445            inline_completions_hidden_for_vim_mode: false,
 1446            show_inline_completions_override: None,
 1447            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1448            edit_prediction_settings: EditPredictionSettings::Disabled,
 1449            edit_prediction_cursor_on_leading_whitespace: false,
 1450            edit_prediction_requires_modifier_in_leading_space: true,
 1451            custom_context_menu: None,
 1452            show_git_blame_gutter: false,
 1453            show_git_blame_inline: false,
 1454            distinguish_unstaged_diff_hunks: false,
 1455            show_selection_menu: None,
 1456            show_git_blame_inline_delay_task: None,
 1457            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1458            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1459                .session
 1460                .restore_unsaved_buffers,
 1461            blame: None,
 1462            blame_subscription: None,
 1463            tasks: Default::default(),
 1464            _subscriptions: vec![
 1465                cx.observe(&buffer, Self::on_buffer_changed),
 1466                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1467                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1468                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1469                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1470                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1471                cx.observe_window_activation(window, |editor, window, cx| {
 1472                    let active = window.is_window_active();
 1473                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1474                        if active {
 1475                            blink_manager.enable(cx);
 1476                        } else {
 1477                            blink_manager.disable(cx);
 1478                        }
 1479                    });
 1480                }),
 1481            ],
 1482            tasks_update_task: None,
 1483            linked_edit_ranges: Default::default(),
 1484            in_project_search: false,
 1485            previous_search_ranges: None,
 1486            breadcrumb_header: None,
 1487            focused_block: None,
 1488            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1489            addons: HashMap::default(),
 1490            registered_buffers: HashMap::default(),
 1491            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1492            selection_mark_mode: false,
 1493            toggle_fold_multiple_buffers: Task::ready(()),
 1494            serialize_selections: Task::ready(()),
 1495            text_style_refinement: None,
 1496            load_diff_task: load_uncommitted_diff,
 1497        };
 1498        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1499        this._subscriptions.extend(project_subscriptions);
 1500
 1501        this.end_selection(window, cx);
 1502        this.scroll_manager.show_scrollbar(window, cx);
 1503
 1504        if mode == EditorMode::Full {
 1505            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1506            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1507
 1508            if this.git_blame_inline_enabled {
 1509                this.git_blame_inline_enabled = true;
 1510                this.start_git_blame_inline(false, window, cx);
 1511            }
 1512
 1513            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1514                if let Some(project) = this.project.as_ref() {
 1515                    let handle = project.update(cx, |project, cx| {
 1516                        project.register_buffer_with_language_servers(&buffer, cx)
 1517                    });
 1518                    this.registered_buffers
 1519                        .insert(buffer.read(cx).remote_id(), handle);
 1520                }
 1521            }
 1522        }
 1523
 1524        this.report_editor_event("Editor Opened", None, cx);
 1525        this
 1526    }
 1527
 1528    pub fn mouse_menu_is_focused(&self, window: &Window, cx: &App) -> bool {
 1529        self.mouse_context_menu
 1530            .as_ref()
 1531            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1532    }
 1533
 1534    fn key_context(&self, window: &Window, cx: &App) -> KeyContext {
 1535        self.key_context_internal(self.has_active_inline_completion(), window, cx)
 1536    }
 1537
 1538    fn key_context_internal(
 1539        &self,
 1540        has_active_edit_prediction: bool,
 1541        window: &Window,
 1542        cx: &App,
 1543    ) -> KeyContext {
 1544        let mut key_context = KeyContext::new_with_defaults();
 1545        key_context.add("Editor");
 1546        let mode = match self.mode {
 1547            EditorMode::SingleLine { .. } => "single_line",
 1548            EditorMode::AutoHeight { .. } => "auto_height",
 1549            EditorMode::Full => "full",
 1550        };
 1551
 1552        if EditorSettings::jupyter_enabled(cx) {
 1553            key_context.add("jupyter");
 1554        }
 1555
 1556        key_context.set("mode", mode);
 1557        if self.pending_rename.is_some() {
 1558            key_context.add("renaming");
 1559        }
 1560
 1561        match self.context_menu.borrow().as_ref() {
 1562            Some(CodeContextMenu::Completions(_)) => {
 1563                key_context.add("menu");
 1564                key_context.add("showing_completions");
 1565            }
 1566            Some(CodeContextMenu::CodeActions(_)) => {
 1567                key_context.add("menu");
 1568                key_context.add("showing_code_actions")
 1569            }
 1570            None => {}
 1571        }
 1572
 1573        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1574        if !self.focus_handle(cx).contains_focused(window, cx)
 1575            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1576        {
 1577            for addon in self.addons.values() {
 1578                addon.extend_key_context(&mut key_context, cx)
 1579            }
 1580        }
 1581
 1582        if let Some(extension) = self
 1583            .buffer
 1584            .read(cx)
 1585            .as_singleton()
 1586            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1587        {
 1588            key_context.set("extension", extension.to_string());
 1589        }
 1590
 1591        if has_active_edit_prediction {
 1592            if self.edit_prediction_in_conflict() {
 1593                key_context.add(EDIT_PREDICTION_CONFLICT_KEY_CONTEXT);
 1594            } else {
 1595                key_context.add(EDIT_PREDICTION_KEY_CONTEXT);
 1596                key_context.add("copilot_suggestion");
 1597            }
 1598        }
 1599
 1600        if self.selection_mark_mode {
 1601            key_context.add("selection_mode");
 1602        }
 1603
 1604        key_context
 1605    }
 1606
 1607    pub fn edit_prediction_in_conflict(&self) -> bool {
 1608        if !self.show_edit_predictions_in_menu() {
 1609            return false;
 1610        }
 1611
 1612        let showing_completions = self
 1613            .context_menu
 1614            .borrow()
 1615            .as_ref()
 1616            .map_or(false, |context| {
 1617                matches!(context, CodeContextMenu::Completions(_))
 1618            });
 1619
 1620        showing_completions
 1621            || self.edit_prediction_requires_modifier()
 1622            // Require modifier key when the cursor is on leading whitespace, to allow `tab`
 1623            // bindings to insert tab characters.
 1624            || (self.edit_prediction_requires_modifier_in_leading_space && self.edit_prediction_cursor_on_leading_whitespace)
 1625    }
 1626
 1627    pub fn accept_edit_prediction_keybind(
 1628        &self,
 1629        window: &Window,
 1630        cx: &App,
 1631    ) -> AcceptEditPredictionBinding {
 1632        let key_context = self.key_context_internal(true, window, cx);
 1633        let in_conflict = self.edit_prediction_in_conflict();
 1634
 1635        AcceptEditPredictionBinding(
 1636            window
 1637                .bindings_for_action_in_context(&AcceptEditPrediction, key_context)
 1638                .into_iter()
 1639                .filter(|binding| {
 1640                    !in_conflict
 1641                        || binding
 1642                            .keystrokes()
 1643                            .first()
 1644                            .map_or(false, |keystroke| keystroke.modifiers.modified())
 1645                })
 1646                .rev()
 1647                .min_by_key(|binding| {
 1648                    binding
 1649                        .keystrokes()
 1650                        .first()
 1651                        .map_or(u8::MAX, |k| k.modifiers.number_of_modifiers())
 1652                }),
 1653        )
 1654    }
 1655
 1656    pub fn new_file(
 1657        workspace: &mut Workspace,
 1658        _: &workspace::NewFile,
 1659        window: &mut Window,
 1660        cx: &mut Context<Workspace>,
 1661    ) {
 1662        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1663            "Failed to create buffer",
 1664            window,
 1665            cx,
 1666            |e, _, _| match e.error_code() {
 1667                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1668                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1669                e.error_tag("required").unwrap_or("the latest version")
 1670            )),
 1671                _ => None,
 1672            },
 1673        );
 1674    }
 1675
 1676    pub fn new_in_workspace(
 1677        workspace: &mut Workspace,
 1678        window: &mut Window,
 1679        cx: &mut Context<Workspace>,
 1680    ) -> Task<Result<Entity<Editor>>> {
 1681        let project = workspace.project().clone();
 1682        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1683
 1684        cx.spawn_in(window, |workspace, mut cx| async move {
 1685            let buffer = create.await?;
 1686            workspace.update_in(&mut cx, |workspace, window, cx| {
 1687                let editor =
 1688                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1689                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1690                editor
 1691            })
 1692        })
 1693    }
 1694
 1695    fn new_file_vertical(
 1696        workspace: &mut Workspace,
 1697        _: &workspace::NewFileSplitVertical,
 1698        window: &mut Window,
 1699        cx: &mut Context<Workspace>,
 1700    ) {
 1701        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1702    }
 1703
 1704    fn new_file_horizontal(
 1705        workspace: &mut Workspace,
 1706        _: &workspace::NewFileSplitHorizontal,
 1707        window: &mut Window,
 1708        cx: &mut Context<Workspace>,
 1709    ) {
 1710        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1711    }
 1712
 1713    fn new_file_in_direction(
 1714        workspace: &mut Workspace,
 1715        direction: SplitDirection,
 1716        window: &mut Window,
 1717        cx: &mut Context<Workspace>,
 1718    ) {
 1719        let project = workspace.project().clone();
 1720        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1721
 1722        cx.spawn_in(window, |workspace, mut cx| async move {
 1723            let buffer = create.await?;
 1724            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1725                workspace.split_item(
 1726                    direction,
 1727                    Box::new(
 1728                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1729                    ),
 1730                    window,
 1731                    cx,
 1732                )
 1733            })?;
 1734            anyhow::Ok(())
 1735        })
 1736        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1737            match e.error_code() {
 1738                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1739                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1740                e.error_tag("required").unwrap_or("the latest version")
 1741            )),
 1742                _ => None,
 1743            }
 1744        });
 1745    }
 1746
 1747    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1748        self.leader_peer_id
 1749    }
 1750
 1751    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1752        &self.buffer
 1753    }
 1754
 1755    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1756        self.workspace.as_ref()?.0.upgrade()
 1757    }
 1758
 1759    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1760        self.buffer().read(cx).title(cx)
 1761    }
 1762
 1763    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1764        let git_blame_gutter_max_author_length = self
 1765            .render_git_blame_gutter(cx)
 1766            .then(|| {
 1767                if let Some(blame) = self.blame.as_ref() {
 1768                    let max_author_length =
 1769                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1770                    Some(max_author_length)
 1771                } else {
 1772                    None
 1773                }
 1774            })
 1775            .flatten();
 1776
 1777        EditorSnapshot {
 1778            mode: self.mode,
 1779            show_gutter: self.show_gutter,
 1780            show_line_numbers: self.show_line_numbers,
 1781            show_git_diff_gutter: self.show_git_diff_gutter,
 1782            show_code_actions: self.show_code_actions,
 1783            show_runnables: self.show_runnables,
 1784            git_blame_gutter_max_author_length,
 1785            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1786            scroll_anchor: self.scroll_manager.anchor(),
 1787            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1788            placeholder_text: self.placeholder_text.clone(),
 1789            is_focused: self.focus_handle.is_focused(window),
 1790            current_line_highlight: self
 1791                .current_line_highlight
 1792                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1793            gutter_hovered: self.gutter_hovered,
 1794        }
 1795    }
 1796
 1797    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1798        self.buffer.read(cx).language_at(point, cx)
 1799    }
 1800
 1801    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1802        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1803    }
 1804
 1805    pub fn active_excerpt(
 1806        &self,
 1807        cx: &App,
 1808    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1809        self.buffer
 1810            .read(cx)
 1811            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1812    }
 1813
 1814    pub fn mode(&self) -> EditorMode {
 1815        self.mode
 1816    }
 1817
 1818    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1819        self.collaboration_hub.as_deref()
 1820    }
 1821
 1822    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1823        self.collaboration_hub = Some(hub);
 1824    }
 1825
 1826    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1827        self.in_project_search = in_project_search;
 1828    }
 1829
 1830    pub fn set_custom_context_menu(
 1831        &mut self,
 1832        f: impl 'static
 1833            + Fn(
 1834                &mut Self,
 1835                DisplayPoint,
 1836                &mut Window,
 1837                &mut Context<Self>,
 1838            ) -> Option<Entity<ui::ContextMenu>>,
 1839    ) {
 1840        self.custom_context_menu = Some(Box::new(f))
 1841    }
 1842
 1843    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1844        self.completion_provider = provider;
 1845    }
 1846
 1847    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1848        self.semantics_provider.clone()
 1849    }
 1850
 1851    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1852        self.semantics_provider = provider;
 1853    }
 1854
 1855    pub fn set_edit_prediction_provider<T>(
 1856        &mut self,
 1857        provider: Option<Entity<T>>,
 1858        window: &mut Window,
 1859        cx: &mut Context<Self>,
 1860    ) where
 1861        T: EditPredictionProvider,
 1862    {
 1863        self.edit_prediction_provider =
 1864            provider.map(|provider| RegisteredInlineCompletionProvider {
 1865                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1866                    if this.focus_handle.is_focused(window) {
 1867                        this.update_visible_inline_completion(window, cx);
 1868                    }
 1869                }),
 1870                provider: Arc::new(provider),
 1871            });
 1872        self.refresh_inline_completion(false, false, window, cx);
 1873    }
 1874
 1875    pub fn placeholder_text(&self) -> Option<&str> {
 1876        self.placeholder_text.as_deref()
 1877    }
 1878
 1879    pub fn set_placeholder_text(
 1880        &mut self,
 1881        placeholder_text: impl Into<Arc<str>>,
 1882        cx: &mut Context<Self>,
 1883    ) {
 1884        let placeholder_text = Some(placeholder_text.into());
 1885        if self.placeholder_text != placeholder_text {
 1886            self.placeholder_text = placeholder_text;
 1887            cx.notify();
 1888        }
 1889    }
 1890
 1891    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1892        self.cursor_shape = cursor_shape;
 1893
 1894        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1895        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1896
 1897        cx.notify();
 1898    }
 1899
 1900    pub fn set_current_line_highlight(
 1901        &mut self,
 1902        current_line_highlight: Option<CurrentLineHighlight>,
 1903    ) {
 1904        self.current_line_highlight = current_line_highlight;
 1905    }
 1906
 1907    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1908        self.collapse_matches = collapse_matches;
 1909    }
 1910
 1911    fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1912        let buffers = self.buffer.read(cx).all_buffers();
 1913        let Some(project) = self.project.as_ref() else {
 1914            return;
 1915        };
 1916        project.update(cx, |project, cx| {
 1917            for buffer in buffers {
 1918                self.registered_buffers
 1919                    .entry(buffer.read(cx).remote_id())
 1920                    .or_insert_with(|| project.register_buffer_with_language_servers(&buffer, cx));
 1921            }
 1922        })
 1923    }
 1924
 1925    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1926        if self.collapse_matches {
 1927            return range.start..range.start;
 1928        }
 1929        range.clone()
 1930    }
 1931
 1932    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1933        if self.display_map.read(cx).clip_at_line_ends != clip {
 1934            self.display_map
 1935                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1936        }
 1937    }
 1938
 1939    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1940        self.input_enabled = input_enabled;
 1941    }
 1942
 1943    pub fn set_inline_completions_hidden_for_vim_mode(
 1944        &mut self,
 1945        hidden: bool,
 1946        window: &mut Window,
 1947        cx: &mut Context<Self>,
 1948    ) {
 1949        if hidden != self.inline_completions_hidden_for_vim_mode {
 1950            self.inline_completions_hidden_for_vim_mode = hidden;
 1951            if hidden {
 1952                self.update_visible_inline_completion(window, cx);
 1953            } else {
 1954                self.refresh_inline_completion(true, false, window, cx);
 1955            }
 1956        }
 1957    }
 1958
 1959    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1960        self.menu_inline_completions_policy = value;
 1961    }
 1962
 1963    pub fn set_autoindent(&mut self, autoindent: bool) {
 1964        if autoindent {
 1965            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1966        } else {
 1967            self.autoindent_mode = None;
 1968        }
 1969    }
 1970
 1971    pub fn read_only(&self, cx: &App) -> bool {
 1972        self.read_only || self.buffer.read(cx).read_only()
 1973    }
 1974
 1975    pub fn set_read_only(&mut self, read_only: bool) {
 1976        self.read_only = read_only;
 1977    }
 1978
 1979    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1980        self.use_autoclose = autoclose;
 1981    }
 1982
 1983    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1984        self.use_auto_surround = auto_surround;
 1985    }
 1986
 1987    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1988        self.auto_replace_emoji_shortcode = auto_replace;
 1989    }
 1990
 1991    pub fn toggle_inline_completions(
 1992        &mut self,
 1993        _: &ToggleEditPrediction,
 1994        window: &mut Window,
 1995        cx: &mut Context<Self>,
 1996    ) {
 1997        if self.show_inline_completions_override.is_some() {
 1998            self.set_show_edit_predictions(None, window, cx);
 1999        } else {
 2000            let show_edit_predictions = !self.edit_predictions_enabled();
 2001            self.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 2002        }
 2003    }
 2004
 2005    pub fn set_show_edit_predictions(
 2006        &mut self,
 2007        show_edit_predictions: Option<bool>,
 2008        window: &mut Window,
 2009        cx: &mut Context<Self>,
 2010    ) {
 2011        self.show_inline_completions_override = show_edit_predictions;
 2012        self.refresh_inline_completion(false, true, window, cx);
 2013    }
 2014
 2015    fn inline_completions_disabled_in_scope(
 2016        &self,
 2017        buffer: &Entity<Buffer>,
 2018        buffer_position: language::Anchor,
 2019        cx: &App,
 2020    ) -> bool {
 2021        let snapshot = buffer.read(cx).snapshot();
 2022        let settings = snapshot.settings_at(buffer_position, cx);
 2023
 2024        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 2025            return false;
 2026        };
 2027
 2028        scope.override_name().map_or(false, |scope_name| {
 2029            settings
 2030                .edit_predictions_disabled_in
 2031                .iter()
 2032                .any(|s| s == scope_name)
 2033        })
 2034    }
 2035
 2036    pub fn set_use_modal_editing(&mut self, to: bool) {
 2037        self.use_modal_editing = to;
 2038    }
 2039
 2040    pub fn use_modal_editing(&self) -> bool {
 2041        self.use_modal_editing
 2042    }
 2043
 2044    fn selections_did_change(
 2045        &mut self,
 2046        local: bool,
 2047        old_cursor_position: &Anchor,
 2048        show_completions: bool,
 2049        window: &mut Window,
 2050        cx: &mut Context<Self>,
 2051    ) {
 2052        window.invalidate_character_coordinates();
 2053
 2054        // Copy selections to primary selection buffer
 2055        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 2056        if local {
 2057            let selections = self.selections.all::<usize>(cx);
 2058            let buffer_handle = self.buffer.read(cx).read(cx);
 2059
 2060            let mut text = String::new();
 2061            for (index, selection) in selections.iter().enumerate() {
 2062                let text_for_selection = buffer_handle
 2063                    .text_for_range(selection.start..selection.end)
 2064                    .collect::<String>();
 2065
 2066                text.push_str(&text_for_selection);
 2067                if index != selections.len() - 1 {
 2068                    text.push('\n');
 2069                }
 2070            }
 2071
 2072            if !text.is_empty() {
 2073                cx.write_to_primary(ClipboardItem::new_string(text));
 2074            }
 2075        }
 2076
 2077        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 2078            self.buffer.update(cx, |buffer, cx| {
 2079                buffer.set_active_selections(
 2080                    &self.selections.disjoint_anchors(),
 2081                    self.selections.line_mode,
 2082                    self.cursor_shape,
 2083                    cx,
 2084                )
 2085            });
 2086        }
 2087        let display_map = self
 2088            .display_map
 2089            .update(cx, |display_map, cx| display_map.snapshot(cx));
 2090        let buffer = &display_map.buffer_snapshot;
 2091        self.add_selections_state = None;
 2092        self.select_next_state = None;
 2093        self.select_prev_state = None;
 2094        self.select_larger_syntax_node_stack.clear();
 2095        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 2096        self.snippet_stack
 2097            .invalidate(&self.selections.disjoint_anchors(), buffer);
 2098        self.take_rename(false, window, cx);
 2099
 2100        let new_cursor_position = self.selections.newest_anchor().head();
 2101
 2102        self.push_to_nav_history(
 2103            *old_cursor_position,
 2104            Some(new_cursor_position.to_point(buffer)),
 2105            cx,
 2106        );
 2107
 2108        if local {
 2109            let new_cursor_position = self.selections.newest_anchor().head();
 2110            let mut context_menu = self.context_menu.borrow_mut();
 2111            let completion_menu = match context_menu.as_ref() {
 2112                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2113                _ => {
 2114                    *context_menu = None;
 2115                    None
 2116                }
 2117            };
 2118            if let Some(buffer_id) = new_cursor_position.buffer_id {
 2119                if !self.registered_buffers.contains_key(&buffer_id) {
 2120                    if let Some(project) = self.project.as_ref() {
 2121                        project.update(cx, |project, cx| {
 2122                            let Some(buffer) = self.buffer.read(cx).buffer(buffer_id) else {
 2123                                return;
 2124                            };
 2125                            self.registered_buffers.insert(
 2126                                buffer_id,
 2127                                project.register_buffer_with_language_servers(&buffer, cx),
 2128                            );
 2129                        })
 2130                    }
 2131                }
 2132            }
 2133
 2134            if let Some(completion_menu) = completion_menu {
 2135                let cursor_position = new_cursor_position.to_offset(buffer);
 2136                let (word_range, kind) =
 2137                    buffer.surrounding_word(completion_menu.initial_position, true);
 2138                if kind == Some(CharKind::Word)
 2139                    && word_range.to_inclusive().contains(&cursor_position)
 2140                {
 2141                    let mut completion_menu = completion_menu.clone();
 2142                    drop(context_menu);
 2143
 2144                    let query = Self::completion_query(buffer, cursor_position);
 2145                    cx.spawn(move |this, mut cx| async move {
 2146                        completion_menu
 2147                            .filter(query.as_deref(), cx.background_executor().clone())
 2148                            .await;
 2149
 2150                        this.update(&mut cx, |this, cx| {
 2151                            let mut context_menu = this.context_menu.borrow_mut();
 2152                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2153                            else {
 2154                                return;
 2155                            };
 2156
 2157                            if menu.id > completion_menu.id {
 2158                                return;
 2159                            }
 2160
 2161                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2162                            drop(context_menu);
 2163                            cx.notify();
 2164                        })
 2165                    })
 2166                    .detach();
 2167
 2168                    if show_completions {
 2169                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2170                    }
 2171                } else {
 2172                    drop(context_menu);
 2173                    self.hide_context_menu(window, cx);
 2174                }
 2175            } else {
 2176                drop(context_menu);
 2177            }
 2178
 2179            hide_hover(self, cx);
 2180
 2181            if old_cursor_position.to_display_point(&display_map).row()
 2182                != new_cursor_position.to_display_point(&display_map).row()
 2183            {
 2184                self.available_code_actions.take();
 2185            }
 2186            self.refresh_code_actions(window, cx);
 2187            self.refresh_document_highlights(cx);
 2188            self.refresh_selected_text_highlights(window, cx);
 2189            refresh_matching_bracket_highlights(self, window, cx);
 2190            self.update_visible_inline_completion(window, cx);
 2191            self.edit_prediction_requires_modifier_in_leading_space = true;
 2192            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2193            if self.git_blame_inline_enabled {
 2194                self.start_inline_blame_timer(window, cx);
 2195            }
 2196        }
 2197
 2198        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2199        cx.emit(EditorEvent::SelectionsChanged { local });
 2200
 2201        let selections = &self.selections.disjoint;
 2202        if selections.len() == 1 {
 2203            cx.emit(SearchEvent::ActiveMatchChanged)
 2204        }
 2205        if local
 2206            && self.is_singleton(cx)
 2207            && WorkspaceSettings::get(None, cx).restore_on_startup != RestoreOnStartupBehavior::None
 2208        {
 2209            if let Some(workspace_id) = self.workspace.as_ref().and_then(|workspace| workspace.1) {
 2210                let background_executor = cx.background_executor().clone();
 2211                let editor_id = cx.entity().entity_id().as_u64() as ItemId;
 2212                let snapshot = self.buffer().read(cx).snapshot(cx);
 2213                let selections = selections.clone();
 2214                self.serialize_selections = cx.background_spawn(async move {
 2215                    background_executor.timer(Duration::from_millis(100)).await;
 2216                    let selections = selections
 2217                        .iter()
 2218                        .map(|selection| {
 2219                            (
 2220                                selection.start.to_offset(&snapshot),
 2221                                selection.end.to_offset(&snapshot),
 2222                            )
 2223                        })
 2224                        .collect();
 2225                    DB.save_editor_selections(editor_id, workspace_id, selections)
 2226                        .await
 2227                        .with_context(|| format!("persisting editor selections for editor {editor_id}, workspace {workspace_id:?}"))
 2228                        .log_err();
 2229                });
 2230            }
 2231        }
 2232
 2233        cx.notify();
 2234    }
 2235
 2236    pub fn change_selections<R>(
 2237        &mut self,
 2238        autoscroll: Option<Autoscroll>,
 2239        window: &mut Window,
 2240        cx: &mut Context<Self>,
 2241        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2242    ) -> R {
 2243        self.change_selections_inner(autoscroll, true, window, cx, change)
 2244    }
 2245
 2246    fn change_selections_inner<R>(
 2247        &mut self,
 2248        autoscroll: Option<Autoscroll>,
 2249        request_completions: bool,
 2250        window: &mut Window,
 2251        cx: &mut Context<Self>,
 2252        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2253    ) -> R {
 2254        let old_cursor_position = self.selections.newest_anchor().head();
 2255        self.push_to_selection_history();
 2256
 2257        let (changed, result) = self.selections.change_with(cx, change);
 2258
 2259        if changed {
 2260            if let Some(autoscroll) = autoscroll {
 2261                self.request_autoscroll(autoscroll, cx);
 2262            }
 2263            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2264
 2265            if self.should_open_signature_help_automatically(
 2266                &old_cursor_position,
 2267                self.signature_help_state.backspace_pressed(),
 2268                cx,
 2269            ) {
 2270                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2271            }
 2272            self.signature_help_state.set_backspace_pressed(false);
 2273        }
 2274
 2275        result
 2276    }
 2277
 2278    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2279    where
 2280        I: IntoIterator<Item = (Range<S>, T)>,
 2281        S: ToOffset,
 2282        T: Into<Arc<str>>,
 2283    {
 2284        if self.read_only(cx) {
 2285            return;
 2286        }
 2287
 2288        self.buffer
 2289            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2290    }
 2291
 2292    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2293    where
 2294        I: IntoIterator<Item = (Range<S>, T)>,
 2295        S: ToOffset,
 2296        T: Into<Arc<str>>,
 2297    {
 2298        if self.read_only(cx) {
 2299            return;
 2300        }
 2301
 2302        self.buffer.update(cx, |buffer, cx| {
 2303            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2304        });
 2305    }
 2306
 2307    pub fn edit_with_block_indent<I, S, T>(
 2308        &mut self,
 2309        edits: I,
 2310        original_indent_columns: Vec<u32>,
 2311        cx: &mut Context<Self>,
 2312    ) where
 2313        I: IntoIterator<Item = (Range<S>, T)>,
 2314        S: ToOffset,
 2315        T: Into<Arc<str>>,
 2316    {
 2317        if self.read_only(cx) {
 2318            return;
 2319        }
 2320
 2321        self.buffer.update(cx, |buffer, cx| {
 2322            buffer.edit(
 2323                edits,
 2324                Some(AutoindentMode::Block {
 2325                    original_indent_columns,
 2326                }),
 2327                cx,
 2328            )
 2329        });
 2330    }
 2331
 2332    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2333        self.hide_context_menu(window, cx);
 2334
 2335        match phase {
 2336            SelectPhase::Begin {
 2337                position,
 2338                add,
 2339                click_count,
 2340            } => self.begin_selection(position, add, click_count, window, cx),
 2341            SelectPhase::BeginColumnar {
 2342                position,
 2343                goal_column,
 2344                reset,
 2345            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2346            SelectPhase::Extend {
 2347                position,
 2348                click_count,
 2349            } => self.extend_selection(position, click_count, window, cx),
 2350            SelectPhase::Update {
 2351                position,
 2352                goal_column,
 2353                scroll_delta,
 2354            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2355            SelectPhase::End => self.end_selection(window, cx),
 2356        }
 2357    }
 2358
 2359    fn extend_selection(
 2360        &mut self,
 2361        position: DisplayPoint,
 2362        click_count: usize,
 2363        window: &mut Window,
 2364        cx: &mut Context<Self>,
 2365    ) {
 2366        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2367        let tail = self.selections.newest::<usize>(cx).tail();
 2368        self.begin_selection(position, false, click_count, window, cx);
 2369
 2370        let position = position.to_offset(&display_map, Bias::Left);
 2371        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2372
 2373        let mut pending_selection = self
 2374            .selections
 2375            .pending_anchor()
 2376            .expect("extend_selection not called with pending selection");
 2377        if position >= tail {
 2378            pending_selection.start = tail_anchor;
 2379        } else {
 2380            pending_selection.end = tail_anchor;
 2381            pending_selection.reversed = true;
 2382        }
 2383
 2384        let mut pending_mode = self.selections.pending_mode().unwrap();
 2385        match &mut pending_mode {
 2386            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2387            _ => {}
 2388        }
 2389
 2390        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2391            s.set_pending(pending_selection, pending_mode)
 2392        });
 2393    }
 2394
 2395    fn begin_selection(
 2396        &mut self,
 2397        position: DisplayPoint,
 2398        add: bool,
 2399        click_count: usize,
 2400        window: &mut Window,
 2401        cx: &mut Context<Self>,
 2402    ) {
 2403        if !self.focus_handle.is_focused(window) {
 2404            self.last_focused_descendant = None;
 2405            window.focus(&self.focus_handle);
 2406        }
 2407
 2408        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2409        let buffer = &display_map.buffer_snapshot;
 2410        let newest_selection = self.selections.newest_anchor().clone();
 2411        let position = display_map.clip_point(position, Bias::Left);
 2412
 2413        let start;
 2414        let end;
 2415        let mode;
 2416        let mut auto_scroll;
 2417        match click_count {
 2418            1 => {
 2419                start = buffer.anchor_before(position.to_point(&display_map));
 2420                end = start;
 2421                mode = SelectMode::Character;
 2422                auto_scroll = true;
 2423            }
 2424            2 => {
 2425                let range = movement::surrounding_word(&display_map, position);
 2426                start = buffer.anchor_before(range.start.to_point(&display_map));
 2427                end = buffer.anchor_before(range.end.to_point(&display_map));
 2428                mode = SelectMode::Word(start..end);
 2429                auto_scroll = true;
 2430            }
 2431            3 => {
 2432                let position = display_map
 2433                    .clip_point(position, Bias::Left)
 2434                    .to_point(&display_map);
 2435                let line_start = display_map.prev_line_boundary(position).0;
 2436                let next_line_start = buffer.clip_point(
 2437                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2438                    Bias::Left,
 2439                );
 2440                start = buffer.anchor_before(line_start);
 2441                end = buffer.anchor_before(next_line_start);
 2442                mode = SelectMode::Line(start..end);
 2443                auto_scroll = true;
 2444            }
 2445            _ => {
 2446                start = buffer.anchor_before(0);
 2447                end = buffer.anchor_before(buffer.len());
 2448                mode = SelectMode::All;
 2449                auto_scroll = false;
 2450            }
 2451        }
 2452        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2453
 2454        let point_to_delete: Option<usize> = {
 2455            let selected_points: Vec<Selection<Point>> =
 2456                self.selections.disjoint_in_range(start..end, cx);
 2457
 2458            if !add || click_count > 1 {
 2459                None
 2460            } else if !selected_points.is_empty() {
 2461                Some(selected_points[0].id)
 2462            } else {
 2463                let clicked_point_already_selected =
 2464                    self.selections.disjoint.iter().find(|selection| {
 2465                        selection.start.to_point(buffer) == start.to_point(buffer)
 2466                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2467                    });
 2468
 2469                clicked_point_already_selected.map(|selection| selection.id)
 2470            }
 2471        };
 2472
 2473        let selections_count = self.selections.count();
 2474
 2475        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2476            if let Some(point_to_delete) = point_to_delete {
 2477                s.delete(point_to_delete);
 2478
 2479                if selections_count == 1 {
 2480                    s.set_pending_anchor_range(start..end, mode);
 2481                }
 2482            } else {
 2483                if !add {
 2484                    s.clear_disjoint();
 2485                } else if click_count > 1 {
 2486                    s.delete(newest_selection.id)
 2487                }
 2488
 2489                s.set_pending_anchor_range(start..end, mode);
 2490            }
 2491        });
 2492    }
 2493
 2494    fn begin_columnar_selection(
 2495        &mut self,
 2496        position: DisplayPoint,
 2497        goal_column: u32,
 2498        reset: bool,
 2499        window: &mut Window,
 2500        cx: &mut Context<Self>,
 2501    ) {
 2502        if !self.focus_handle.is_focused(window) {
 2503            self.last_focused_descendant = None;
 2504            window.focus(&self.focus_handle);
 2505        }
 2506
 2507        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2508
 2509        if reset {
 2510            let pointer_position = display_map
 2511                .buffer_snapshot
 2512                .anchor_before(position.to_point(&display_map));
 2513
 2514            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2515                s.clear_disjoint();
 2516                s.set_pending_anchor_range(
 2517                    pointer_position..pointer_position,
 2518                    SelectMode::Character,
 2519                );
 2520            });
 2521        }
 2522
 2523        let tail = self.selections.newest::<Point>(cx).tail();
 2524        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2525
 2526        if !reset {
 2527            self.select_columns(
 2528                tail.to_display_point(&display_map),
 2529                position,
 2530                goal_column,
 2531                &display_map,
 2532                window,
 2533                cx,
 2534            );
 2535        }
 2536    }
 2537
 2538    fn update_selection(
 2539        &mut self,
 2540        position: DisplayPoint,
 2541        goal_column: u32,
 2542        scroll_delta: gpui::Point<f32>,
 2543        window: &mut Window,
 2544        cx: &mut Context<Self>,
 2545    ) {
 2546        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2547
 2548        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2549            let tail = tail.to_display_point(&display_map);
 2550            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2551        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2552            let buffer = self.buffer.read(cx).snapshot(cx);
 2553            let head;
 2554            let tail;
 2555            let mode = self.selections.pending_mode().unwrap();
 2556            match &mode {
 2557                SelectMode::Character => {
 2558                    head = position.to_point(&display_map);
 2559                    tail = pending.tail().to_point(&buffer);
 2560                }
 2561                SelectMode::Word(original_range) => {
 2562                    let original_display_range = original_range.start.to_display_point(&display_map)
 2563                        ..original_range.end.to_display_point(&display_map);
 2564                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2565                        ..original_display_range.end.to_point(&display_map);
 2566                    if movement::is_inside_word(&display_map, position)
 2567                        || original_display_range.contains(&position)
 2568                    {
 2569                        let word_range = movement::surrounding_word(&display_map, position);
 2570                        if word_range.start < original_display_range.start {
 2571                            head = word_range.start.to_point(&display_map);
 2572                        } else {
 2573                            head = word_range.end.to_point(&display_map);
 2574                        }
 2575                    } else {
 2576                        head = position.to_point(&display_map);
 2577                    }
 2578
 2579                    if head <= original_buffer_range.start {
 2580                        tail = original_buffer_range.end;
 2581                    } else {
 2582                        tail = original_buffer_range.start;
 2583                    }
 2584                }
 2585                SelectMode::Line(original_range) => {
 2586                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2587
 2588                    let position = display_map
 2589                        .clip_point(position, Bias::Left)
 2590                        .to_point(&display_map);
 2591                    let line_start = display_map.prev_line_boundary(position).0;
 2592                    let next_line_start = buffer.clip_point(
 2593                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2594                        Bias::Left,
 2595                    );
 2596
 2597                    if line_start < original_range.start {
 2598                        head = line_start
 2599                    } else {
 2600                        head = next_line_start
 2601                    }
 2602
 2603                    if head <= original_range.start {
 2604                        tail = original_range.end;
 2605                    } else {
 2606                        tail = original_range.start;
 2607                    }
 2608                }
 2609                SelectMode::All => {
 2610                    return;
 2611                }
 2612            };
 2613
 2614            if head < tail {
 2615                pending.start = buffer.anchor_before(head);
 2616                pending.end = buffer.anchor_before(tail);
 2617                pending.reversed = true;
 2618            } else {
 2619                pending.start = buffer.anchor_before(tail);
 2620                pending.end = buffer.anchor_before(head);
 2621                pending.reversed = false;
 2622            }
 2623
 2624            self.change_selections(None, window, cx, |s| {
 2625                s.set_pending(pending, mode);
 2626            });
 2627        } else {
 2628            log::error!("update_selection dispatched with no pending selection");
 2629            return;
 2630        }
 2631
 2632        self.apply_scroll_delta(scroll_delta, window, cx);
 2633        cx.notify();
 2634    }
 2635
 2636    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2637        self.columnar_selection_tail.take();
 2638        if self.selections.pending_anchor().is_some() {
 2639            let selections = self.selections.all::<usize>(cx);
 2640            self.change_selections(None, window, cx, |s| {
 2641                s.select(selections);
 2642                s.clear_pending();
 2643            });
 2644        }
 2645    }
 2646
 2647    fn select_columns(
 2648        &mut self,
 2649        tail: DisplayPoint,
 2650        head: DisplayPoint,
 2651        goal_column: u32,
 2652        display_map: &DisplaySnapshot,
 2653        window: &mut Window,
 2654        cx: &mut Context<Self>,
 2655    ) {
 2656        let start_row = cmp::min(tail.row(), head.row());
 2657        let end_row = cmp::max(tail.row(), head.row());
 2658        let start_column = cmp::min(tail.column(), goal_column);
 2659        let end_column = cmp::max(tail.column(), goal_column);
 2660        let reversed = start_column < tail.column();
 2661
 2662        let selection_ranges = (start_row.0..=end_row.0)
 2663            .map(DisplayRow)
 2664            .filter_map(|row| {
 2665                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2666                    let start = display_map
 2667                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2668                        .to_point(display_map);
 2669                    let end = display_map
 2670                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2671                        .to_point(display_map);
 2672                    if reversed {
 2673                        Some(end..start)
 2674                    } else {
 2675                        Some(start..end)
 2676                    }
 2677                } else {
 2678                    None
 2679                }
 2680            })
 2681            .collect::<Vec<_>>();
 2682
 2683        self.change_selections(None, window, cx, |s| {
 2684            s.select_ranges(selection_ranges);
 2685        });
 2686        cx.notify();
 2687    }
 2688
 2689    pub fn has_pending_nonempty_selection(&self) -> bool {
 2690        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2691            Some(Selection { start, end, .. }) => start != end,
 2692            None => false,
 2693        };
 2694
 2695        pending_nonempty_selection
 2696            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2697    }
 2698
 2699    pub fn has_pending_selection(&self) -> bool {
 2700        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2701    }
 2702
 2703    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2704        self.selection_mark_mode = false;
 2705
 2706        if self.clear_expanded_diff_hunks(cx) {
 2707            cx.notify();
 2708            return;
 2709        }
 2710        if self.dismiss_menus_and_popups(true, window, cx) {
 2711            return;
 2712        }
 2713
 2714        if self.mode == EditorMode::Full
 2715            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2716        {
 2717            return;
 2718        }
 2719
 2720        cx.propagate();
 2721    }
 2722
 2723    pub fn dismiss_menus_and_popups(
 2724        &mut self,
 2725        is_user_requested: bool,
 2726        window: &mut Window,
 2727        cx: &mut Context<Self>,
 2728    ) -> bool {
 2729        if self.take_rename(false, window, cx).is_some() {
 2730            return true;
 2731        }
 2732
 2733        if hide_hover(self, cx) {
 2734            return true;
 2735        }
 2736
 2737        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2738            return true;
 2739        }
 2740
 2741        if self.hide_context_menu(window, cx).is_some() {
 2742            return true;
 2743        }
 2744
 2745        if self.mouse_context_menu.take().is_some() {
 2746            return true;
 2747        }
 2748
 2749        if is_user_requested && self.discard_inline_completion(true, cx) {
 2750            return true;
 2751        }
 2752
 2753        if self.snippet_stack.pop().is_some() {
 2754            return true;
 2755        }
 2756
 2757        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2758            self.dismiss_diagnostics(cx);
 2759            return true;
 2760        }
 2761
 2762        false
 2763    }
 2764
 2765    fn linked_editing_ranges_for(
 2766        &self,
 2767        selection: Range<text::Anchor>,
 2768        cx: &App,
 2769    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2770        if self.linked_edit_ranges.is_empty() {
 2771            return None;
 2772        }
 2773        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2774            selection.end.buffer_id.and_then(|end_buffer_id| {
 2775                if selection.start.buffer_id != Some(end_buffer_id) {
 2776                    return None;
 2777                }
 2778                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2779                let snapshot = buffer.read(cx).snapshot();
 2780                self.linked_edit_ranges
 2781                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2782                    .map(|ranges| (ranges, snapshot, buffer))
 2783            })?;
 2784        use text::ToOffset as TO;
 2785        // find offset from the start of current range to current cursor position
 2786        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2787
 2788        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2789        let start_difference = start_offset - start_byte_offset;
 2790        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2791        let end_difference = end_offset - start_byte_offset;
 2792        // Current range has associated linked ranges.
 2793        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2794        for range in linked_ranges.iter() {
 2795            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2796            let end_offset = start_offset + end_difference;
 2797            let start_offset = start_offset + start_difference;
 2798            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2799                continue;
 2800            }
 2801            if self.selections.disjoint_anchor_ranges().any(|s| {
 2802                if s.start.buffer_id != selection.start.buffer_id
 2803                    || s.end.buffer_id != selection.end.buffer_id
 2804                {
 2805                    return false;
 2806                }
 2807                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2808                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2809            }) {
 2810                continue;
 2811            }
 2812            let start = buffer_snapshot.anchor_after(start_offset);
 2813            let end = buffer_snapshot.anchor_after(end_offset);
 2814            linked_edits
 2815                .entry(buffer.clone())
 2816                .or_default()
 2817                .push(start..end);
 2818        }
 2819        Some(linked_edits)
 2820    }
 2821
 2822    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2823        let text: Arc<str> = text.into();
 2824
 2825        if self.read_only(cx) {
 2826            return;
 2827        }
 2828
 2829        let selections = self.selections.all_adjusted(cx);
 2830        let mut bracket_inserted = false;
 2831        let mut edits = Vec::new();
 2832        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2833        let mut new_selections = Vec::with_capacity(selections.len());
 2834        let mut new_autoclose_regions = Vec::new();
 2835        let snapshot = self.buffer.read(cx).read(cx);
 2836
 2837        for (selection, autoclose_region) in
 2838            self.selections_with_autoclose_regions(selections, &snapshot)
 2839        {
 2840            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2841                // Determine if the inserted text matches the opening or closing
 2842                // bracket of any of this language's bracket pairs.
 2843                let mut bracket_pair = None;
 2844                let mut is_bracket_pair_start = false;
 2845                let mut is_bracket_pair_end = false;
 2846                if !text.is_empty() {
 2847                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2848                    //  and they are removing the character that triggered IME popup.
 2849                    for (pair, enabled) in scope.brackets() {
 2850                        if !pair.close && !pair.surround {
 2851                            continue;
 2852                        }
 2853
 2854                        if enabled && pair.start.ends_with(text.as_ref()) {
 2855                            let prefix_len = pair.start.len() - text.len();
 2856                            let preceding_text_matches_prefix = prefix_len == 0
 2857                                || (selection.start.column >= (prefix_len as u32)
 2858                                    && snapshot.contains_str_at(
 2859                                        Point::new(
 2860                                            selection.start.row,
 2861                                            selection.start.column - (prefix_len as u32),
 2862                                        ),
 2863                                        &pair.start[..prefix_len],
 2864                                    ));
 2865                            if preceding_text_matches_prefix {
 2866                                bracket_pair = Some(pair.clone());
 2867                                is_bracket_pair_start = true;
 2868                                break;
 2869                            }
 2870                        }
 2871                        if pair.end.as_str() == text.as_ref() {
 2872                            bracket_pair = Some(pair.clone());
 2873                            is_bracket_pair_end = true;
 2874                            break;
 2875                        }
 2876                    }
 2877                }
 2878
 2879                if let Some(bracket_pair) = bracket_pair {
 2880                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2881                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2882                    let auto_surround =
 2883                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2884                    if selection.is_empty() {
 2885                        if is_bracket_pair_start {
 2886                            // If the inserted text is a suffix of an opening bracket and the
 2887                            // selection is preceded by the rest of the opening bracket, then
 2888                            // insert the closing bracket.
 2889                            let following_text_allows_autoclose = snapshot
 2890                                .chars_at(selection.start)
 2891                                .next()
 2892                                .map_or(true, |c| scope.should_autoclose_before(c));
 2893
 2894                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2895                                && bracket_pair.start.len() == 1
 2896                            {
 2897                                let target = bracket_pair.start.chars().next().unwrap();
 2898                                let current_line_count = snapshot
 2899                                    .reversed_chars_at(selection.start)
 2900                                    .take_while(|&c| c != '\n')
 2901                                    .filter(|&c| c == target)
 2902                                    .count();
 2903                                current_line_count % 2 == 1
 2904                            } else {
 2905                                false
 2906                            };
 2907
 2908                            if autoclose
 2909                                && bracket_pair.close
 2910                                && following_text_allows_autoclose
 2911                                && !is_closing_quote
 2912                            {
 2913                                let anchor = snapshot.anchor_before(selection.end);
 2914                                new_selections.push((selection.map(|_| anchor), text.len()));
 2915                                new_autoclose_regions.push((
 2916                                    anchor,
 2917                                    text.len(),
 2918                                    selection.id,
 2919                                    bracket_pair.clone(),
 2920                                ));
 2921                                edits.push((
 2922                                    selection.range(),
 2923                                    format!("{}{}", text, bracket_pair.end).into(),
 2924                                ));
 2925                                bracket_inserted = true;
 2926                                continue;
 2927                            }
 2928                        }
 2929
 2930                        if let Some(region) = autoclose_region {
 2931                            // If the selection is followed by an auto-inserted closing bracket,
 2932                            // then don't insert that closing bracket again; just move the selection
 2933                            // past the closing bracket.
 2934                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2935                                && text.as_ref() == region.pair.end.as_str();
 2936                            if should_skip {
 2937                                let anchor = snapshot.anchor_after(selection.end);
 2938                                new_selections
 2939                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2940                                continue;
 2941                            }
 2942                        }
 2943
 2944                        let always_treat_brackets_as_autoclosed = snapshot
 2945                            .settings_at(selection.start, cx)
 2946                            .always_treat_brackets_as_autoclosed;
 2947                        if always_treat_brackets_as_autoclosed
 2948                            && is_bracket_pair_end
 2949                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2950                        {
 2951                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2952                            // and the inserted text is a closing bracket and the selection is followed
 2953                            // by the closing bracket then move the selection past the closing bracket.
 2954                            let anchor = snapshot.anchor_after(selection.end);
 2955                            new_selections.push((selection.map(|_| anchor), text.len()));
 2956                            continue;
 2957                        }
 2958                    }
 2959                    // If an opening bracket is 1 character long and is typed while
 2960                    // text is selected, then surround that text with the bracket pair.
 2961                    else if auto_surround
 2962                        && bracket_pair.surround
 2963                        && is_bracket_pair_start
 2964                        && bracket_pair.start.chars().count() == 1
 2965                    {
 2966                        edits.push((selection.start..selection.start, text.clone()));
 2967                        edits.push((
 2968                            selection.end..selection.end,
 2969                            bracket_pair.end.as_str().into(),
 2970                        ));
 2971                        bracket_inserted = true;
 2972                        new_selections.push((
 2973                            Selection {
 2974                                id: selection.id,
 2975                                start: snapshot.anchor_after(selection.start),
 2976                                end: snapshot.anchor_before(selection.end),
 2977                                reversed: selection.reversed,
 2978                                goal: selection.goal,
 2979                            },
 2980                            0,
 2981                        ));
 2982                        continue;
 2983                    }
 2984                }
 2985            }
 2986
 2987            if self.auto_replace_emoji_shortcode
 2988                && selection.is_empty()
 2989                && text.as_ref().ends_with(':')
 2990            {
 2991                if let Some(possible_emoji_short_code) =
 2992                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2993                {
 2994                    if !possible_emoji_short_code.is_empty() {
 2995                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2996                            let emoji_shortcode_start = Point::new(
 2997                                selection.start.row,
 2998                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2999                            );
 3000
 3001                            // Remove shortcode from buffer
 3002                            edits.push((
 3003                                emoji_shortcode_start..selection.start,
 3004                                "".to_string().into(),
 3005                            ));
 3006                            new_selections.push((
 3007                                Selection {
 3008                                    id: selection.id,
 3009                                    start: snapshot.anchor_after(emoji_shortcode_start),
 3010                                    end: snapshot.anchor_before(selection.start),
 3011                                    reversed: selection.reversed,
 3012                                    goal: selection.goal,
 3013                                },
 3014                                0,
 3015                            ));
 3016
 3017                            // Insert emoji
 3018                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 3019                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 3020                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 3021
 3022                            continue;
 3023                        }
 3024                    }
 3025                }
 3026            }
 3027
 3028            // If not handling any auto-close operation, then just replace the selected
 3029            // text with the given input and move the selection to the end of the
 3030            // newly inserted text.
 3031            let anchor = snapshot.anchor_after(selection.end);
 3032            if !self.linked_edit_ranges.is_empty() {
 3033                let start_anchor = snapshot.anchor_before(selection.start);
 3034
 3035                let is_word_char = text.chars().next().map_or(true, |char| {
 3036                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 3037                    classifier.is_word(char)
 3038                });
 3039
 3040                if is_word_char {
 3041                    if let Some(ranges) = self
 3042                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 3043                    {
 3044                        for (buffer, edits) in ranges {
 3045                            linked_edits
 3046                                .entry(buffer.clone())
 3047                                .or_default()
 3048                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 3049                        }
 3050                    }
 3051                }
 3052            }
 3053
 3054            new_selections.push((selection.map(|_| anchor), 0));
 3055            edits.push((selection.start..selection.end, text.clone()));
 3056        }
 3057
 3058        drop(snapshot);
 3059
 3060        self.transact(window, cx, |this, window, cx| {
 3061            this.buffer.update(cx, |buffer, cx| {
 3062                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 3063            });
 3064            for (buffer, edits) in linked_edits {
 3065                buffer.update(cx, |buffer, cx| {
 3066                    let snapshot = buffer.snapshot();
 3067                    let edits = edits
 3068                        .into_iter()
 3069                        .map(|(range, text)| {
 3070                            use text::ToPoint as TP;
 3071                            let end_point = TP::to_point(&range.end, &snapshot);
 3072                            let start_point = TP::to_point(&range.start, &snapshot);
 3073                            (start_point..end_point, text)
 3074                        })
 3075                        .sorted_by_key(|(range, _)| range.start)
 3076                        .collect::<Vec<_>>();
 3077                    buffer.edit(edits, None, cx);
 3078                })
 3079            }
 3080            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 3081            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 3082            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 3083            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 3084                .zip(new_selection_deltas)
 3085                .map(|(selection, delta)| Selection {
 3086                    id: selection.id,
 3087                    start: selection.start + delta,
 3088                    end: selection.end + delta,
 3089                    reversed: selection.reversed,
 3090                    goal: SelectionGoal::None,
 3091                })
 3092                .collect::<Vec<_>>();
 3093
 3094            let mut i = 0;
 3095            for (position, delta, selection_id, pair) in new_autoclose_regions {
 3096                let position = position.to_offset(&map.buffer_snapshot) + delta;
 3097                let start = map.buffer_snapshot.anchor_before(position);
 3098                let end = map.buffer_snapshot.anchor_after(position);
 3099                while let Some(existing_state) = this.autoclose_regions.get(i) {
 3100                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 3101                        Ordering::Less => i += 1,
 3102                        Ordering::Greater => break,
 3103                        Ordering::Equal => {
 3104                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 3105                                Ordering::Less => i += 1,
 3106                                Ordering::Equal => break,
 3107                                Ordering::Greater => break,
 3108                            }
 3109                        }
 3110                    }
 3111                }
 3112                this.autoclose_regions.insert(
 3113                    i,
 3114                    AutocloseRegion {
 3115                        selection_id,
 3116                        range: start..end,
 3117                        pair,
 3118                    },
 3119                );
 3120            }
 3121
 3122            let had_active_inline_completion = this.has_active_inline_completion();
 3123            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 3124                s.select(new_selections)
 3125            });
 3126
 3127            if !bracket_inserted {
 3128                if let Some(on_type_format_task) =
 3129                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 3130                {
 3131                    on_type_format_task.detach_and_log_err(cx);
 3132                }
 3133            }
 3134
 3135            let editor_settings = EditorSettings::get_global(cx);
 3136            if bracket_inserted
 3137                && (editor_settings.auto_signature_help
 3138                    || editor_settings.show_signature_help_after_edits)
 3139            {
 3140                this.show_signature_help(&ShowSignatureHelp, window, cx);
 3141            }
 3142
 3143            let trigger_in_words =
 3144                this.show_edit_predictions_in_menu() || !had_active_inline_completion;
 3145            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 3146            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 3147            this.refresh_inline_completion(true, false, window, cx);
 3148        });
 3149    }
 3150
 3151    fn find_possible_emoji_shortcode_at_position(
 3152        snapshot: &MultiBufferSnapshot,
 3153        position: Point,
 3154    ) -> Option<String> {
 3155        let mut chars = Vec::new();
 3156        let mut found_colon = false;
 3157        for char in snapshot.reversed_chars_at(position).take(100) {
 3158            // Found a possible emoji shortcode in the middle of the buffer
 3159            if found_colon {
 3160                if char.is_whitespace() {
 3161                    chars.reverse();
 3162                    return Some(chars.iter().collect());
 3163                }
 3164                // If the previous character is not a whitespace, we are in the middle of a word
 3165                // and we only want to complete the shortcode if the word is made up of other emojis
 3166                let mut containing_word = String::new();
 3167                for ch in snapshot
 3168                    .reversed_chars_at(position)
 3169                    .skip(chars.len() + 1)
 3170                    .take(100)
 3171                {
 3172                    if ch.is_whitespace() {
 3173                        break;
 3174                    }
 3175                    containing_word.push(ch);
 3176                }
 3177                let containing_word = containing_word.chars().rev().collect::<String>();
 3178                if util::word_consists_of_emojis(containing_word.as_str()) {
 3179                    chars.reverse();
 3180                    return Some(chars.iter().collect());
 3181                }
 3182            }
 3183
 3184            if char.is_whitespace() || !char.is_ascii() {
 3185                return None;
 3186            }
 3187            if char == ':' {
 3188                found_colon = true;
 3189            } else {
 3190                chars.push(char);
 3191            }
 3192        }
 3193        // Found a possible emoji shortcode at the beginning of the buffer
 3194        chars.reverse();
 3195        Some(chars.iter().collect())
 3196    }
 3197
 3198    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3199        self.transact(window, cx, |this, window, cx| {
 3200            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3201                let selections = this.selections.all::<usize>(cx);
 3202                let multi_buffer = this.buffer.read(cx);
 3203                let buffer = multi_buffer.snapshot(cx);
 3204                selections
 3205                    .iter()
 3206                    .map(|selection| {
 3207                        let start_point = selection.start.to_point(&buffer);
 3208                        let mut indent =
 3209                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3210                        indent.len = cmp::min(indent.len, start_point.column);
 3211                        let start = selection.start;
 3212                        let end = selection.end;
 3213                        let selection_is_empty = start == end;
 3214                        let language_scope = buffer.language_scope_at(start);
 3215                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3216                            &language_scope
 3217                        {
 3218                            let leading_whitespace_len = buffer
 3219                                .reversed_chars_at(start)
 3220                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3221                                .map(|c| c.len_utf8())
 3222                                .sum::<usize>();
 3223
 3224                            let trailing_whitespace_len = buffer
 3225                                .chars_at(end)
 3226                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3227                                .map(|c| c.len_utf8())
 3228                                .sum::<usize>();
 3229
 3230                            let insert_extra_newline =
 3231                                language.brackets().any(|(pair, enabled)| {
 3232                                    let pair_start = pair.start.trim_end();
 3233                                    let pair_end = pair.end.trim_start();
 3234
 3235                                    enabled
 3236                                        && pair.newline
 3237                                        && buffer.contains_str_at(
 3238                                            end + trailing_whitespace_len,
 3239                                            pair_end,
 3240                                        )
 3241                                        && buffer.contains_str_at(
 3242                                            (start - leading_whitespace_len)
 3243                                                .saturating_sub(pair_start.len()),
 3244                                            pair_start,
 3245                                        )
 3246                                });
 3247
 3248                            // Comment extension on newline is allowed only for cursor selections
 3249                            let comment_delimiter = maybe!({
 3250                                if !selection_is_empty {
 3251                                    return None;
 3252                                }
 3253
 3254                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3255                                    return None;
 3256                                }
 3257
 3258                                let delimiters = language.line_comment_prefixes();
 3259                                let max_len_of_delimiter =
 3260                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3261                                let (snapshot, range) =
 3262                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3263
 3264                                let mut index_of_first_non_whitespace = 0;
 3265                                let comment_candidate = snapshot
 3266                                    .chars_for_range(range)
 3267                                    .skip_while(|c| {
 3268                                        let should_skip = c.is_whitespace();
 3269                                        if should_skip {
 3270                                            index_of_first_non_whitespace += 1;
 3271                                        }
 3272                                        should_skip
 3273                                    })
 3274                                    .take(max_len_of_delimiter)
 3275                                    .collect::<String>();
 3276                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3277                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3278                                })?;
 3279                                let cursor_is_placed_after_comment_marker =
 3280                                    index_of_first_non_whitespace + comment_prefix.len()
 3281                                        <= start_point.column as usize;
 3282                                if cursor_is_placed_after_comment_marker {
 3283                                    Some(comment_prefix.clone())
 3284                                } else {
 3285                                    None
 3286                                }
 3287                            });
 3288                            (comment_delimiter, insert_extra_newline)
 3289                        } else {
 3290                            (None, false)
 3291                        };
 3292
 3293                        let capacity_for_delimiter = comment_delimiter
 3294                            .as_deref()
 3295                            .map(str::len)
 3296                            .unwrap_or_default();
 3297                        let mut new_text =
 3298                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3299                        new_text.push('\n');
 3300                        new_text.extend(indent.chars());
 3301                        if let Some(delimiter) = &comment_delimiter {
 3302                            new_text.push_str(delimiter);
 3303                        }
 3304                        if insert_extra_newline {
 3305                            new_text = new_text.repeat(2);
 3306                        }
 3307
 3308                        let anchor = buffer.anchor_after(end);
 3309                        let new_selection = selection.map(|_| anchor);
 3310                        (
 3311                            (start..end, new_text),
 3312                            (insert_extra_newline, new_selection),
 3313                        )
 3314                    })
 3315                    .unzip()
 3316            };
 3317
 3318            this.edit_with_autoindent(edits, cx);
 3319            let buffer = this.buffer.read(cx).snapshot(cx);
 3320            let new_selections = selection_fixup_info
 3321                .into_iter()
 3322                .map(|(extra_newline_inserted, new_selection)| {
 3323                    let mut cursor = new_selection.end.to_point(&buffer);
 3324                    if extra_newline_inserted {
 3325                        cursor.row -= 1;
 3326                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3327                    }
 3328                    new_selection.map(|_| cursor)
 3329                })
 3330                .collect();
 3331
 3332            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3333                s.select(new_selections)
 3334            });
 3335            this.refresh_inline_completion(true, false, window, cx);
 3336        });
 3337    }
 3338
 3339    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3340        let buffer = self.buffer.read(cx);
 3341        let snapshot = buffer.snapshot(cx);
 3342
 3343        let mut edits = Vec::new();
 3344        let mut rows = Vec::new();
 3345
 3346        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3347            let cursor = selection.head();
 3348            let row = cursor.row;
 3349
 3350            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3351
 3352            let newline = "\n".to_string();
 3353            edits.push((start_of_line..start_of_line, newline));
 3354
 3355            rows.push(row + rows_inserted as u32);
 3356        }
 3357
 3358        self.transact(window, cx, |editor, window, cx| {
 3359            editor.edit(edits, cx);
 3360
 3361            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3362                let mut index = 0;
 3363                s.move_cursors_with(|map, _, _| {
 3364                    let row = rows[index];
 3365                    index += 1;
 3366
 3367                    let point = Point::new(row, 0);
 3368                    let boundary = map.next_line_boundary(point).1;
 3369                    let clipped = map.clip_point(boundary, Bias::Left);
 3370
 3371                    (clipped, SelectionGoal::None)
 3372                });
 3373            });
 3374
 3375            let mut indent_edits = Vec::new();
 3376            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3377            for row in rows {
 3378                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3379                for (row, indent) in indents {
 3380                    if indent.len == 0 {
 3381                        continue;
 3382                    }
 3383
 3384                    let text = match indent.kind {
 3385                        IndentKind::Space => " ".repeat(indent.len as usize),
 3386                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3387                    };
 3388                    let point = Point::new(row.0, 0);
 3389                    indent_edits.push((point..point, text));
 3390                }
 3391            }
 3392            editor.edit(indent_edits, cx);
 3393        });
 3394    }
 3395
 3396    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3397        let buffer = self.buffer.read(cx);
 3398        let snapshot = buffer.snapshot(cx);
 3399
 3400        let mut edits = Vec::new();
 3401        let mut rows = Vec::new();
 3402        let mut rows_inserted = 0;
 3403
 3404        for selection in self.selections.all_adjusted(cx) {
 3405            let cursor = selection.head();
 3406            let row = cursor.row;
 3407
 3408            let point = Point::new(row + 1, 0);
 3409            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3410
 3411            let newline = "\n".to_string();
 3412            edits.push((start_of_line..start_of_line, newline));
 3413
 3414            rows_inserted += 1;
 3415            rows.push(row + rows_inserted);
 3416        }
 3417
 3418        self.transact(window, cx, |editor, window, cx| {
 3419            editor.edit(edits, cx);
 3420
 3421            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3422                let mut index = 0;
 3423                s.move_cursors_with(|map, _, _| {
 3424                    let row = rows[index];
 3425                    index += 1;
 3426
 3427                    let point = Point::new(row, 0);
 3428                    let boundary = map.next_line_boundary(point).1;
 3429                    let clipped = map.clip_point(boundary, Bias::Left);
 3430
 3431                    (clipped, SelectionGoal::None)
 3432                });
 3433            });
 3434
 3435            let mut indent_edits = Vec::new();
 3436            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3437            for row in rows {
 3438                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3439                for (row, indent) in indents {
 3440                    if indent.len == 0 {
 3441                        continue;
 3442                    }
 3443
 3444                    let text = match indent.kind {
 3445                        IndentKind::Space => " ".repeat(indent.len as usize),
 3446                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3447                    };
 3448                    let point = Point::new(row.0, 0);
 3449                    indent_edits.push((point..point, text));
 3450                }
 3451            }
 3452            editor.edit(indent_edits, cx);
 3453        });
 3454    }
 3455
 3456    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3457        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3458            original_indent_columns: Vec::new(),
 3459        });
 3460        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3461    }
 3462
 3463    fn insert_with_autoindent_mode(
 3464        &mut self,
 3465        text: &str,
 3466        autoindent_mode: Option<AutoindentMode>,
 3467        window: &mut Window,
 3468        cx: &mut Context<Self>,
 3469    ) {
 3470        if self.read_only(cx) {
 3471            return;
 3472        }
 3473
 3474        let text: Arc<str> = text.into();
 3475        self.transact(window, cx, |this, window, cx| {
 3476            let old_selections = this.selections.all_adjusted(cx);
 3477            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3478                let anchors = {
 3479                    let snapshot = buffer.read(cx);
 3480                    old_selections
 3481                        .iter()
 3482                        .map(|s| {
 3483                            let anchor = snapshot.anchor_after(s.head());
 3484                            s.map(|_| anchor)
 3485                        })
 3486                        .collect::<Vec<_>>()
 3487                };
 3488                buffer.edit(
 3489                    old_selections
 3490                        .iter()
 3491                        .map(|s| (s.start..s.end, text.clone())),
 3492                    autoindent_mode,
 3493                    cx,
 3494                );
 3495                anchors
 3496            });
 3497
 3498            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3499                s.select_anchors(selection_anchors);
 3500            });
 3501
 3502            cx.notify();
 3503        });
 3504    }
 3505
 3506    fn trigger_completion_on_input(
 3507        &mut self,
 3508        text: &str,
 3509        trigger_in_words: bool,
 3510        window: &mut Window,
 3511        cx: &mut Context<Self>,
 3512    ) {
 3513        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3514            self.show_completions(
 3515                &ShowCompletions {
 3516                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3517                },
 3518                window,
 3519                cx,
 3520            );
 3521        } else {
 3522            self.hide_context_menu(window, cx);
 3523        }
 3524    }
 3525
 3526    fn is_completion_trigger(
 3527        &self,
 3528        text: &str,
 3529        trigger_in_words: bool,
 3530        cx: &mut Context<Self>,
 3531    ) -> bool {
 3532        let position = self.selections.newest_anchor().head();
 3533        let multibuffer = self.buffer.read(cx);
 3534        let Some(buffer) = position
 3535            .buffer_id
 3536            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3537        else {
 3538            return false;
 3539        };
 3540
 3541        if let Some(completion_provider) = &self.completion_provider {
 3542            completion_provider.is_completion_trigger(
 3543                &buffer,
 3544                position.text_anchor,
 3545                text,
 3546                trigger_in_words,
 3547                cx,
 3548            )
 3549        } else {
 3550            false
 3551        }
 3552    }
 3553
 3554    /// If any empty selections is touching the start of its innermost containing autoclose
 3555    /// region, expand it to select the brackets.
 3556    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3557        let selections = self.selections.all::<usize>(cx);
 3558        let buffer = self.buffer.read(cx).read(cx);
 3559        let new_selections = self
 3560            .selections_with_autoclose_regions(selections, &buffer)
 3561            .map(|(mut selection, region)| {
 3562                if !selection.is_empty() {
 3563                    return selection;
 3564                }
 3565
 3566                if let Some(region) = region {
 3567                    let mut range = region.range.to_offset(&buffer);
 3568                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3569                        range.start -= region.pair.start.len();
 3570                        if buffer.contains_str_at(range.start, &region.pair.start)
 3571                            && buffer.contains_str_at(range.end, &region.pair.end)
 3572                        {
 3573                            range.end += region.pair.end.len();
 3574                            selection.start = range.start;
 3575                            selection.end = range.end;
 3576
 3577                            return selection;
 3578                        }
 3579                    }
 3580                }
 3581
 3582                let always_treat_brackets_as_autoclosed = buffer
 3583                    .settings_at(selection.start, cx)
 3584                    .always_treat_brackets_as_autoclosed;
 3585
 3586                if !always_treat_brackets_as_autoclosed {
 3587                    return selection;
 3588                }
 3589
 3590                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3591                    for (pair, enabled) in scope.brackets() {
 3592                        if !enabled || !pair.close {
 3593                            continue;
 3594                        }
 3595
 3596                        if buffer.contains_str_at(selection.start, &pair.end) {
 3597                            let pair_start_len = pair.start.len();
 3598                            if buffer.contains_str_at(
 3599                                selection.start.saturating_sub(pair_start_len),
 3600                                &pair.start,
 3601                            ) {
 3602                                selection.start -= pair_start_len;
 3603                                selection.end += pair.end.len();
 3604
 3605                                return selection;
 3606                            }
 3607                        }
 3608                    }
 3609                }
 3610
 3611                selection
 3612            })
 3613            .collect();
 3614
 3615        drop(buffer);
 3616        self.change_selections(None, window, cx, |selections| {
 3617            selections.select(new_selections)
 3618        });
 3619    }
 3620
 3621    /// Iterate the given selections, and for each one, find the smallest surrounding
 3622    /// autoclose region. This uses the ordering of the selections and the autoclose
 3623    /// regions to avoid repeated comparisons.
 3624    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3625        &'a self,
 3626        selections: impl IntoIterator<Item = Selection<D>>,
 3627        buffer: &'a MultiBufferSnapshot,
 3628    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3629        let mut i = 0;
 3630        let mut regions = self.autoclose_regions.as_slice();
 3631        selections.into_iter().map(move |selection| {
 3632            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3633
 3634            let mut enclosing = None;
 3635            while let Some(pair_state) = regions.get(i) {
 3636                if pair_state.range.end.to_offset(buffer) < range.start {
 3637                    regions = &regions[i + 1..];
 3638                    i = 0;
 3639                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3640                    break;
 3641                } else {
 3642                    if pair_state.selection_id == selection.id {
 3643                        enclosing = Some(pair_state);
 3644                    }
 3645                    i += 1;
 3646                }
 3647            }
 3648
 3649            (selection, enclosing)
 3650        })
 3651    }
 3652
 3653    /// Remove any autoclose regions that no longer contain their selection.
 3654    fn invalidate_autoclose_regions(
 3655        &mut self,
 3656        mut selections: &[Selection<Anchor>],
 3657        buffer: &MultiBufferSnapshot,
 3658    ) {
 3659        self.autoclose_regions.retain(|state| {
 3660            let mut i = 0;
 3661            while let Some(selection) = selections.get(i) {
 3662                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3663                    selections = &selections[1..];
 3664                    continue;
 3665                }
 3666                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3667                    break;
 3668                }
 3669                if selection.id == state.selection_id {
 3670                    return true;
 3671                } else {
 3672                    i += 1;
 3673                }
 3674            }
 3675            false
 3676        });
 3677    }
 3678
 3679    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3680        let offset = position.to_offset(buffer);
 3681        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3682        if offset > word_range.start && kind == Some(CharKind::Word) {
 3683            Some(
 3684                buffer
 3685                    .text_for_range(word_range.start..offset)
 3686                    .collect::<String>(),
 3687            )
 3688        } else {
 3689            None
 3690        }
 3691    }
 3692
 3693    pub fn toggle_inlay_hints(
 3694        &mut self,
 3695        _: &ToggleInlayHints,
 3696        _: &mut Window,
 3697        cx: &mut Context<Self>,
 3698    ) {
 3699        self.refresh_inlay_hints(
 3700            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3701            cx,
 3702        );
 3703    }
 3704
 3705    pub fn inlay_hints_enabled(&self) -> bool {
 3706        self.inlay_hint_cache.enabled
 3707    }
 3708
 3709    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3710        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3711            return;
 3712        }
 3713
 3714        let reason_description = reason.description();
 3715        let ignore_debounce = matches!(
 3716            reason,
 3717            InlayHintRefreshReason::SettingsChange(_)
 3718                | InlayHintRefreshReason::Toggle(_)
 3719                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3720        );
 3721        let (invalidate_cache, required_languages) = match reason {
 3722            InlayHintRefreshReason::Toggle(enabled) => {
 3723                self.inlay_hint_cache.enabled = enabled;
 3724                if enabled {
 3725                    (InvalidationStrategy::RefreshRequested, None)
 3726                } else {
 3727                    self.inlay_hint_cache.clear();
 3728                    self.splice_inlays(
 3729                        &self
 3730                            .visible_inlay_hints(cx)
 3731                            .iter()
 3732                            .map(|inlay| inlay.id)
 3733                            .collect::<Vec<InlayId>>(),
 3734                        Vec::new(),
 3735                        cx,
 3736                    );
 3737                    return;
 3738                }
 3739            }
 3740            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3741                match self.inlay_hint_cache.update_settings(
 3742                    &self.buffer,
 3743                    new_settings,
 3744                    self.visible_inlay_hints(cx),
 3745                    cx,
 3746                ) {
 3747                    ControlFlow::Break(Some(InlaySplice {
 3748                        to_remove,
 3749                        to_insert,
 3750                    })) => {
 3751                        self.splice_inlays(&to_remove, to_insert, cx);
 3752                        return;
 3753                    }
 3754                    ControlFlow::Break(None) => return,
 3755                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3756                }
 3757            }
 3758            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3759                if let Some(InlaySplice {
 3760                    to_remove,
 3761                    to_insert,
 3762                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3763                {
 3764                    self.splice_inlays(&to_remove, to_insert, cx);
 3765                }
 3766                return;
 3767            }
 3768            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3769            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3770                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3771            }
 3772            InlayHintRefreshReason::RefreshRequested => {
 3773                (InvalidationStrategy::RefreshRequested, None)
 3774            }
 3775        };
 3776
 3777        if let Some(InlaySplice {
 3778            to_remove,
 3779            to_insert,
 3780        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3781            reason_description,
 3782            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3783            invalidate_cache,
 3784            ignore_debounce,
 3785            cx,
 3786        ) {
 3787            self.splice_inlays(&to_remove, to_insert, cx);
 3788        }
 3789    }
 3790
 3791    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3792        self.display_map
 3793            .read(cx)
 3794            .current_inlays()
 3795            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3796            .cloned()
 3797            .collect()
 3798    }
 3799
 3800    pub fn excerpts_for_inlay_hints_query(
 3801        &self,
 3802        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3803        cx: &mut Context<Editor>,
 3804    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3805        let Some(project) = self.project.as_ref() else {
 3806            return HashMap::default();
 3807        };
 3808        let project = project.read(cx);
 3809        let multi_buffer = self.buffer().read(cx);
 3810        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3811        let multi_buffer_visible_start = self
 3812            .scroll_manager
 3813            .anchor()
 3814            .anchor
 3815            .to_point(&multi_buffer_snapshot);
 3816        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3817            multi_buffer_visible_start
 3818                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3819            Bias::Left,
 3820        );
 3821        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3822        multi_buffer_snapshot
 3823            .range_to_buffer_ranges(multi_buffer_visible_range)
 3824            .into_iter()
 3825            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3826            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3827                let buffer_file = project::File::from_dyn(buffer.file())?;
 3828                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3829                let worktree_entry = buffer_worktree
 3830                    .read(cx)
 3831                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3832                if worktree_entry.is_ignored {
 3833                    return None;
 3834                }
 3835
 3836                let language = buffer.language()?;
 3837                if let Some(restrict_to_languages) = restrict_to_languages {
 3838                    if !restrict_to_languages.contains(language) {
 3839                        return None;
 3840                    }
 3841                }
 3842                Some((
 3843                    excerpt_id,
 3844                    (
 3845                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3846                        buffer.version().clone(),
 3847                        excerpt_visible_range,
 3848                    ),
 3849                ))
 3850            })
 3851            .collect()
 3852    }
 3853
 3854    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3855        TextLayoutDetails {
 3856            text_system: window.text_system().clone(),
 3857            editor_style: self.style.clone().unwrap(),
 3858            rem_size: window.rem_size(),
 3859            scroll_anchor: self.scroll_manager.anchor(),
 3860            visible_rows: self.visible_line_count(),
 3861            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3862        }
 3863    }
 3864
 3865    pub fn splice_inlays(
 3866        &self,
 3867        to_remove: &[InlayId],
 3868        to_insert: Vec<Inlay>,
 3869        cx: &mut Context<Self>,
 3870    ) {
 3871        self.display_map.update(cx, |display_map, cx| {
 3872            display_map.splice_inlays(to_remove, to_insert, cx)
 3873        });
 3874        cx.notify();
 3875    }
 3876
 3877    fn trigger_on_type_formatting(
 3878        &self,
 3879        input: String,
 3880        window: &mut Window,
 3881        cx: &mut Context<Self>,
 3882    ) -> Option<Task<Result<()>>> {
 3883        if input.len() != 1 {
 3884            return None;
 3885        }
 3886
 3887        let project = self.project.as_ref()?;
 3888        let position = self.selections.newest_anchor().head();
 3889        let (buffer, buffer_position) = self
 3890            .buffer
 3891            .read(cx)
 3892            .text_anchor_for_position(position, cx)?;
 3893
 3894        let settings = language_settings::language_settings(
 3895            buffer
 3896                .read(cx)
 3897                .language_at(buffer_position)
 3898                .map(|l| l.name()),
 3899            buffer.read(cx).file(),
 3900            cx,
 3901        );
 3902        if !settings.use_on_type_format {
 3903            return None;
 3904        }
 3905
 3906        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3907        // hence we do LSP request & edit on host side only — add formats to host's history.
 3908        let push_to_lsp_host_history = true;
 3909        // If this is not the host, append its history with new edits.
 3910        let push_to_client_history = project.read(cx).is_via_collab();
 3911
 3912        let on_type_formatting = project.update(cx, |project, cx| {
 3913            project.on_type_format(
 3914                buffer.clone(),
 3915                buffer_position,
 3916                input,
 3917                push_to_lsp_host_history,
 3918                cx,
 3919            )
 3920        });
 3921        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3922            if let Some(transaction) = on_type_formatting.await? {
 3923                if push_to_client_history {
 3924                    buffer
 3925                        .update(&mut cx, |buffer, _| {
 3926                            buffer.push_transaction(transaction, Instant::now());
 3927                        })
 3928                        .ok();
 3929                }
 3930                editor.update(&mut cx, |editor, cx| {
 3931                    editor.refresh_document_highlights(cx);
 3932                })?;
 3933            }
 3934            Ok(())
 3935        }))
 3936    }
 3937
 3938    pub fn show_completions(
 3939        &mut self,
 3940        options: &ShowCompletions,
 3941        window: &mut Window,
 3942        cx: &mut Context<Self>,
 3943    ) {
 3944        if self.pending_rename.is_some() {
 3945            return;
 3946        }
 3947
 3948        let Some(provider) = self.completion_provider.as_ref() else {
 3949            return;
 3950        };
 3951
 3952        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3953            return;
 3954        }
 3955
 3956        let position = self.selections.newest_anchor().head();
 3957        if position.diff_base_anchor.is_some() {
 3958            return;
 3959        }
 3960        let (buffer, buffer_position) =
 3961            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3962                output
 3963            } else {
 3964                return;
 3965            };
 3966        let show_completion_documentation = buffer
 3967            .read(cx)
 3968            .snapshot()
 3969            .settings_at(buffer_position, cx)
 3970            .show_completion_documentation;
 3971
 3972        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3973
 3974        let trigger_kind = match &options.trigger {
 3975            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3976                CompletionTriggerKind::TRIGGER_CHARACTER
 3977            }
 3978            _ => CompletionTriggerKind::INVOKED,
 3979        };
 3980        let completion_context = CompletionContext {
 3981            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3982                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3983                    Some(String::from(trigger))
 3984                } else {
 3985                    None
 3986                }
 3987            }),
 3988            trigger_kind,
 3989        };
 3990        let completions =
 3991            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3992        let sort_completions = provider.sort_completions();
 3993
 3994        let id = post_inc(&mut self.next_completion_id);
 3995        let task = cx.spawn_in(window, |editor, mut cx| {
 3996            async move {
 3997                editor.update(&mut cx, |this, _| {
 3998                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3999                })?;
 4000                let completions = completions.await.log_err();
 4001                let menu = if let Some(completions) = completions {
 4002                    let mut menu = CompletionsMenu::new(
 4003                        id,
 4004                        sort_completions,
 4005                        show_completion_documentation,
 4006                        position,
 4007                        buffer.clone(),
 4008                        completions.into(),
 4009                    );
 4010
 4011                    menu.filter(query.as_deref(), cx.background_executor().clone())
 4012                        .await;
 4013
 4014                    menu.visible().then_some(menu)
 4015                } else {
 4016                    None
 4017                };
 4018
 4019                editor.update_in(&mut cx, |editor, window, cx| {
 4020                    match editor.context_menu.borrow().as_ref() {
 4021                        None => {}
 4022                        Some(CodeContextMenu::Completions(prev_menu)) => {
 4023                            if prev_menu.id > id {
 4024                                return;
 4025                            }
 4026                        }
 4027                        _ => return,
 4028                    }
 4029
 4030                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 4031                        let mut menu = menu.unwrap();
 4032                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 4033
 4034                        *editor.context_menu.borrow_mut() =
 4035                            Some(CodeContextMenu::Completions(menu));
 4036
 4037                        if editor.show_edit_predictions_in_menu() {
 4038                            editor.update_visible_inline_completion(window, cx);
 4039                        } else {
 4040                            editor.discard_inline_completion(false, cx);
 4041                        }
 4042
 4043                        cx.notify();
 4044                    } else if editor.completion_tasks.len() <= 1 {
 4045                        // If there are no more completion tasks and the last menu was
 4046                        // empty, we should hide it.
 4047                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 4048                        // If it was already hidden and we don't show inline
 4049                        // completions in the menu, we should also show the
 4050                        // inline-completion when available.
 4051                        if was_hidden && editor.show_edit_predictions_in_menu() {
 4052                            editor.update_visible_inline_completion(window, cx);
 4053                        }
 4054                    }
 4055                })?;
 4056
 4057                Ok::<_, anyhow::Error>(())
 4058            }
 4059            .log_err()
 4060        });
 4061
 4062        self.completion_tasks.push((id, task));
 4063    }
 4064
 4065    pub fn confirm_completion(
 4066        &mut self,
 4067        action: &ConfirmCompletion,
 4068        window: &mut Window,
 4069        cx: &mut Context<Self>,
 4070    ) -> Option<Task<Result<()>>> {
 4071        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 4072    }
 4073
 4074    pub fn compose_completion(
 4075        &mut self,
 4076        action: &ComposeCompletion,
 4077        window: &mut Window,
 4078        cx: &mut Context<Self>,
 4079    ) -> Option<Task<Result<()>>> {
 4080        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 4081    }
 4082
 4083    fn do_completion(
 4084        &mut self,
 4085        item_ix: Option<usize>,
 4086        intent: CompletionIntent,
 4087        window: &mut Window,
 4088        cx: &mut Context<Editor>,
 4089    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 4090        use language::ToOffset as _;
 4091
 4092        let completions_menu =
 4093            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 4094                menu
 4095            } else {
 4096                return None;
 4097            };
 4098
 4099        let entries = completions_menu.entries.borrow();
 4100        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 4101        if self.show_edit_predictions_in_menu() {
 4102            self.discard_inline_completion(true, cx);
 4103        }
 4104        let candidate_id = mat.candidate_id;
 4105        drop(entries);
 4106
 4107        let buffer_handle = completions_menu.buffer;
 4108        let completion = completions_menu
 4109            .completions
 4110            .borrow()
 4111            .get(candidate_id)?
 4112            .clone();
 4113        cx.stop_propagation();
 4114
 4115        let snippet;
 4116        let text;
 4117
 4118        if completion.is_snippet() {
 4119            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 4120            text = snippet.as_ref().unwrap().text.clone();
 4121        } else {
 4122            snippet = None;
 4123            text = completion.new_text.clone();
 4124        };
 4125        let selections = self.selections.all::<usize>(cx);
 4126        let buffer = buffer_handle.read(cx);
 4127        let old_range = completion.old_range.to_offset(buffer);
 4128        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 4129
 4130        let newest_selection = self.selections.newest_anchor();
 4131        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 4132            return None;
 4133        }
 4134
 4135        let lookbehind = newest_selection
 4136            .start
 4137            .text_anchor
 4138            .to_offset(buffer)
 4139            .saturating_sub(old_range.start);
 4140        let lookahead = old_range
 4141            .end
 4142            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 4143        let mut common_prefix_len = old_text
 4144            .bytes()
 4145            .zip(text.bytes())
 4146            .take_while(|(a, b)| a == b)
 4147            .count();
 4148
 4149        let snapshot = self.buffer.read(cx).snapshot(cx);
 4150        let mut range_to_replace: Option<Range<isize>> = None;
 4151        let mut ranges = Vec::new();
 4152        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 4153        for selection in &selections {
 4154            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 4155                let start = selection.start.saturating_sub(lookbehind);
 4156                let end = selection.end + lookahead;
 4157                if selection.id == newest_selection.id {
 4158                    range_to_replace = Some(
 4159                        ((start + common_prefix_len) as isize - selection.start as isize)
 4160                            ..(end as isize - selection.start as isize),
 4161                    );
 4162                }
 4163                ranges.push(start + common_prefix_len..end);
 4164            } else {
 4165                common_prefix_len = 0;
 4166                ranges.clear();
 4167                ranges.extend(selections.iter().map(|s| {
 4168                    if s.id == newest_selection.id {
 4169                        range_to_replace = Some(
 4170                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4171                                - selection.start as isize
 4172                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4173                                    - selection.start as isize,
 4174                        );
 4175                        old_range.clone()
 4176                    } else {
 4177                        s.start..s.end
 4178                    }
 4179                }));
 4180                break;
 4181            }
 4182            if !self.linked_edit_ranges.is_empty() {
 4183                let start_anchor = snapshot.anchor_before(selection.head());
 4184                let end_anchor = snapshot.anchor_after(selection.tail());
 4185                if let Some(ranges) = self
 4186                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4187                {
 4188                    for (buffer, edits) in ranges {
 4189                        linked_edits.entry(buffer.clone()).or_default().extend(
 4190                            edits
 4191                                .into_iter()
 4192                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4193                        );
 4194                    }
 4195                }
 4196            }
 4197        }
 4198        let text = &text[common_prefix_len..];
 4199
 4200        cx.emit(EditorEvent::InputHandled {
 4201            utf16_range_to_replace: range_to_replace,
 4202            text: text.into(),
 4203        });
 4204
 4205        self.transact(window, cx, |this, window, cx| {
 4206            if let Some(mut snippet) = snippet {
 4207                snippet.text = text.to_string();
 4208                for tabstop in snippet
 4209                    .tabstops
 4210                    .iter_mut()
 4211                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4212                {
 4213                    tabstop.start -= common_prefix_len as isize;
 4214                    tabstop.end -= common_prefix_len as isize;
 4215                }
 4216
 4217                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4218            } else {
 4219                this.buffer.update(cx, |buffer, cx| {
 4220                    buffer.edit(
 4221                        ranges.iter().map(|range| (range.clone(), text)),
 4222                        this.autoindent_mode.clone(),
 4223                        cx,
 4224                    );
 4225                });
 4226            }
 4227            for (buffer, edits) in linked_edits {
 4228                buffer.update(cx, |buffer, cx| {
 4229                    let snapshot = buffer.snapshot();
 4230                    let edits = edits
 4231                        .into_iter()
 4232                        .map(|(range, text)| {
 4233                            use text::ToPoint as TP;
 4234                            let end_point = TP::to_point(&range.end, &snapshot);
 4235                            let start_point = TP::to_point(&range.start, &snapshot);
 4236                            (start_point..end_point, text)
 4237                        })
 4238                        .sorted_by_key(|(range, _)| range.start)
 4239                        .collect::<Vec<_>>();
 4240                    buffer.edit(edits, None, cx);
 4241                })
 4242            }
 4243
 4244            this.refresh_inline_completion(true, false, window, cx);
 4245        });
 4246
 4247        let show_new_completions_on_confirm = completion
 4248            .confirm
 4249            .as_ref()
 4250            .map_or(false, |confirm| confirm(intent, window, cx));
 4251        if show_new_completions_on_confirm {
 4252            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4253        }
 4254
 4255        let provider = self.completion_provider.as_ref()?;
 4256        drop(completion);
 4257        let apply_edits = provider.apply_additional_edits_for_completion(
 4258            buffer_handle,
 4259            completions_menu.completions.clone(),
 4260            candidate_id,
 4261            true,
 4262            cx,
 4263        );
 4264
 4265        let editor_settings = EditorSettings::get_global(cx);
 4266        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4267            // After the code completion is finished, users often want to know what signatures are needed.
 4268            // so we should automatically call signature_help
 4269            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4270        }
 4271
 4272        Some(cx.foreground_executor().spawn(async move {
 4273            apply_edits.await?;
 4274            Ok(())
 4275        }))
 4276    }
 4277
 4278    pub fn toggle_code_actions(
 4279        &mut self,
 4280        action: &ToggleCodeActions,
 4281        window: &mut Window,
 4282        cx: &mut Context<Self>,
 4283    ) {
 4284        let mut context_menu = self.context_menu.borrow_mut();
 4285        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4286            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4287                // Toggle if we're selecting the same one
 4288                *context_menu = None;
 4289                cx.notify();
 4290                return;
 4291            } else {
 4292                // Otherwise, clear it and start a new one
 4293                *context_menu = None;
 4294                cx.notify();
 4295            }
 4296        }
 4297        drop(context_menu);
 4298        let snapshot = self.snapshot(window, cx);
 4299        let deployed_from_indicator = action.deployed_from_indicator;
 4300        let mut task = self.code_actions_task.take();
 4301        let action = action.clone();
 4302        cx.spawn_in(window, |editor, mut cx| async move {
 4303            while let Some(prev_task) = task {
 4304                prev_task.await.log_err();
 4305                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4306            }
 4307
 4308            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4309                if editor.focus_handle.is_focused(window) {
 4310                    let multibuffer_point = action
 4311                        .deployed_from_indicator
 4312                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4313                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4314                    let (buffer, buffer_row) = snapshot
 4315                        .buffer_snapshot
 4316                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4317                        .and_then(|(buffer_snapshot, range)| {
 4318                            editor
 4319                                .buffer
 4320                                .read(cx)
 4321                                .buffer(buffer_snapshot.remote_id())
 4322                                .map(|buffer| (buffer, range.start.row))
 4323                        })?;
 4324                    let (_, code_actions) = editor
 4325                        .available_code_actions
 4326                        .clone()
 4327                        .and_then(|(location, code_actions)| {
 4328                            let snapshot = location.buffer.read(cx).snapshot();
 4329                            let point_range = location.range.to_point(&snapshot);
 4330                            let point_range = point_range.start.row..=point_range.end.row;
 4331                            if point_range.contains(&buffer_row) {
 4332                                Some((location, code_actions))
 4333                            } else {
 4334                                None
 4335                            }
 4336                        })
 4337                        .unzip();
 4338                    let buffer_id = buffer.read(cx).remote_id();
 4339                    let tasks = editor
 4340                        .tasks
 4341                        .get(&(buffer_id, buffer_row))
 4342                        .map(|t| Arc::new(t.to_owned()));
 4343                    if tasks.is_none() && code_actions.is_none() {
 4344                        return None;
 4345                    }
 4346
 4347                    editor.completion_tasks.clear();
 4348                    editor.discard_inline_completion(false, cx);
 4349                    let task_context =
 4350                        tasks
 4351                            .as_ref()
 4352                            .zip(editor.project.clone())
 4353                            .map(|(tasks, project)| {
 4354                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4355                            });
 4356
 4357                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4358                        let task_context = match task_context {
 4359                            Some(task_context) => task_context.await,
 4360                            None => None,
 4361                        };
 4362                        let resolved_tasks =
 4363                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4364                                Rc::new(ResolvedTasks {
 4365                                    templates: tasks.resolve(&task_context).collect(),
 4366                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4367                                        multibuffer_point.row,
 4368                                        tasks.column,
 4369                                    )),
 4370                                })
 4371                            });
 4372                        let spawn_straight_away = resolved_tasks
 4373                            .as_ref()
 4374                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4375                            && code_actions
 4376                                .as_ref()
 4377                                .map_or(true, |actions| actions.is_empty());
 4378                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4379                            *editor.context_menu.borrow_mut() =
 4380                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4381                                    buffer,
 4382                                    actions: CodeActionContents {
 4383                                        tasks: resolved_tasks,
 4384                                        actions: code_actions,
 4385                                    },
 4386                                    selected_item: Default::default(),
 4387                                    scroll_handle: UniformListScrollHandle::default(),
 4388                                    deployed_from_indicator,
 4389                                }));
 4390                            if spawn_straight_away {
 4391                                if let Some(task) = editor.confirm_code_action(
 4392                                    &ConfirmCodeAction { item_ix: Some(0) },
 4393                                    window,
 4394                                    cx,
 4395                                ) {
 4396                                    cx.notify();
 4397                                    return task;
 4398                                }
 4399                            }
 4400                            cx.notify();
 4401                            Task::ready(Ok(()))
 4402                        }) {
 4403                            task.await
 4404                        } else {
 4405                            Ok(())
 4406                        }
 4407                    }))
 4408                } else {
 4409                    Some(Task::ready(Ok(())))
 4410                }
 4411            })?;
 4412            if let Some(task) = spawned_test_task {
 4413                task.await?;
 4414            }
 4415
 4416            Ok::<_, anyhow::Error>(())
 4417        })
 4418        .detach_and_log_err(cx);
 4419    }
 4420
 4421    pub fn confirm_code_action(
 4422        &mut self,
 4423        action: &ConfirmCodeAction,
 4424        window: &mut Window,
 4425        cx: &mut Context<Self>,
 4426    ) -> Option<Task<Result<()>>> {
 4427        let actions_menu =
 4428            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4429                menu
 4430            } else {
 4431                return None;
 4432            };
 4433        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4434        let action = actions_menu.actions.get(action_ix)?;
 4435        let title = action.label();
 4436        let buffer = actions_menu.buffer;
 4437        let workspace = self.workspace()?;
 4438
 4439        match action {
 4440            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4441                workspace.update(cx, |workspace, cx| {
 4442                    workspace::tasks::schedule_resolved_task(
 4443                        workspace,
 4444                        task_source_kind,
 4445                        resolved_task,
 4446                        false,
 4447                        cx,
 4448                    );
 4449
 4450                    Some(Task::ready(Ok(())))
 4451                })
 4452            }
 4453            CodeActionsItem::CodeAction {
 4454                excerpt_id,
 4455                action,
 4456                provider,
 4457            } => {
 4458                let apply_code_action =
 4459                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4460                let workspace = workspace.downgrade();
 4461                Some(cx.spawn_in(window, |editor, cx| async move {
 4462                    let project_transaction = apply_code_action.await?;
 4463                    Self::open_project_transaction(
 4464                        &editor,
 4465                        workspace,
 4466                        project_transaction,
 4467                        title,
 4468                        cx,
 4469                    )
 4470                    .await
 4471                }))
 4472            }
 4473        }
 4474    }
 4475
 4476    pub async fn open_project_transaction(
 4477        this: &WeakEntity<Editor>,
 4478        workspace: WeakEntity<Workspace>,
 4479        transaction: ProjectTransaction,
 4480        title: String,
 4481        mut cx: AsyncWindowContext,
 4482    ) -> Result<()> {
 4483        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4484        cx.update(|_, cx| {
 4485            entries.sort_unstable_by_key(|(buffer, _)| {
 4486                buffer.read(cx).file().map(|f| f.path().clone())
 4487            });
 4488        })?;
 4489
 4490        // If the project transaction's edits are all contained within this editor, then
 4491        // avoid opening a new editor to display them.
 4492
 4493        if let Some((buffer, transaction)) = entries.first() {
 4494            if entries.len() == 1 {
 4495                let excerpt = this.update(&mut cx, |editor, cx| {
 4496                    editor
 4497                        .buffer()
 4498                        .read(cx)
 4499                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4500                })?;
 4501                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4502                    if excerpted_buffer == *buffer {
 4503                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4504                            let excerpt_range = excerpt_range.to_offset(buffer);
 4505                            buffer
 4506                                .edited_ranges_for_transaction::<usize>(transaction)
 4507                                .all(|range| {
 4508                                    excerpt_range.start <= range.start
 4509                                        && excerpt_range.end >= range.end
 4510                                })
 4511                        })?;
 4512
 4513                        if all_edits_within_excerpt {
 4514                            return Ok(());
 4515                        }
 4516                    }
 4517                }
 4518            }
 4519        } else {
 4520            return Ok(());
 4521        }
 4522
 4523        let mut ranges_to_highlight = Vec::new();
 4524        let excerpt_buffer = cx.new(|cx| {
 4525            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4526            for (buffer_handle, transaction) in &entries {
 4527                let buffer = buffer_handle.read(cx);
 4528                ranges_to_highlight.extend(
 4529                    multibuffer.push_excerpts_with_context_lines(
 4530                        buffer_handle.clone(),
 4531                        buffer
 4532                            .edited_ranges_for_transaction::<usize>(transaction)
 4533                            .collect(),
 4534                        DEFAULT_MULTIBUFFER_CONTEXT,
 4535                        cx,
 4536                    ),
 4537                );
 4538            }
 4539            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4540            multibuffer
 4541        })?;
 4542
 4543        workspace.update_in(&mut cx, |workspace, window, cx| {
 4544            let project = workspace.project().clone();
 4545            let editor = cx
 4546                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4547            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4548            editor.update(cx, |editor, cx| {
 4549                editor.highlight_background::<Self>(
 4550                    &ranges_to_highlight,
 4551                    |theme| theme.editor_highlighted_line_background,
 4552                    cx,
 4553                );
 4554            });
 4555        })?;
 4556
 4557        Ok(())
 4558    }
 4559
 4560    pub fn clear_code_action_providers(&mut self) {
 4561        self.code_action_providers.clear();
 4562        self.available_code_actions.take();
 4563    }
 4564
 4565    pub fn add_code_action_provider(
 4566        &mut self,
 4567        provider: Rc<dyn CodeActionProvider>,
 4568        window: &mut Window,
 4569        cx: &mut Context<Self>,
 4570    ) {
 4571        if self
 4572            .code_action_providers
 4573            .iter()
 4574            .any(|existing_provider| existing_provider.id() == provider.id())
 4575        {
 4576            return;
 4577        }
 4578
 4579        self.code_action_providers.push(provider);
 4580        self.refresh_code_actions(window, cx);
 4581    }
 4582
 4583    pub fn remove_code_action_provider(
 4584        &mut self,
 4585        id: Arc<str>,
 4586        window: &mut Window,
 4587        cx: &mut Context<Self>,
 4588    ) {
 4589        self.code_action_providers
 4590            .retain(|provider| provider.id() != id);
 4591        self.refresh_code_actions(window, cx);
 4592    }
 4593
 4594    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4595        let buffer = self.buffer.read(cx);
 4596        let newest_selection = self.selections.newest_anchor().clone();
 4597        if newest_selection.head().diff_base_anchor.is_some() {
 4598            return None;
 4599        }
 4600        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4601        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4602        if start_buffer != end_buffer {
 4603            return None;
 4604        }
 4605
 4606        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4607            cx.background_executor()
 4608                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4609                .await;
 4610
 4611            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4612                let providers = this.code_action_providers.clone();
 4613                let tasks = this
 4614                    .code_action_providers
 4615                    .iter()
 4616                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4617                    .collect::<Vec<_>>();
 4618                (providers, tasks)
 4619            })?;
 4620
 4621            let mut actions = Vec::new();
 4622            for (provider, provider_actions) in
 4623                providers.into_iter().zip(future::join_all(tasks).await)
 4624            {
 4625                if let Some(provider_actions) = provider_actions.log_err() {
 4626                    actions.extend(provider_actions.into_iter().map(|action| {
 4627                        AvailableCodeAction {
 4628                            excerpt_id: newest_selection.start.excerpt_id,
 4629                            action,
 4630                            provider: provider.clone(),
 4631                        }
 4632                    }));
 4633                }
 4634            }
 4635
 4636            this.update(&mut cx, |this, cx| {
 4637                this.available_code_actions = if actions.is_empty() {
 4638                    None
 4639                } else {
 4640                    Some((
 4641                        Location {
 4642                            buffer: start_buffer,
 4643                            range: start..end,
 4644                        },
 4645                        actions.into(),
 4646                    ))
 4647                };
 4648                cx.notify();
 4649            })
 4650        }));
 4651        None
 4652    }
 4653
 4654    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4655        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4656            self.show_git_blame_inline = false;
 4657
 4658            self.show_git_blame_inline_delay_task =
 4659                Some(cx.spawn_in(window, |this, mut cx| async move {
 4660                    cx.background_executor().timer(delay).await;
 4661
 4662                    this.update(&mut cx, |this, cx| {
 4663                        this.show_git_blame_inline = true;
 4664                        cx.notify();
 4665                    })
 4666                    .log_err();
 4667                }));
 4668        }
 4669    }
 4670
 4671    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4672        if self.pending_rename.is_some() {
 4673            return None;
 4674        }
 4675
 4676        let provider = self.semantics_provider.clone()?;
 4677        let buffer = self.buffer.read(cx);
 4678        let newest_selection = self.selections.newest_anchor().clone();
 4679        let cursor_position = newest_selection.head();
 4680        let (cursor_buffer, cursor_buffer_position) =
 4681            buffer.text_anchor_for_position(cursor_position, cx)?;
 4682        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4683        if cursor_buffer != tail_buffer {
 4684            return None;
 4685        }
 4686        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4687        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4688            cx.background_executor()
 4689                .timer(Duration::from_millis(debounce))
 4690                .await;
 4691
 4692            let highlights = if let Some(highlights) = cx
 4693                .update(|cx| {
 4694                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4695                })
 4696                .ok()
 4697                .flatten()
 4698            {
 4699                highlights.await.log_err()
 4700            } else {
 4701                None
 4702            };
 4703
 4704            if let Some(highlights) = highlights {
 4705                this.update(&mut cx, |this, cx| {
 4706                    if this.pending_rename.is_some() {
 4707                        return;
 4708                    }
 4709
 4710                    let buffer_id = cursor_position.buffer_id;
 4711                    let buffer = this.buffer.read(cx);
 4712                    if !buffer
 4713                        .text_anchor_for_position(cursor_position, cx)
 4714                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4715                    {
 4716                        return;
 4717                    }
 4718
 4719                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4720                    let mut write_ranges = Vec::new();
 4721                    let mut read_ranges = Vec::new();
 4722                    for highlight in highlights {
 4723                        for (excerpt_id, excerpt_range) in
 4724                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4725                        {
 4726                            let start = highlight
 4727                                .range
 4728                                .start
 4729                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4730                            let end = highlight
 4731                                .range
 4732                                .end
 4733                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4734                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4735                                continue;
 4736                            }
 4737
 4738                            let range = Anchor {
 4739                                buffer_id,
 4740                                excerpt_id,
 4741                                text_anchor: start,
 4742                                diff_base_anchor: None,
 4743                            }..Anchor {
 4744                                buffer_id,
 4745                                excerpt_id,
 4746                                text_anchor: end,
 4747                                diff_base_anchor: None,
 4748                            };
 4749                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4750                                write_ranges.push(range);
 4751                            } else {
 4752                                read_ranges.push(range);
 4753                            }
 4754                        }
 4755                    }
 4756
 4757                    this.highlight_background::<DocumentHighlightRead>(
 4758                        &read_ranges,
 4759                        |theme| theme.editor_document_highlight_read_background,
 4760                        cx,
 4761                    );
 4762                    this.highlight_background::<DocumentHighlightWrite>(
 4763                        &write_ranges,
 4764                        |theme| theme.editor_document_highlight_write_background,
 4765                        cx,
 4766                    );
 4767                    cx.notify();
 4768                })
 4769                .log_err();
 4770            }
 4771        }));
 4772        None
 4773    }
 4774
 4775    pub fn refresh_selected_text_highlights(
 4776        &mut self,
 4777        window: &mut Window,
 4778        cx: &mut Context<Editor>,
 4779    ) {
 4780        self.selection_highlight_task.take();
 4781        if !EditorSettings::get_global(cx).selection_highlight {
 4782            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4783            return;
 4784        }
 4785        if self.selections.count() != 1 || self.selections.line_mode {
 4786            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4787            return;
 4788        }
 4789        let selection = self.selections.newest::<Point>(cx);
 4790        if selection.is_empty() || selection.start.row != selection.end.row {
 4791            self.clear_background_highlights::<SelectedTextHighlight>(cx);
 4792            return;
 4793        }
 4794        let debounce = EditorSettings::get_global(cx).selection_highlight_debounce;
 4795        self.selection_highlight_task = Some(cx.spawn_in(window, |editor, mut cx| async move {
 4796            cx.background_executor()
 4797                .timer(Duration::from_millis(debounce))
 4798                .await;
 4799            let Some(Some(matches_task)) = editor
 4800                .update_in(&mut cx, |editor, _, cx| {
 4801                    if editor.selections.count() != 1 || editor.selections.line_mode {
 4802                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4803                        return None;
 4804                    }
 4805                    let selection = editor.selections.newest::<Point>(cx);
 4806                    if selection.is_empty() || selection.start.row != selection.end.row {
 4807                        editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4808                        return None;
 4809                    }
 4810                    let buffer = editor.buffer().read(cx).snapshot(cx);
 4811                    Some(cx.background_spawn(async move {
 4812                        let mut ranges = Vec::new();
 4813                        let query = buffer.text_for_range(selection.range()).collect::<String>();
 4814                        let selection_anchors = selection.range().to_anchors(&buffer);
 4815                        for range in [buffer.anchor_before(0)..buffer.anchor_after(buffer.len())] {
 4816                            for (search_buffer, search_range, excerpt_id) in
 4817                                buffer.range_to_buffer_ranges(range)
 4818                            {
 4819                                ranges.extend(
 4820                                    project::search::SearchQuery::text(
 4821                                        query.clone(),
 4822                                        false,
 4823                                        false,
 4824                                        false,
 4825                                        Default::default(),
 4826                                        Default::default(),
 4827                                        None,
 4828                                    )
 4829                                    .unwrap()
 4830                                    .search(search_buffer, Some(search_range.clone()))
 4831                                    .await
 4832                                    .into_iter()
 4833                                    .filter_map(
 4834                                        |match_range| {
 4835                                            let start = search_buffer.anchor_after(
 4836                                                search_range.start + match_range.start,
 4837                                            );
 4838                                            let end = search_buffer.anchor_before(
 4839                                                search_range.start + match_range.end,
 4840                                            );
 4841                                            let range = Anchor::range_in_buffer(
 4842                                                excerpt_id,
 4843                                                search_buffer.remote_id(),
 4844                                                start..end,
 4845                                            );
 4846                                            (range != selection_anchors).then_some(range)
 4847                                        },
 4848                                    ),
 4849                                );
 4850                            }
 4851                        }
 4852                        ranges
 4853                    }))
 4854                })
 4855                .log_err()
 4856            else {
 4857                return;
 4858            };
 4859            let matches = matches_task.await;
 4860            editor
 4861                .update_in(&mut cx, |editor, _, cx| {
 4862                    editor.clear_background_highlights::<SelectedTextHighlight>(cx);
 4863                    if !matches.is_empty() {
 4864                        editor.highlight_background::<SelectedTextHighlight>(
 4865                            &matches,
 4866                            |theme| theme.editor_document_highlight_bracket_background,
 4867                            cx,
 4868                        )
 4869                    }
 4870                })
 4871                .log_err();
 4872        }));
 4873    }
 4874
 4875    pub fn refresh_inline_completion(
 4876        &mut self,
 4877        debounce: bool,
 4878        user_requested: bool,
 4879        window: &mut Window,
 4880        cx: &mut Context<Self>,
 4881    ) -> Option<()> {
 4882        let provider = self.edit_prediction_provider()?;
 4883        let cursor = self.selections.newest_anchor().head();
 4884        let (buffer, cursor_buffer_position) =
 4885            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4886
 4887        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4888            self.discard_inline_completion(false, cx);
 4889            return None;
 4890        }
 4891
 4892        if !user_requested
 4893            && (!self.should_show_edit_predictions()
 4894                || !self.is_focused(window)
 4895                || buffer.read(cx).is_empty())
 4896        {
 4897            self.discard_inline_completion(false, cx);
 4898            return None;
 4899        }
 4900
 4901        self.update_visible_inline_completion(window, cx);
 4902        provider.refresh(
 4903            self.project.clone(),
 4904            buffer,
 4905            cursor_buffer_position,
 4906            debounce,
 4907            cx,
 4908        );
 4909        Some(())
 4910    }
 4911
 4912    fn show_edit_predictions_in_menu(&self) -> bool {
 4913        match self.edit_prediction_settings {
 4914            EditPredictionSettings::Disabled => false,
 4915            EditPredictionSettings::Enabled { show_in_menu, .. } => show_in_menu,
 4916        }
 4917    }
 4918
 4919    pub fn edit_predictions_enabled(&self) -> bool {
 4920        match self.edit_prediction_settings {
 4921            EditPredictionSettings::Disabled => false,
 4922            EditPredictionSettings::Enabled { .. } => true,
 4923        }
 4924    }
 4925
 4926    fn edit_prediction_requires_modifier(&self) -> bool {
 4927        match self.edit_prediction_settings {
 4928            EditPredictionSettings::Disabled => false,
 4929            EditPredictionSettings::Enabled {
 4930                preview_requires_modifier,
 4931                ..
 4932            } => preview_requires_modifier,
 4933        }
 4934    }
 4935
 4936    fn edit_prediction_settings_at_position(
 4937        &self,
 4938        buffer: &Entity<Buffer>,
 4939        buffer_position: language::Anchor,
 4940        cx: &App,
 4941    ) -> EditPredictionSettings {
 4942        if self.mode != EditorMode::Full
 4943            || !self.show_inline_completions_override.unwrap_or(true)
 4944            || self.inline_completions_disabled_in_scope(buffer, buffer_position, cx)
 4945        {
 4946            return EditPredictionSettings::Disabled;
 4947        }
 4948
 4949        let buffer = buffer.read(cx);
 4950
 4951        let file = buffer.file();
 4952
 4953        if !language_settings(buffer.language().map(|l| l.name()), file, cx).show_edit_predictions {
 4954            return EditPredictionSettings::Disabled;
 4955        };
 4956
 4957        let by_provider = matches!(
 4958            self.menu_inline_completions_policy,
 4959            MenuInlineCompletionsPolicy::ByProvider
 4960        );
 4961
 4962        let show_in_menu = by_provider
 4963            && self
 4964                .edit_prediction_provider
 4965                .as_ref()
 4966                .map_or(false, |provider| {
 4967                    provider.provider.show_completions_in_menu()
 4968                });
 4969
 4970        let preview_requires_modifier =
 4971            all_language_settings(file, cx).edit_predictions_mode() == EditPredictionsMode::Auto;
 4972
 4973        EditPredictionSettings::Enabled {
 4974            show_in_menu,
 4975            preview_requires_modifier,
 4976        }
 4977    }
 4978
 4979    fn should_show_edit_predictions(&self) -> bool {
 4980        self.snippet_stack.is_empty() && self.edit_predictions_enabled()
 4981    }
 4982
 4983    pub fn edit_prediction_preview_is_active(&self) -> bool {
 4984        matches!(
 4985            self.edit_prediction_preview,
 4986            EditPredictionPreview::Active { .. }
 4987        )
 4988    }
 4989
 4990    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4991        let cursor = self.selections.newest_anchor().head();
 4992        if let Some((buffer, cursor_position)) =
 4993            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4994        {
 4995            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4996        } else {
 4997            false
 4998        }
 4999    }
 5000
 5001    fn inline_completions_enabled_in_buffer(
 5002        &self,
 5003        buffer: &Entity<Buffer>,
 5004        buffer_position: language::Anchor,
 5005        cx: &App,
 5006    ) -> bool {
 5007        maybe!({
 5008            let provider = self.edit_prediction_provider()?;
 5009            if !provider.is_enabled(&buffer, buffer_position, cx) {
 5010                return Some(false);
 5011            }
 5012            let buffer = buffer.read(cx);
 5013            let Some(file) = buffer.file() else {
 5014                return Some(true);
 5015            };
 5016            let settings = all_language_settings(Some(file), cx);
 5017            Some(settings.inline_completions_enabled_for_path(file.path()))
 5018        })
 5019        .unwrap_or(false)
 5020    }
 5021
 5022    fn cycle_inline_completion(
 5023        &mut self,
 5024        direction: Direction,
 5025        window: &mut Window,
 5026        cx: &mut Context<Self>,
 5027    ) -> Option<()> {
 5028        let provider = self.edit_prediction_provider()?;
 5029        let cursor = self.selections.newest_anchor().head();
 5030        let (buffer, cursor_buffer_position) =
 5031            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5032        if self.inline_completions_hidden_for_vim_mode || !self.should_show_edit_predictions() {
 5033            return None;
 5034        }
 5035
 5036        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 5037        self.update_visible_inline_completion(window, cx);
 5038
 5039        Some(())
 5040    }
 5041
 5042    pub fn show_inline_completion(
 5043        &mut self,
 5044        _: &ShowEditPrediction,
 5045        window: &mut Window,
 5046        cx: &mut Context<Self>,
 5047    ) {
 5048        if !self.has_active_inline_completion() {
 5049            self.refresh_inline_completion(false, true, window, cx);
 5050            return;
 5051        }
 5052
 5053        self.update_visible_inline_completion(window, cx);
 5054    }
 5055
 5056    pub fn display_cursor_names(
 5057        &mut self,
 5058        _: &DisplayCursorNames,
 5059        window: &mut Window,
 5060        cx: &mut Context<Self>,
 5061    ) {
 5062        self.show_cursor_names(window, cx);
 5063    }
 5064
 5065    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 5066        self.show_cursor_names = true;
 5067        cx.notify();
 5068        cx.spawn_in(window, |this, mut cx| async move {
 5069            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 5070            this.update(&mut cx, |this, cx| {
 5071                this.show_cursor_names = false;
 5072                cx.notify()
 5073            })
 5074            .ok()
 5075        })
 5076        .detach();
 5077    }
 5078
 5079    pub fn next_edit_prediction(
 5080        &mut self,
 5081        _: &NextEditPrediction,
 5082        window: &mut Window,
 5083        cx: &mut Context<Self>,
 5084    ) {
 5085        if self.has_active_inline_completion() {
 5086            self.cycle_inline_completion(Direction::Next, window, cx);
 5087        } else {
 5088            let is_copilot_disabled = self
 5089                .refresh_inline_completion(false, true, window, cx)
 5090                .is_none();
 5091            if is_copilot_disabled {
 5092                cx.propagate();
 5093            }
 5094        }
 5095    }
 5096
 5097    pub fn previous_edit_prediction(
 5098        &mut self,
 5099        _: &PreviousEditPrediction,
 5100        window: &mut Window,
 5101        cx: &mut Context<Self>,
 5102    ) {
 5103        if self.has_active_inline_completion() {
 5104            self.cycle_inline_completion(Direction::Prev, window, cx);
 5105        } else {
 5106            let is_copilot_disabled = self
 5107                .refresh_inline_completion(false, true, window, cx)
 5108                .is_none();
 5109            if is_copilot_disabled {
 5110                cx.propagate();
 5111            }
 5112        }
 5113    }
 5114
 5115    pub fn accept_edit_prediction(
 5116        &mut self,
 5117        _: &AcceptEditPrediction,
 5118        window: &mut Window,
 5119        cx: &mut Context<Self>,
 5120    ) {
 5121        if self.show_edit_predictions_in_menu() {
 5122            self.hide_context_menu(window, cx);
 5123        }
 5124
 5125        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5126            return;
 5127        };
 5128
 5129        self.report_inline_completion_event(
 5130            active_inline_completion.completion_id.clone(),
 5131            true,
 5132            cx,
 5133        );
 5134
 5135        match &active_inline_completion.completion {
 5136            InlineCompletion::Move { target, .. } => {
 5137                let target = *target;
 5138
 5139                if let Some(position_map) = &self.last_position_map {
 5140                    if position_map
 5141                        .visible_row_range
 5142                        .contains(&target.to_display_point(&position_map.snapshot).row())
 5143                        || !self.edit_prediction_requires_modifier()
 5144                    {
 5145                        self.unfold_ranges(&[target..target], true, false, cx);
 5146                        // Note that this is also done in vim's handler of the Tab action.
 5147                        self.change_selections(
 5148                            Some(Autoscroll::newest()),
 5149                            window,
 5150                            cx,
 5151                            |selections| {
 5152                                selections.select_anchor_ranges([target..target]);
 5153                            },
 5154                        );
 5155                        self.clear_row_highlights::<EditPredictionPreview>();
 5156
 5157                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5158                            previous_scroll_position: None,
 5159                        };
 5160                    } else {
 5161                        self.edit_prediction_preview = EditPredictionPreview::Active {
 5162                            previous_scroll_position: Some(position_map.snapshot.scroll_anchor),
 5163                        };
 5164                        self.highlight_rows::<EditPredictionPreview>(
 5165                            target..target,
 5166                            cx.theme().colors().editor_highlighted_line_background,
 5167                            true,
 5168                            cx,
 5169                        );
 5170                        self.request_autoscroll(Autoscroll::fit(), cx);
 5171                    }
 5172                }
 5173            }
 5174            InlineCompletion::Edit { edits, .. } => {
 5175                if let Some(provider) = self.edit_prediction_provider() {
 5176                    provider.accept(cx);
 5177                }
 5178
 5179                let snapshot = self.buffer.read(cx).snapshot(cx);
 5180                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 5181
 5182                self.buffer.update(cx, |buffer, cx| {
 5183                    buffer.edit(edits.iter().cloned(), None, cx)
 5184                });
 5185
 5186                self.change_selections(None, window, cx, |s| {
 5187                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 5188                });
 5189
 5190                self.update_visible_inline_completion(window, cx);
 5191                if self.active_inline_completion.is_none() {
 5192                    self.refresh_inline_completion(true, true, window, cx);
 5193                }
 5194
 5195                cx.notify();
 5196            }
 5197        }
 5198
 5199        self.edit_prediction_requires_modifier_in_leading_space = false;
 5200    }
 5201
 5202    pub fn accept_partial_inline_completion(
 5203        &mut self,
 5204        _: &AcceptPartialEditPrediction,
 5205        window: &mut Window,
 5206        cx: &mut Context<Self>,
 5207    ) {
 5208        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 5209            return;
 5210        };
 5211        if self.selections.count() != 1 {
 5212            return;
 5213        }
 5214
 5215        self.report_inline_completion_event(
 5216            active_inline_completion.completion_id.clone(),
 5217            true,
 5218            cx,
 5219        );
 5220
 5221        match &active_inline_completion.completion {
 5222            InlineCompletion::Move { target, .. } => {
 5223                let target = *target;
 5224                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 5225                    selections.select_anchor_ranges([target..target]);
 5226                });
 5227            }
 5228            InlineCompletion::Edit { edits, .. } => {
 5229                // Find an insertion that starts at the cursor position.
 5230                let snapshot = self.buffer.read(cx).snapshot(cx);
 5231                let cursor_offset = self.selections.newest::<usize>(cx).head();
 5232                let insertion = edits.iter().find_map(|(range, text)| {
 5233                    let range = range.to_offset(&snapshot);
 5234                    if range.is_empty() && range.start == cursor_offset {
 5235                        Some(text)
 5236                    } else {
 5237                        None
 5238                    }
 5239                });
 5240
 5241                if let Some(text) = insertion {
 5242                    let mut partial_completion = text
 5243                        .chars()
 5244                        .by_ref()
 5245                        .take_while(|c| c.is_alphabetic())
 5246                        .collect::<String>();
 5247                    if partial_completion.is_empty() {
 5248                        partial_completion = text
 5249                            .chars()
 5250                            .by_ref()
 5251                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 5252                            .collect::<String>();
 5253                    }
 5254
 5255                    cx.emit(EditorEvent::InputHandled {
 5256                        utf16_range_to_replace: None,
 5257                        text: partial_completion.clone().into(),
 5258                    });
 5259
 5260                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 5261
 5262                    self.refresh_inline_completion(true, true, window, cx);
 5263                    cx.notify();
 5264                } else {
 5265                    self.accept_edit_prediction(&Default::default(), window, cx);
 5266                }
 5267            }
 5268        }
 5269    }
 5270
 5271    fn discard_inline_completion(
 5272        &mut self,
 5273        should_report_inline_completion_event: bool,
 5274        cx: &mut Context<Self>,
 5275    ) -> bool {
 5276        if should_report_inline_completion_event {
 5277            let completion_id = self
 5278                .active_inline_completion
 5279                .as_ref()
 5280                .and_then(|active_completion| active_completion.completion_id.clone());
 5281
 5282            self.report_inline_completion_event(completion_id, false, cx);
 5283        }
 5284
 5285        if let Some(provider) = self.edit_prediction_provider() {
 5286            provider.discard(cx);
 5287        }
 5288
 5289        self.take_active_inline_completion(cx)
 5290    }
 5291
 5292    fn report_inline_completion_event(&self, id: Option<SharedString>, accepted: bool, cx: &App) {
 5293        let Some(provider) = self.edit_prediction_provider() else {
 5294            return;
 5295        };
 5296
 5297        let Some((_, buffer, _)) = self
 5298            .buffer
 5299            .read(cx)
 5300            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 5301        else {
 5302            return;
 5303        };
 5304
 5305        let extension = buffer
 5306            .read(cx)
 5307            .file()
 5308            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5309
 5310        let event_type = match accepted {
 5311            true => "Edit Prediction Accepted",
 5312            false => "Edit Prediction Discarded",
 5313        };
 5314        telemetry::event!(
 5315            event_type,
 5316            provider = provider.name(),
 5317            prediction_id = id,
 5318            suggestion_accepted = accepted,
 5319            file_extension = extension,
 5320        );
 5321    }
 5322
 5323    pub fn has_active_inline_completion(&self) -> bool {
 5324        self.active_inline_completion.is_some()
 5325    }
 5326
 5327    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5328        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5329            return false;
 5330        };
 5331
 5332        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5333        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5334        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5335        true
 5336    }
 5337
 5338    /// Returns true when we're displaying the edit prediction popover below the cursor
 5339    /// like we are not previewing and the LSP autocomplete menu is visible
 5340    /// or we are in `when_holding_modifier` mode.
 5341    pub fn edit_prediction_visible_in_cursor_popover(&self, has_completion: bool) -> bool {
 5342        if self.edit_prediction_preview_is_active()
 5343            || !self.show_edit_predictions_in_menu()
 5344            || !self.edit_predictions_enabled()
 5345        {
 5346            return false;
 5347        }
 5348
 5349        if self.has_visible_completions_menu() {
 5350            return true;
 5351        }
 5352
 5353        has_completion && self.edit_prediction_requires_modifier()
 5354    }
 5355
 5356    fn handle_modifiers_changed(
 5357        &mut self,
 5358        modifiers: Modifiers,
 5359        position_map: &PositionMap,
 5360        window: &mut Window,
 5361        cx: &mut Context<Self>,
 5362    ) {
 5363        if self.show_edit_predictions_in_menu() {
 5364            self.update_edit_prediction_preview(&modifiers, window, cx);
 5365        }
 5366
 5367        self.update_selection_mode(&modifiers, position_map, window, cx);
 5368
 5369        let mouse_position = window.mouse_position();
 5370        if !position_map.text_hitbox.is_hovered(window) {
 5371            return;
 5372        }
 5373
 5374        self.update_hovered_link(
 5375            position_map.point_for_position(mouse_position),
 5376            &position_map.snapshot,
 5377            modifiers,
 5378            window,
 5379            cx,
 5380        )
 5381    }
 5382
 5383    fn update_selection_mode(
 5384        &mut self,
 5385        modifiers: &Modifiers,
 5386        position_map: &PositionMap,
 5387        window: &mut Window,
 5388        cx: &mut Context<Self>,
 5389    ) {
 5390        if modifiers != &COLUMNAR_SELECTION_MODIFIERS || self.selections.pending.is_none() {
 5391            return;
 5392        }
 5393
 5394        let mouse_position = window.mouse_position();
 5395        let point_for_position = position_map.point_for_position(mouse_position);
 5396        let position = point_for_position.previous_valid;
 5397
 5398        self.select(
 5399            SelectPhase::BeginColumnar {
 5400                position,
 5401                reset: false,
 5402                goal_column: point_for_position.exact_unclipped.column(),
 5403            },
 5404            window,
 5405            cx,
 5406        );
 5407    }
 5408
 5409    fn update_edit_prediction_preview(
 5410        &mut self,
 5411        modifiers: &Modifiers,
 5412        window: &mut Window,
 5413        cx: &mut Context<Self>,
 5414    ) {
 5415        let accept_keybind = self.accept_edit_prediction_keybind(window, cx);
 5416        let Some(accept_keystroke) = accept_keybind.keystroke() else {
 5417            return;
 5418        };
 5419
 5420        if &accept_keystroke.modifiers == modifiers && accept_keystroke.modifiers.modified() {
 5421            if matches!(
 5422                self.edit_prediction_preview,
 5423                EditPredictionPreview::Inactive
 5424            ) {
 5425                self.edit_prediction_preview = EditPredictionPreview::Active {
 5426                    previous_scroll_position: None,
 5427                };
 5428
 5429                self.update_visible_inline_completion(window, cx);
 5430                cx.notify();
 5431            }
 5432        } else if let EditPredictionPreview::Active {
 5433            previous_scroll_position,
 5434        } = self.edit_prediction_preview
 5435        {
 5436            if let (Some(previous_scroll_position), Some(position_map)) =
 5437                (previous_scroll_position, self.last_position_map.as_ref())
 5438            {
 5439                self.set_scroll_position(
 5440                    previous_scroll_position
 5441                        .scroll_position(&position_map.snapshot.display_snapshot),
 5442                    window,
 5443                    cx,
 5444                );
 5445            }
 5446
 5447            self.edit_prediction_preview = EditPredictionPreview::Inactive;
 5448            self.clear_row_highlights::<EditPredictionPreview>();
 5449            self.update_visible_inline_completion(window, cx);
 5450            cx.notify();
 5451        }
 5452    }
 5453
 5454    fn update_visible_inline_completion(
 5455        &mut self,
 5456        _window: &mut Window,
 5457        cx: &mut Context<Self>,
 5458    ) -> Option<()> {
 5459        let selection = self.selections.newest_anchor();
 5460        let cursor = selection.head();
 5461        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5462        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5463        let excerpt_id = cursor.excerpt_id;
 5464
 5465        let show_in_menu = self.show_edit_predictions_in_menu();
 5466        let completions_menu_has_precedence = !show_in_menu
 5467            && (self.context_menu.borrow().is_some()
 5468                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5469
 5470        if completions_menu_has_precedence
 5471            || !offset_selection.is_empty()
 5472            || self
 5473                .active_inline_completion
 5474                .as_ref()
 5475                .map_or(false, |completion| {
 5476                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5477                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5478                    !invalidation_range.contains(&offset_selection.head())
 5479                })
 5480        {
 5481            self.discard_inline_completion(false, cx);
 5482            return None;
 5483        }
 5484
 5485        self.take_active_inline_completion(cx);
 5486        let Some(provider) = self.edit_prediction_provider() else {
 5487            self.edit_prediction_settings = EditPredictionSettings::Disabled;
 5488            return None;
 5489        };
 5490
 5491        let (buffer, cursor_buffer_position) =
 5492            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5493
 5494        self.edit_prediction_settings =
 5495            self.edit_prediction_settings_at_position(&buffer, cursor_buffer_position, cx);
 5496
 5497        self.edit_prediction_cursor_on_leading_whitespace =
 5498            multibuffer.is_line_whitespace_upto(cursor);
 5499
 5500        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5501        let edits = inline_completion
 5502            .edits
 5503            .into_iter()
 5504            .flat_map(|(range, new_text)| {
 5505                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5506                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5507                Some((start..end, new_text))
 5508            })
 5509            .collect::<Vec<_>>();
 5510        if edits.is_empty() {
 5511            return None;
 5512        }
 5513
 5514        let first_edit_start = edits.first().unwrap().0.start;
 5515        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5516        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5517
 5518        let last_edit_end = edits.last().unwrap().0.end;
 5519        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5520        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5521
 5522        let cursor_row = cursor.to_point(&multibuffer).row;
 5523
 5524        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5525
 5526        let mut inlay_ids = Vec::new();
 5527        let invalidation_row_range;
 5528        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5529            Some(cursor_row..edit_end_row)
 5530        } else if cursor_row > edit_end_row {
 5531            Some(edit_start_row..cursor_row)
 5532        } else {
 5533            None
 5534        };
 5535        let is_move =
 5536            move_invalidation_row_range.is_some() || self.inline_completions_hidden_for_vim_mode;
 5537        let completion = if is_move {
 5538            invalidation_row_range =
 5539                move_invalidation_row_range.unwrap_or(edit_start_row..edit_end_row);
 5540            let target = first_edit_start;
 5541            InlineCompletion::Move { target, snapshot }
 5542        } else {
 5543            let show_completions_in_buffer = !self.edit_prediction_visible_in_cursor_popover(true)
 5544                && !self.inline_completions_hidden_for_vim_mode;
 5545
 5546            if show_completions_in_buffer {
 5547                if edits
 5548                    .iter()
 5549                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5550                {
 5551                    let mut inlays = Vec::new();
 5552                    for (range, new_text) in &edits {
 5553                        let inlay = Inlay::inline_completion(
 5554                            post_inc(&mut self.next_inlay_id),
 5555                            range.start,
 5556                            new_text.as_str(),
 5557                        );
 5558                        inlay_ids.push(inlay.id);
 5559                        inlays.push(inlay);
 5560                    }
 5561
 5562                    self.splice_inlays(&[], inlays, cx);
 5563                } else {
 5564                    let background_color = cx.theme().status().deleted_background;
 5565                    self.highlight_text::<InlineCompletionHighlight>(
 5566                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5567                        HighlightStyle {
 5568                            background_color: Some(background_color),
 5569                            ..Default::default()
 5570                        },
 5571                        cx,
 5572                    );
 5573                }
 5574            }
 5575
 5576            invalidation_row_range = edit_start_row..edit_end_row;
 5577
 5578            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5579                if provider.show_tab_accept_marker() {
 5580                    EditDisplayMode::TabAccept
 5581                } else {
 5582                    EditDisplayMode::Inline
 5583                }
 5584            } else {
 5585                EditDisplayMode::DiffPopover
 5586            };
 5587
 5588            InlineCompletion::Edit {
 5589                edits,
 5590                edit_preview: inline_completion.edit_preview,
 5591                display_mode,
 5592                snapshot,
 5593            }
 5594        };
 5595
 5596        let invalidation_range = multibuffer
 5597            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5598            ..multibuffer.anchor_after(Point::new(
 5599                invalidation_row_range.end,
 5600                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5601            ));
 5602
 5603        self.stale_inline_completion_in_menu = None;
 5604        self.active_inline_completion = Some(InlineCompletionState {
 5605            inlay_ids,
 5606            completion,
 5607            completion_id: inline_completion.id,
 5608            invalidation_range,
 5609        });
 5610
 5611        cx.notify();
 5612
 5613        Some(())
 5614    }
 5615
 5616    pub fn edit_prediction_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5617        Some(self.edit_prediction_provider.as_ref()?.provider.clone())
 5618    }
 5619
 5620    fn render_code_actions_indicator(
 5621        &self,
 5622        _style: &EditorStyle,
 5623        row: DisplayRow,
 5624        is_active: bool,
 5625        cx: &mut Context<Self>,
 5626    ) -> Option<IconButton> {
 5627        if self.available_code_actions.is_some() {
 5628            Some(
 5629                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5630                    .shape(ui::IconButtonShape::Square)
 5631                    .icon_size(IconSize::XSmall)
 5632                    .icon_color(Color::Muted)
 5633                    .toggle_state(is_active)
 5634                    .tooltip({
 5635                        let focus_handle = self.focus_handle.clone();
 5636                        move |window, cx| {
 5637                            Tooltip::for_action_in(
 5638                                "Toggle Code Actions",
 5639                                &ToggleCodeActions {
 5640                                    deployed_from_indicator: None,
 5641                                },
 5642                                &focus_handle,
 5643                                window,
 5644                                cx,
 5645                            )
 5646                        }
 5647                    })
 5648                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5649                        window.focus(&editor.focus_handle(cx));
 5650                        editor.toggle_code_actions(
 5651                            &ToggleCodeActions {
 5652                                deployed_from_indicator: Some(row),
 5653                            },
 5654                            window,
 5655                            cx,
 5656                        );
 5657                    })),
 5658            )
 5659        } else {
 5660            None
 5661        }
 5662    }
 5663
 5664    fn clear_tasks(&mut self) {
 5665        self.tasks.clear()
 5666    }
 5667
 5668    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5669        if self.tasks.insert(key, value).is_some() {
 5670            // This case should hopefully be rare, but just in case...
 5671            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5672        }
 5673    }
 5674
 5675    fn build_tasks_context(
 5676        project: &Entity<Project>,
 5677        buffer: &Entity<Buffer>,
 5678        buffer_row: u32,
 5679        tasks: &Arc<RunnableTasks>,
 5680        cx: &mut Context<Self>,
 5681    ) -> Task<Option<task::TaskContext>> {
 5682        let position = Point::new(buffer_row, tasks.column);
 5683        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5684        let location = Location {
 5685            buffer: buffer.clone(),
 5686            range: range_start..range_start,
 5687        };
 5688        // Fill in the environmental variables from the tree-sitter captures
 5689        let mut captured_task_variables = TaskVariables::default();
 5690        for (capture_name, value) in tasks.extra_variables.clone() {
 5691            captured_task_variables.insert(
 5692                task::VariableName::Custom(capture_name.into()),
 5693                value.clone(),
 5694            );
 5695        }
 5696        project.update(cx, |project, cx| {
 5697            project.task_store().update(cx, |task_store, cx| {
 5698                task_store.task_context_for_location(captured_task_variables, location, cx)
 5699            })
 5700        })
 5701    }
 5702
 5703    pub fn spawn_nearest_task(
 5704        &mut self,
 5705        action: &SpawnNearestTask,
 5706        window: &mut Window,
 5707        cx: &mut Context<Self>,
 5708    ) {
 5709        let Some((workspace, _)) = self.workspace.clone() else {
 5710            return;
 5711        };
 5712        let Some(project) = self.project.clone() else {
 5713            return;
 5714        };
 5715
 5716        // Try to find a closest, enclosing node using tree-sitter that has a
 5717        // task
 5718        let Some((buffer, buffer_row, tasks)) = self
 5719            .find_enclosing_node_task(cx)
 5720            // Or find the task that's closest in row-distance.
 5721            .or_else(|| self.find_closest_task(cx))
 5722        else {
 5723            return;
 5724        };
 5725
 5726        let reveal_strategy = action.reveal;
 5727        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5728        cx.spawn_in(window, |_, mut cx| async move {
 5729            let context = task_context.await?;
 5730            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5731
 5732            let resolved = resolved_task.resolved.as_mut()?;
 5733            resolved.reveal = reveal_strategy;
 5734
 5735            workspace
 5736                .update(&mut cx, |workspace, cx| {
 5737                    workspace::tasks::schedule_resolved_task(
 5738                        workspace,
 5739                        task_source_kind,
 5740                        resolved_task,
 5741                        false,
 5742                        cx,
 5743                    );
 5744                })
 5745                .ok()
 5746        })
 5747        .detach();
 5748    }
 5749
 5750    fn find_closest_task(
 5751        &mut self,
 5752        cx: &mut Context<Self>,
 5753    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5754        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5755
 5756        let ((buffer_id, row), tasks) = self
 5757            .tasks
 5758            .iter()
 5759            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5760
 5761        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5762        let tasks = Arc::new(tasks.to_owned());
 5763        Some((buffer, *row, tasks))
 5764    }
 5765
 5766    fn find_enclosing_node_task(
 5767        &mut self,
 5768        cx: &mut Context<Self>,
 5769    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5770        let snapshot = self.buffer.read(cx).snapshot(cx);
 5771        let offset = self.selections.newest::<usize>(cx).head();
 5772        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5773        let buffer_id = excerpt.buffer().remote_id();
 5774
 5775        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5776        let mut cursor = layer.node().walk();
 5777
 5778        while cursor.goto_first_child_for_byte(offset).is_some() {
 5779            if cursor.node().end_byte() == offset {
 5780                cursor.goto_next_sibling();
 5781            }
 5782        }
 5783
 5784        // Ascend to the smallest ancestor that contains the range and has a task.
 5785        loop {
 5786            let node = cursor.node();
 5787            let node_range = node.byte_range();
 5788            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5789
 5790            // Check if this node contains our offset
 5791            if node_range.start <= offset && node_range.end >= offset {
 5792                // If it contains offset, check for task
 5793                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5794                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5795                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5796                }
 5797            }
 5798
 5799            if !cursor.goto_parent() {
 5800                break;
 5801            }
 5802        }
 5803        None
 5804    }
 5805
 5806    fn render_run_indicator(
 5807        &self,
 5808        _style: &EditorStyle,
 5809        is_active: bool,
 5810        row: DisplayRow,
 5811        cx: &mut Context<Self>,
 5812    ) -> IconButton {
 5813        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5814            .shape(ui::IconButtonShape::Square)
 5815            .icon_size(IconSize::XSmall)
 5816            .icon_color(Color::Muted)
 5817            .toggle_state(is_active)
 5818            .on_click(cx.listener(move |editor, _e, window, cx| {
 5819                window.focus(&editor.focus_handle(cx));
 5820                editor.toggle_code_actions(
 5821                    &ToggleCodeActions {
 5822                        deployed_from_indicator: Some(row),
 5823                    },
 5824                    window,
 5825                    cx,
 5826                );
 5827            }))
 5828    }
 5829
 5830    pub fn context_menu_visible(&self) -> bool {
 5831        !self.edit_prediction_preview_is_active()
 5832            && self
 5833                .context_menu
 5834                .borrow()
 5835                .as_ref()
 5836                .map_or(false, |menu| menu.visible())
 5837    }
 5838
 5839    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5840        self.context_menu
 5841            .borrow()
 5842            .as_ref()
 5843            .map(|menu| menu.origin())
 5844    }
 5845
 5846    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5847        px(30.)
 5848    }
 5849
 5850    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5851        if self.read_only(cx) {
 5852            cx.theme().players().read_only()
 5853        } else {
 5854            self.style.as_ref().unwrap().local_player
 5855        }
 5856    }
 5857
 5858    fn render_edit_prediction_accept_keybind(&self, window: &mut Window, cx: &App) -> Option<Div> {
 5859        let accept_binding = self.accept_edit_prediction_keybind(window, cx);
 5860        let accept_keystroke = accept_binding.keystroke()?;
 5861
 5862        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 5863
 5864        let modifiers_color = if accept_keystroke.modifiers == window.modifiers() {
 5865            Color::Accent
 5866        } else {
 5867            Color::Muted
 5868        };
 5869
 5870        h_flex()
 5871            .px_0p5()
 5872            .when(is_platform_style_mac, |parent| parent.gap_0p5())
 5873            .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 5874            .text_size(TextSize::XSmall.rems(cx))
 5875            .child(h_flex().children(ui::render_modifiers(
 5876                &accept_keystroke.modifiers,
 5877                PlatformStyle::platform(),
 5878                Some(modifiers_color),
 5879                Some(IconSize::XSmall.rems().into()),
 5880                true,
 5881            )))
 5882            .when(is_platform_style_mac, |parent| {
 5883                parent.child(accept_keystroke.key.clone())
 5884            })
 5885            .when(!is_platform_style_mac, |parent| {
 5886                parent.child(
 5887                    Key::new(
 5888                        util::capitalize(&accept_keystroke.key),
 5889                        Some(Color::Default),
 5890                    )
 5891                    .size(Some(IconSize::XSmall.rems().into())),
 5892                )
 5893            })
 5894            .into()
 5895    }
 5896
 5897    fn render_edit_prediction_line_popover(
 5898        &self,
 5899        label: impl Into<SharedString>,
 5900        icon: Option<IconName>,
 5901        window: &mut Window,
 5902        cx: &App,
 5903    ) -> Option<Div> {
 5904        let bg_color = Self::edit_prediction_line_popover_bg_color(cx);
 5905
 5906        let padding_right = if icon.is_some() { px(4.) } else { px(8.) };
 5907
 5908        let result = h_flex()
 5909            .gap_1()
 5910            .border_1()
 5911            .rounded_lg()
 5912            .shadow_sm()
 5913            .bg(bg_color)
 5914            .border_color(cx.theme().colors().text_accent.opacity(0.4))
 5915            .py_0p5()
 5916            .pl_1()
 5917            .pr(padding_right)
 5918            .children(self.render_edit_prediction_accept_keybind(window, cx))
 5919            .child(Label::new(label).size(LabelSize::Small))
 5920            .when_some(icon, |element, icon| {
 5921                element.child(
 5922                    div()
 5923                        .mt(px(1.5))
 5924                        .child(Icon::new(icon).size(IconSize::Small)),
 5925                )
 5926            });
 5927
 5928        Some(result)
 5929    }
 5930
 5931    fn edit_prediction_line_popover_bg_color(cx: &App) -> Hsla {
 5932        let accent_color = cx.theme().colors().text_accent;
 5933        let editor_bg_color = cx.theme().colors().editor_background;
 5934        editor_bg_color.blend(accent_color.opacity(0.1))
 5935    }
 5936
 5937    fn render_edit_prediction_cursor_popover(
 5938        &self,
 5939        min_width: Pixels,
 5940        max_width: Pixels,
 5941        cursor_point: Point,
 5942        style: &EditorStyle,
 5943        accept_keystroke: Option<&gpui::Keystroke>,
 5944        _window: &Window,
 5945        cx: &mut Context<Editor>,
 5946    ) -> Option<AnyElement> {
 5947        let provider = self.edit_prediction_provider.as_ref()?;
 5948
 5949        if provider.provider.needs_terms_acceptance(cx) {
 5950            return Some(
 5951                h_flex()
 5952                    .min_w(min_width)
 5953                    .flex_1()
 5954                    .px_2()
 5955                    .py_1()
 5956                    .gap_3()
 5957                    .elevation_2(cx)
 5958                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5959                    .id("accept-terms")
 5960                    .cursor_pointer()
 5961                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5962                    .on_click(cx.listener(|this, _event, window, cx| {
 5963                        cx.stop_propagation();
 5964                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5965                        window.dispatch_action(
 5966                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5967                            cx,
 5968                        );
 5969                    }))
 5970                    .child(
 5971                        h_flex()
 5972                            .flex_1()
 5973                            .gap_2()
 5974                            .child(Icon::new(IconName::ZedPredict))
 5975                            .child(Label::new("Accept Terms of Service"))
 5976                            .child(div().w_full())
 5977                            .child(
 5978                                Icon::new(IconName::ArrowUpRight)
 5979                                    .color(Color::Muted)
 5980                                    .size(IconSize::Small),
 5981                            )
 5982                            .into_any_element(),
 5983                    )
 5984                    .into_any(),
 5985            );
 5986        }
 5987
 5988        let is_refreshing = provider.provider.is_refreshing(cx);
 5989
 5990        fn pending_completion_container() -> Div {
 5991            h_flex()
 5992                .h_full()
 5993                .flex_1()
 5994                .gap_2()
 5995                .child(Icon::new(IconName::ZedPredict))
 5996        }
 5997
 5998        let completion = match &self.active_inline_completion {
 5999            Some(completion) => match &completion.completion {
 6000                InlineCompletion::Move {
 6001                    target, snapshot, ..
 6002                } if !self.has_visible_completions_menu() => {
 6003                    use text::ToPoint as _;
 6004
 6005                    return Some(
 6006                        h_flex()
 6007                            .px_2()
 6008                            .py_1()
 6009                            .elevation_2(cx)
 6010                            .border_color(cx.theme().colors().border)
 6011                            .rounded_tl(px(0.))
 6012                            .gap_2()
 6013                            .child(
 6014                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6015                                    Icon::new(IconName::ZedPredictDown)
 6016                                } else {
 6017                                    Icon::new(IconName::ZedPredictUp)
 6018                                },
 6019                            )
 6020                            .child(Label::new("Hold").size(LabelSize::Small))
 6021                            .child(h_flex().children(ui::render_modifiers(
 6022                                &accept_keystroke?.modifiers,
 6023                                PlatformStyle::platform(),
 6024                                Some(Color::Default),
 6025                                Some(IconSize::Small.rems().into()),
 6026                                false,
 6027                            )))
 6028                            .into_any(),
 6029                    );
 6030                }
 6031                _ => self.render_edit_prediction_cursor_popover_preview(
 6032                    completion,
 6033                    cursor_point,
 6034                    style,
 6035                    cx,
 6036                )?,
 6037            },
 6038
 6039            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6040                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6041                    stale_completion,
 6042                    cursor_point,
 6043                    style,
 6044                    cx,
 6045                )?,
 6046
 6047                None => {
 6048                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6049                }
 6050            },
 6051
 6052            None => pending_completion_container().child(Label::new("No Prediction")),
 6053        };
 6054
 6055        let completion = if is_refreshing {
 6056            completion
 6057                .with_animation(
 6058                    "loading-completion",
 6059                    Animation::new(Duration::from_secs(2))
 6060                        .repeat()
 6061                        .with_easing(pulsating_between(0.4, 0.8)),
 6062                    |label, delta| label.opacity(delta),
 6063                )
 6064                .into_any_element()
 6065        } else {
 6066            completion.into_any_element()
 6067        };
 6068
 6069        let has_completion = self.active_inline_completion.is_some();
 6070
 6071        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6072        Some(
 6073            h_flex()
 6074                .min_w(min_width)
 6075                .max_w(max_width)
 6076                .flex_1()
 6077                .elevation_2(cx)
 6078                .border_color(cx.theme().colors().border)
 6079                .child(
 6080                    div()
 6081                        .flex_1()
 6082                        .py_1()
 6083                        .px_2()
 6084                        .overflow_hidden()
 6085                        .child(completion),
 6086                )
 6087                .when_some(accept_keystroke, |el, accept_keystroke| {
 6088                    if !accept_keystroke.modifiers.modified() {
 6089                        return el;
 6090                    }
 6091
 6092                    el.child(
 6093                        h_flex()
 6094                            .h_full()
 6095                            .border_l_1()
 6096                            .rounded_r_lg()
 6097                            .border_color(cx.theme().colors().border)
 6098                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6099                            .gap_1()
 6100                            .py_1()
 6101                            .px_2()
 6102                            .child(
 6103                                h_flex()
 6104                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6105                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6106                                    .child(h_flex().children(ui::render_modifiers(
 6107                                        &accept_keystroke.modifiers,
 6108                                        PlatformStyle::platform(),
 6109                                        Some(if !has_completion {
 6110                                            Color::Muted
 6111                                        } else {
 6112                                            Color::Default
 6113                                        }),
 6114                                        None,
 6115                                        false,
 6116                                    ))),
 6117                            )
 6118                            .child(Label::new("Preview").into_any_element())
 6119                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6120                    )
 6121                })
 6122                .into_any(),
 6123        )
 6124    }
 6125
 6126    fn render_edit_prediction_cursor_popover_preview(
 6127        &self,
 6128        completion: &InlineCompletionState,
 6129        cursor_point: Point,
 6130        style: &EditorStyle,
 6131        cx: &mut Context<Editor>,
 6132    ) -> Option<Div> {
 6133        use text::ToPoint as _;
 6134
 6135        fn render_relative_row_jump(
 6136            prefix: impl Into<String>,
 6137            current_row: u32,
 6138            target_row: u32,
 6139        ) -> Div {
 6140            let (row_diff, arrow) = if target_row < current_row {
 6141                (current_row - target_row, IconName::ArrowUp)
 6142            } else {
 6143                (target_row - current_row, IconName::ArrowDown)
 6144            };
 6145
 6146            h_flex()
 6147                .child(
 6148                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6149                        .color(Color::Muted)
 6150                        .size(LabelSize::Small),
 6151                )
 6152                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6153        }
 6154
 6155        match &completion.completion {
 6156            InlineCompletion::Move {
 6157                target, snapshot, ..
 6158            } => Some(
 6159                h_flex()
 6160                    .px_2()
 6161                    .gap_2()
 6162                    .flex_1()
 6163                    .child(
 6164                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6165                            Icon::new(IconName::ZedPredictDown)
 6166                        } else {
 6167                            Icon::new(IconName::ZedPredictUp)
 6168                        },
 6169                    )
 6170                    .child(Label::new("Jump to Edit")),
 6171            ),
 6172
 6173            InlineCompletion::Edit {
 6174                edits,
 6175                edit_preview,
 6176                snapshot,
 6177                display_mode: _,
 6178            } => {
 6179                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6180
 6181                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6182                    &snapshot,
 6183                    &edits,
 6184                    edit_preview.as_ref()?,
 6185                    true,
 6186                    cx,
 6187                )
 6188                .first_line_preview();
 6189
 6190                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6191                    .with_highlights(&style.text, highlighted_edits.highlights);
 6192
 6193                let preview = h_flex()
 6194                    .gap_1()
 6195                    .min_w_16()
 6196                    .child(styled_text)
 6197                    .when(has_more_lines, |parent| parent.child(""));
 6198
 6199                let left = if first_edit_row != cursor_point.row {
 6200                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6201                        .into_any_element()
 6202                } else {
 6203                    Icon::new(IconName::ZedPredict).into_any_element()
 6204                };
 6205
 6206                Some(
 6207                    h_flex()
 6208                        .h_full()
 6209                        .flex_1()
 6210                        .gap_2()
 6211                        .pr_1()
 6212                        .overflow_x_hidden()
 6213                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6214                        .child(left)
 6215                        .child(preview),
 6216                )
 6217            }
 6218        }
 6219    }
 6220
 6221    fn render_context_menu(
 6222        &self,
 6223        style: &EditorStyle,
 6224        max_height_in_lines: u32,
 6225        y_flipped: bool,
 6226        window: &mut Window,
 6227        cx: &mut Context<Editor>,
 6228    ) -> Option<AnyElement> {
 6229        let menu = self.context_menu.borrow();
 6230        let menu = menu.as_ref()?;
 6231        if !menu.visible() {
 6232            return None;
 6233        };
 6234        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6235    }
 6236
 6237    fn render_context_menu_aside(
 6238        &mut self,
 6239        max_size: Size<Pixels>,
 6240        window: &mut Window,
 6241        cx: &mut Context<Editor>,
 6242    ) -> Option<AnyElement> {
 6243        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6244            if menu.visible() {
 6245                menu.render_aside(self, max_size, window, cx)
 6246            } else {
 6247                None
 6248            }
 6249        })
 6250    }
 6251
 6252    fn hide_context_menu(
 6253        &mut self,
 6254        window: &mut Window,
 6255        cx: &mut Context<Self>,
 6256    ) -> Option<CodeContextMenu> {
 6257        cx.notify();
 6258        self.completion_tasks.clear();
 6259        let context_menu = self.context_menu.borrow_mut().take();
 6260        self.stale_inline_completion_in_menu.take();
 6261        self.update_visible_inline_completion(window, cx);
 6262        context_menu
 6263    }
 6264
 6265    fn show_snippet_choices(
 6266        &mut self,
 6267        choices: &Vec<String>,
 6268        selection: Range<Anchor>,
 6269        cx: &mut Context<Self>,
 6270    ) {
 6271        if selection.start.buffer_id.is_none() {
 6272            return;
 6273        }
 6274        let buffer_id = selection.start.buffer_id.unwrap();
 6275        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6276        let id = post_inc(&mut self.next_completion_id);
 6277
 6278        if let Some(buffer) = buffer {
 6279            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6280                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6281            ));
 6282        }
 6283    }
 6284
 6285    pub fn insert_snippet(
 6286        &mut self,
 6287        insertion_ranges: &[Range<usize>],
 6288        snippet: Snippet,
 6289        window: &mut Window,
 6290        cx: &mut Context<Self>,
 6291    ) -> Result<()> {
 6292        struct Tabstop<T> {
 6293            is_end_tabstop: bool,
 6294            ranges: Vec<Range<T>>,
 6295            choices: Option<Vec<String>>,
 6296        }
 6297
 6298        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6299            let snippet_text: Arc<str> = snippet.text.clone().into();
 6300            buffer.edit(
 6301                insertion_ranges
 6302                    .iter()
 6303                    .cloned()
 6304                    .map(|range| (range, snippet_text.clone())),
 6305                Some(AutoindentMode::EachLine),
 6306                cx,
 6307            );
 6308
 6309            let snapshot = &*buffer.read(cx);
 6310            let snippet = &snippet;
 6311            snippet
 6312                .tabstops
 6313                .iter()
 6314                .map(|tabstop| {
 6315                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6316                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6317                    });
 6318                    let mut tabstop_ranges = tabstop
 6319                        .ranges
 6320                        .iter()
 6321                        .flat_map(|tabstop_range| {
 6322                            let mut delta = 0_isize;
 6323                            insertion_ranges.iter().map(move |insertion_range| {
 6324                                let insertion_start = insertion_range.start as isize + delta;
 6325                                delta +=
 6326                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6327
 6328                                let start = ((insertion_start + tabstop_range.start) as usize)
 6329                                    .min(snapshot.len());
 6330                                let end = ((insertion_start + tabstop_range.end) as usize)
 6331                                    .min(snapshot.len());
 6332                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6333                            })
 6334                        })
 6335                        .collect::<Vec<_>>();
 6336                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6337
 6338                    Tabstop {
 6339                        is_end_tabstop,
 6340                        ranges: tabstop_ranges,
 6341                        choices: tabstop.choices.clone(),
 6342                    }
 6343                })
 6344                .collect::<Vec<_>>()
 6345        });
 6346        if let Some(tabstop) = tabstops.first() {
 6347            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6348                s.select_ranges(tabstop.ranges.iter().cloned());
 6349            });
 6350
 6351            if let Some(choices) = &tabstop.choices {
 6352                if let Some(selection) = tabstop.ranges.first() {
 6353                    self.show_snippet_choices(choices, selection.clone(), cx)
 6354                }
 6355            }
 6356
 6357            // If we're already at the last tabstop and it's at the end of the snippet,
 6358            // we're done, we don't need to keep the state around.
 6359            if !tabstop.is_end_tabstop {
 6360                let choices = tabstops
 6361                    .iter()
 6362                    .map(|tabstop| tabstop.choices.clone())
 6363                    .collect();
 6364
 6365                let ranges = tabstops
 6366                    .into_iter()
 6367                    .map(|tabstop| tabstop.ranges)
 6368                    .collect::<Vec<_>>();
 6369
 6370                self.snippet_stack.push(SnippetState {
 6371                    active_index: 0,
 6372                    ranges,
 6373                    choices,
 6374                });
 6375            }
 6376
 6377            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6378            if self.autoclose_regions.is_empty() {
 6379                let snapshot = self.buffer.read(cx).snapshot(cx);
 6380                for selection in &mut self.selections.all::<Point>(cx) {
 6381                    let selection_head = selection.head();
 6382                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6383                        continue;
 6384                    };
 6385
 6386                    let mut bracket_pair = None;
 6387                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6388                    let prev_chars = snapshot
 6389                        .reversed_chars_at(selection_head)
 6390                        .collect::<String>();
 6391                    for (pair, enabled) in scope.brackets() {
 6392                        if enabled
 6393                            && pair.close
 6394                            && prev_chars.starts_with(pair.start.as_str())
 6395                            && next_chars.starts_with(pair.end.as_str())
 6396                        {
 6397                            bracket_pair = Some(pair.clone());
 6398                            break;
 6399                        }
 6400                    }
 6401                    if let Some(pair) = bracket_pair {
 6402                        let start = snapshot.anchor_after(selection_head);
 6403                        let end = snapshot.anchor_after(selection_head);
 6404                        self.autoclose_regions.push(AutocloseRegion {
 6405                            selection_id: selection.id,
 6406                            range: start..end,
 6407                            pair,
 6408                        });
 6409                    }
 6410                }
 6411            }
 6412        }
 6413        Ok(())
 6414    }
 6415
 6416    pub fn move_to_next_snippet_tabstop(
 6417        &mut self,
 6418        window: &mut Window,
 6419        cx: &mut Context<Self>,
 6420    ) -> bool {
 6421        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6422    }
 6423
 6424    pub fn move_to_prev_snippet_tabstop(
 6425        &mut self,
 6426        window: &mut Window,
 6427        cx: &mut Context<Self>,
 6428    ) -> bool {
 6429        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6430    }
 6431
 6432    pub fn move_to_snippet_tabstop(
 6433        &mut self,
 6434        bias: Bias,
 6435        window: &mut Window,
 6436        cx: &mut Context<Self>,
 6437    ) -> bool {
 6438        if let Some(mut snippet) = self.snippet_stack.pop() {
 6439            match bias {
 6440                Bias::Left => {
 6441                    if snippet.active_index > 0 {
 6442                        snippet.active_index -= 1;
 6443                    } else {
 6444                        self.snippet_stack.push(snippet);
 6445                        return false;
 6446                    }
 6447                }
 6448                Bias::Right => {
 6449                    if snippet.active_index + 1 < snippet.ranges.len() {
 6450                        snippet.active_index += 1;
 6451                    } else {
 6452                        self.snippet_stack.push(snippet);
 6453                        return false;
 6454                    }
 6455                }
 6456            }
 6457            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6458                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6459                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6460                });
 6461
 6462                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6463                    if let Some(selection) = current_ranges.first() {
 6464                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6465                    }
 6466                }
 6467
 6468                // If snippet state is not at the last tabstop, push it back on the stack
 6469                if snippet.active_index + 1 < snippet.ranges.len() {
 6470                    self.snippet_stack.push(snippet);
 6471                }
 6472                return true;
 6473            }
 6474        }
 6475
 6476        false
 6477    }
 6478
 6479    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6480        self.transact(window, cx, |this, window, cx| {
 6481            this.select_all(&SelectAll, window, cx);
 6482            this.insert("", window, cx);
 6483        });
 6484    }
 6485
 6486    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6487        self.transact(window, cx, |this, window, cx| {
 6488            this.select_autoclose_pair(window, cx);
 6489            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6490            if !this.linked_edit_ranges.is_empty() {
 6491                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6492                let snapshot = this.buffer.read(cx).snapshot(cx);
 6493
 6494                for selection in selections.iter() {
 6495                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6496                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6497                    if selection_start.buffer_id != selection_end.buffer_id {
 6498                        continue;
 6499                    }
 6500                    if let Some(ranges) =
 6501                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6502                    {
 6503                        for (buffer, entries) in ranges {
 6504                            linked_ranges.entry(buffer).or_default().extend(entries);
 6505                        }
 6506                    }
 6507                }
 6508            }
 6509
 6510            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6511            if !this.selections.line_mode {
 6512                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6513                for selection in &mut selections {
 6514                    if selection.is_empty() {
 6515                        let old_head = selection.head();
 6516                        let mut new_head =
 6517                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6518                                .to_point(&display_map);
 6519                        if let Some((buffer, line_buffer_range)) = display_map
 6520                            .buffer_snapshot
 6521                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6522                        {
 6523                            let indent_size =
 6524                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6525                            let indent_len = match indent_size.kind {
 6526                                IndentKind::Space => {
 6527                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6528                                }
 6529                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6530                            };
 6531                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6532                                let indent_len = indent_len.get();
 6533                                new_head = cmp::min(
 6534                                    new_head,
 6535                                    MultiBufferPoint::new(
 6536                                        old_head.row,
 6537                                        ((old_head.column - 1) / indent_len) * indent_len,
 6538                                    ),
 6539                                );
 6540                            }
 6541                        }
 6542
 6543                        selection.set_head(new_head, SelectionGoal::None);
 6544                    }
 6545                }
 6546            }
 6547
 6548            this.signature_help_state.set_backspace_pressed(true);
 6549            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6550                s.select(selections)
 6551            });
 6552            this.insert("", window, cx);
 6553            let empty_str: Arc<str> = Arc::from("");
 6554            for (buffer, edits) in linked_ranges {
 6555                let snapshot = buffer.read(cx).snapshot();
 6556                use text::ToPoint as TP;
 6557
 6558                let edits = edits
 6559                    .into_iter()
 6560                    .map(|range| {
 6561                        let end_point = TP::to_point(&range.end, &snapshot);
 6562                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6563
 6564                        if end_point == start_point {
 6565                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6566                                .saturating_sub(1);
 6567                            start_point =
 6568                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6569                        };
 6570
 6571                        (start_point..end_point, empty_str.clone())
 6572                    })
 6573                    .sorted_by_key(|(range, _)| range.start)
 6574                    .collect::<Vec<_>>();
 6575                buffer.update(cx, |this, cx| {
 6576                    this.edit(edits, None, cx);
 6577                })
 6578            }
 6579            this.refresh_inline_completion(true, false, window, cx);
 6580            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6581        });
 6582    }
 6583
 6584    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6585        self.transact(window, cx, |this, window, cx| {
 6586            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6587                let line_mode = s.line_mode;
 6588                s.move_with(|map, selection| {
 6589                    if selection.is_empty() && !line_mode {
 6590                        let cursor = movement::right(map, selection.head());
 6591                        selection.end = cursor;
 6592                        selection.reversed = true;
 6593                        selection.goal = SelectionGoal::None;
 6594                    }
 6595                })
 6596            });
 6597            this.insert("", window, cx);
 6598            this.refresh_inline_completion(true, false, window, cx);
 6599        });
 6600    }
 6601
 6602    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6603        if self.move_to_prev_snippet_tabstop(window, cx) {
 6604            return;
 6605        }
 6606
 6607        self.outdent(&Outdent, window, cx);
 6608    }
 6609
 6610    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6611        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6612            return;
 6613        }
 6614
 6615        let mut selections = self.selections.all_adjusted(cx);
 6616        let buffer = self.buffer.read(cx);
 6617        let snapshot = buffer.snapshot(cx);
 6618        let rows_iter = selections.iter().map(|s| s.head().row);
 6619        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6620
 6621        let mut edits = Vec::new();
 6622        let mut prev_edited_row = 0;
 6623        let mut row_delta = 0;
 6624        for selection in &mut selections {
 6625            if selection.start.row != prev_edited_row {
 6626                row_delta = 0;
 6627            }
 6628            prev_edited_row = selection.end.row;
 6629
 6630            // If the selection is non-empty, then increase the indentation of the selected lines.
 6631            if !selection.is_empty() {
 6632                row_delta =
 6633                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6634                continue;
 6635            }
 6636
 6637            // If the selection is empty and the cursor is in the leading whitespace before the
 6638            // suggested indentation, then auto-indent the line.
 6639            let cursor = selection.head();
 6640            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6641            if let Some(suggested_indent) =
 6642                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6643            {
 6644                if cursor.column < suggested_indent.len
 6645                    && cursor.column <= current_indent.len
 6646                    && current_indent.len <= suggested_indent.len
 6647                {
 6648                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6649                    selection.end = selection.start;
 6650                    if row_delta == 0 {
 6651                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6652                            cursor.row,
 6653                            current_indent,
 6654                            suggested_indent,
 6655                        ));
 6656                        row_delta = suggested_indent.len - current_indent.len;
 6657                    }
 6658                    continue;
 6659                }
 6660            }
 6661
 6662            // Otherwise, insert a hard or soft tab.
 6663            let settings = buffer.settings_at(cursor, cx);
 6664            let tab_size = if settings.hard_tabs {
 6665                IndentSize::tab()
 6666            } else {
 6667                let tab_size = settings.tab_size.get();
 6668                let char_column = snapshot
 6669                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6670                    .flat_map(str::chars)
 6671                    .count()
 6672                    + row_delta as usize;
 6673                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6674                IndentSize::spaces(chars_to_next_tab_stop)
 6675            };
 6676            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6677            selection.end = selection.start;
 6678            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6679            row_delta += tab_size.len;
 6680        }
 6681
 6682        self.transact(window, cx, |this, window, cx| {
 6683            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6684            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6685                s.select(selections)
 6686            });
 6687            this.refresh_inline_completion(true, false, window, cx);
 6688        });
 6689    }
 6690
 6691    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6692        if self.read_only(cx) {
 6693            return;
 6694        }
 6695        let mut selections = self.selections.all::<Point>(cx);
 6696        let mut prev_edited_row = 0;
 6697        let mut row_delta = 0;
 6698        let mut edits = Vec::new();
 6699        let buffer = self.buffer.read(cx);
 6700        let snapshot = buffer.snapshot(cx);
 6701        for selection in &mut selections {
 6702            if selection.start.row != prev_edited_row {
 6703                row_delta = 0;
 6704            }
 6705            prev_edited_row = selection.end.row;
 6706
 6707            row_delta =
 6708                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6709        }
 6710
 6711        self.transact(window, cx, |this, window, cx| {
 6712            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6713            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6714                s.select(selections)
 6715            });
 6716        });
 6717    }
 6718
 6719    fn indent_selection(
 6720        buffer: &MultiBuffer,
 6721        snapshot: &MultiBufferSnapshot,
 6722        selection: &mut Selection<Point>,
 6723        edits: &mut Vec<(Range<Point>, String)>,
 6724        delta_for_start_row: u32,
 6725        cx: &App,
 6726    ) -> u32 {
 6727        let settings = buffer.settings_at(selection.start, cx);
 6728        let tab_size = settings.tab_size.get();
 6729        let indent_kind = if settings.hard_tabs {
 6730            IndentKind::Tab
 6731        } else {
 6732            IndentKind::Space
 6733        };
 6734        let mut start_row = selection.start.row;
 6735        let mut end_row = selection.end.row + 1;
 6736
 6737        // If a selection ends at the beginning of a line, don't indent
 6738        // that last line.
 6739        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6740            end_row -= 1;
 6741        }
 6742
 6743        // Avoid re-indenting a row that has already been indented by a
 6744        // previous selection, but still update this selection's column
 6745        // to reflect that indentation.
 6746        if delta_for_start_row > 0 {
 6747            start_row += 1;
 6748            selection.start.column += delta_for_start_row;
 6749            if selection.end.row == selection.start.row {
 6750                selection.end.column += delta_for_start_row;
 6751            }
 6752        }
 6753
 6754        let mut delta_for_end_row = 0;
 6755        let has_multiple_rows = start_row + 1 != end_row;
 6756        for row in start_row..end_row {
 6757            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6758            let indent_delta = match (current_indent.kind, indent_kind) {
 6759                (IndentKind::Space, IndentKind::Space) => {
 6760                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6761                    IndentSize::spaces(columns_to_next_tab_stop)
 6762                }
 6763                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6764                (_, IndentKind::Tab) => IndentSize::tab(),
 6765            };
 6766
 6767            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6768                0
 6769            } else {
 6770                selection.start.column
 6771            };
 6772            let row_start = Point::new(row, start);
 6773            edits.push((
 6774                row_start..row_start,
 6775                indent_delta.chars().collect::<String>(),
 6776            ));
 6777
 6778            // Update this selection's endpoints to reflect the indentation.
 6779            if row == selection.start.row {
 6780                selection.start.column += indent_delta.len;
 6781            }
 6782            if row == selection.end.row {
 6783                selection.end.column += indent_delta.len;
 6784                delta_for_end_row = indent_delta.len;
 6785            }
 6786        }
 6787
 6788        if selection.start.row == selection.end.row {
 6789            delta_for_start_row + delta_for_end_row
 6790        } else {
 6791            delta_for_end_row
 6792        }
 6793    }
 6794
 6795    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6796        if self.read_only(cx) {
 6797            return;
 6798        }
 6799        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6800        let selections = self.selections.all::<Point>(cx);
 6801        let mut deletion_ranges = Vec::new();
 6802        let mut last_outdent = None;
 6803        {
 6804            let buffer = self.buffer.read(cx);
 6805            let snapshot = buffer.snapshot(cx);
 6806            for selection in &selections {
 6807                let settings = buffer.settings_at(selection.start, cx);
 6808                let tab_size = settings.tab_size.get();
 6809                let mut rows = selection.spanned_rows(false, &display_map);
 6810
 6811                // Avoid re-outdenting a row that has already been outdented by a
 6812                // previous selection.
 6813                if let Some(last_row) = last_outdent {
 6814                    if last_row == rows.start {
 6815                        rows.start = rows.start.next_row();
 6816                    }
 6817                }
 6818                let has_multiple_rows = rows.len() > 1;
 6819                for row in rows.iter_rows() {
 6820                    let indent_size = snapshot.indent_size_for_line(row);
 6821                    if indent_size.len > 0 {
 6822                        let deletion_len = match indent_size.kind {
 6823                            IndentKind::Space => {
 6824                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6825                                if columns_to_prev_tab_stop == 0 {
 6826                                    tab_size
 6827                                } else {
 6828                                    columns_to_prev_tab_stop
 6829                                }
 6830                            }
 6831                            IndentKind::Tab => 1,
 6832                        };
 6833                        let start = if has_multiple_rows
 6834                            || deletion_len > selection.start.column
 6835                            || indent_size.len < selection.start.column
 6836                        {
 6837                            0
 6838                        } else {
 6839                            selection.start.column - deletion_len
 6840                        };
 6841                        deletion_ranges.push(
 6842                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6843                        );
 6844                        last_outdent = Some(row);
 6845                    }
 6846                }
 6847            }
 6848        }
 6849
 6850        self.transact(window, cx, |this, window, cx| {
 6851            this.buffer.update(cx, |buffer, cx| {
 6852                let empty_str: Arc<str> = Arc::default();
 6853                buffer.edit(
 6854                    deletion_ranges
 6855                        .into_iter()
 6856                        .map(|range| (range, empty_str.clone())),
 6857                    None,
 6858                    cx,
 6859                );
 6860            });
 6861            let selections = this.selections.all::<usize>(cx);
 6862            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6863                s.select(selections)
 6864            });
 6865        });
 6866    }
 6867
 6868    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6869        if self.read_only(cx) {
 6870            return;
 6871        }
 6872        let selections = self
 6873            .selections
 6874            .all::<usize>(cx)
 6875            .into_iter()
 6876            .map(|s| s.range());
 6877
 6878        self.transact(window, cx, |this, window, cx| {
 6879            this.buffer.update(cx, |buffer, cx| {
 6880                buffer.autoindent_ranges(selections, cx);
 6881            });
 6882            let selections = this.selections.all::<usize>(cx);
 6883            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6884                s.select(selections)
 6885            });
 6886        });
 6887    }
 6888
 6889    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6890        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6891        let selections = self.selections.all::<Point>(cx);
 6892
 6893        let mut new_cursors = Vec::new();
 6894        let mut edit_ranges = Vec::new();
 6895        let mut selections = selections.iter().peekable();
 6896        while let Some(selection) = selections.next() {
 6897            let mut rows = selection.spanned_rows(false, &display_map);
 6898            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6899
 6900            // Accumulate contiguous regions of rows that we want to delete.
 6901            while let Some(next_selection) = selections.peek() {
 6902                let next_rows = next_selection.spanned_rows(false, &display_map);
 6903                if next_rows.start <= rows.end {
 6904                    rows.end = next_rows.end;
 6905                    selections.next().unwrap();
 6906                } else {
 6907                    break;
 6908                }
 6909            }
 6910
 6911            let buffer = &display_map.buffer_snapshot;
 6912            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6913            let edit_end;
 6914            let cursor_buffer_row;
 6915            if buffer.max_point().row >= rows.end.0 {
 6916                // If there's a line after the range, delete the \n from the end of the row range
 6917                // and position the cursor on the next line.
 6918                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6919                cursor_buffer_row = rows.end;
 6920            } else {
 6921                // If there isn't a line after the range, delete the \n from the line before the
 6922                // start of the row range and position the cursor there.
 6923                edit_start = edit_start.saturating_sub(1);
 6924                edit_end = buffer.len();
 6925                cursor_buffer_row = rows.start.previous_row();
 6926            }
 6927
 6928            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6929            *cursor.column_mut() =
 6930                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6931
 6932            new_cursors.push((
 6933                selection.id,
 6934                buffer.anchor_after(cursor.to_point(&display_map)),
 6935            ));
 6936            edit_ranges.push(edit_start..edit_end);
 6937        }
 6938
 6939        self.transact(window, cx, |this, window, cx| {
 6940            let buffer = this.buffer.update(cx, |buffer, cx| {
 6941                let empty_str: Arc<str> = Arc::default();
 6942                buffer.edit(
 6943                    edit_ranges
 6944                        .into_iter()
 6945                        .map(|range| (range, empty_str.clone())),
 6946                    None,
 6947                    cx,
 6948                );
 6949                buffer.snapshot(cx)
 6950            });
 6951            let new_selections = new_cursors
 6952                .into_iter()
 6953                .map(|(id, cursor)| {
 6954                    let cursor = cursor.to_point(&buffer);
 6955                    Selection {
 6956                        id,
 6957                        start: cursor,
 6958                        end: cursor,
 6959                        reversed: false,
 6960                        goal: SelectionGoal::None,
 6961                    }
 6962                })
 6963                .collect();
 6964
 6965            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6966                s.select(new_selections);
 6967            });
 6968        });
 6969    }
 6970
 6971    pub fn join_lines_impl(
 6972        &mut self,
 6973        insert_whitespace: bool,
 6974        window: &mut Window,
 6975        cx: &mut Context<Self>,
 6976    ) {
 6977        if self.read_only(cx) {
 6978            return;
 6979        }
 6980        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6981        for selection in self.selections.all::<Point>(cx) {
 6982            let start = MultiBufferRow(selection.start.row);
 6983            // Treat single line selections as if they include the next line. Otherwise this action
 6984            // would do nothing for single line selections individual cursors.
 6985            let end = if selection.start.row == selection.end.row {
 6986                MultiBufferRow(selection.start.row + 1)
 6987            } else {
 6988                MultiBufferRow(selection.end.row)
 6989            };
 6990
 6991            if let Some(last_row_range) = row_ranges.last_mut() {
 6992                if start <= last_row_range.end {
 6993                    last_row_range.end = end;
 6994                    continue;
 6995                }
 6996            }
 6997            row_ranges.push(start..end);
 6998        }
 6999
 7000        let snapshot = self.buffer.read(cx).snapshot(cx);
 7001        let mut cursor_positions = Vec::new();
 7002        for row_range in &row_ranges {
 7003            let anchor = snapshot.anchor_before(Point::new(
 7004                row_range.end.previous_row().0,
 7005                snapshot.line_len(row_range.end.previous_row()),
 7006            ));
 7007            cursor_positions.push(anchor..anchor);
 7008        }
 7009
 7010        self.transact(window, cx, |this, window, cx| {
 7011            for row_range in row_ranges.into_iter().rev() {
 7012                for row in row_range.iter_rows().rev() {
 7013                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7014                    let next_line_row = row.next_row();
 7015                    let indent = snapshot.indent_size_for_line(next_line_row);
 7016                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7017
 7018                    let replace =
 7019                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7020                            " "
 7021                        } else {
 7022                            ""
 7023                        };
 7024
 7025                    this.buffer.update(cx, |buffer, cx| {
 7026                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7027                    });
 7028                }
 7029            }
 7030
 7031            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7032                s.select_anchor_ranges(cursor_positions)
 7033            });
 7034        });
 7035    }
 7036
 7037    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7038        self.join_lines_impl(true, window, cx);
 7039    }
 7040
 7041    pub fn sort_lines_case_sensitive(
 7042        &mut self,
 7043        _: &SortLinesCaseSensitive,
 7044        window: &mut Window,
 7045        cx: &mut Context<Self>,
 7046    ) {
 7047        self.manipulate_lines(window, cx, |lines| lines.sort())
 7048    }
 7049
 7050    pub fn sort_lines_case_insensitive(
 7051        &mut self,
 7052        _: &SortLinesCaseInsensitive,
 7053        window: &mut Window,
 7054        cx: &mut Context<Self>,
 7055    ) {
 7056        self.manipulate_lines(window, cx, |lines| {
 7057            lines.sort_by_key(|line| line.to_lowercase())
 7058        })
 7059    }
 7060
 7061    pub fn unique_lines_case_insensitive(
 7062        &mut self,
 7063        _: &UniqueLinesCaseInsensitive,
 7064        window: &mut Window,
 7065        cx: &mut Context<Self>,
 7066    ) {
 7067        self.manipulate_lines(window, cx, |lines| {
 7068            let mut seen = HashSet::default();
 7069            lines.retain(|line| seen.insert(line.to_lowercase()));
 7070        })
 7071    }
 7072
 7073    pub fn unique_lines_case_sensitive(
 7074        &mut self,
 7075        _: &UniqueLinesCaseSensitive,
 7076        window: &mut Window,
 7077        cx: &mut Context<Self>,
 7078    ) {
 7079        self.manipulate_lines(window, cx, |lines| {
 7080            let mut seen = HashSet::default();
 7081            lines.retain(|line| seen.insert(*line));
 7082        })
 7083    }
 7084
 7085    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 7086        let mut revert_changes = HashMap::default();
 7087        let snapshot = self.snapshot(window, cx);
 7088        for hunk in snapshot
 7089            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 7090        {
 7091            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7092        }
 7093        if !revert_changes.is_empty() {
 7094            self.transact(window, cx, |editor, window, cx| {
 7095                editor.revert(revert_changes, window, cx);
 7096            });
 7097        }
 7098    }
 7099
 7100    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7101        let Some(project) = self.project.clone() else {
 7102            return;
 7103        };
 7104        self.reload(project, window, cx)
 7105            .detach_and_notify_err(window, cx);
 7106    }
 7107
 7108    pub fn revert_selected_hunks(
 7109        &mut self,
 7110        _: &RevertSelectedHunks,
 7111        window: &mut Window,
 7112        cx: &mut Context<Self>,
 7113    ) {
 7114        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 7115        self.discard_hunks_in_ranges(selections, window, cx);
 7116    }
 7117
 7118    fn discard_hunks_in_ranges(
 7119        &mut self,
 7120        ranges: impl Iterator<Item = Range<Point>>,
 7121        window: &mut Window,
 7122        cx: &mut Context<Editor>,
 7123    ) {
 7124        let mut revert_changes = HashMap::default();
 7125        let snapshot = self.snapshot(window, cx);
 7126        for hunk in &snapshot.hunks_for_ranges(ranges) {
 7127            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7128        }
 7129        if !revert_changes.is_empty() {
 7130            self.transact(window, cx, |editor, window, cx| {
 7131                editor.revert(revert_changes, window, cx);
 7132            });
 7133        }
 7134    }
 7135
 7136    pub fn open_active_item_in_terminal(
 7137        &mut self,
 7138        _: &OpenInTerminal,
 7139        window: &mut Window,
 7140        cx: &mut Context<Self>,
 7141    ) {
 7142        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7143            let project_path = buffer.read(cx).project_path(cx)?;
 7144            let project = self.project.as_ref()?.read(cx);
 7145            let entry = project.entry_for_path(&project_path, cx)?;
 7146            let parent = match &entry.canonical_path {
 7147                Some(canonical_path) => canonical_path.to_path_buf(),
 7148                None => project.absolute_path(&project_path, cx)?,
 7149            }
 7150            .parent()?
 7151            .to_path_buf();
 7152            Some(parent)
 7153        }) {
 7154            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7155        }
 7156    }
 7157
 7158    pub fn prepare_revert_change(
 7159        &self,
 7160        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7161        hunk: &MultiBufferDiffHunk,
 7162        cx: &mut App,
 7163    ) -> Option<()> {
 7164        let buffer = self.buffer.read(cx);
 7165        let diff = buffer.diff_for(hunk.buffer_id)?;
 7166        let buffer = buffer.buffer(hunk.buffer_id)?;
 7167        let buffer = buffer.read(cx);
 7168        let original_text = diff
 7169            .read(cx)
 7170            .base_text()
 7171            .as_ref()?
 7172            .as_rope()
 7173            .slice(hunk.diff_base_byte_range.clone());
 7174        let buffer_snapshot = buffer.snapshot();
 7175        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7176        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7177            probe
 7178                .0
 7179                .start
 7180                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7181                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7182        }) {
 7183            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7184            Some(())
 7185        } else {
 7186            None
 7187        }
 7188    }
 7189
 7190    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7191        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7192    }
 7193
 7194    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7195        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7196    }
 7197
 7198    fn manipulate_lines<Fn>(
 7199        &mut self,
 7200        window: &mut Window,
 7201        cx: &mut Context<Self>,
 7202        mut callback: Fn,
 7203    ) where
 7204        Fn: FnMut(&mut Vec<&str>),
 7205    {
 7206        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7207        let buffer = self.buffer.read(cx).snapshot(cx);
 7208
 7209        let mut edits = Vec::new();
 7210
 7211        let selections = self.selections.all::<Point>(cx);
 7212        let mut selections = selections.iter().peekable();
 7213        let mut contiguous_row_selections = Vec::new();
 7214        let mut new_selections = Vec::new();
 7215        let mut added_lines = 0;
 7216        let mut removed_lines = 0;
 7217
 7218        while let Some(selection) = selections.next() {
 7219            let (start_row, end_row) = consume_contiguous_rows(
 7220                &mut contiguous_row_selections,
 7221                selection,
 7222                &display_map,
 7223                &mut selections,
 7224            );
 7225
 7226            let start_point = Point::new(start_row.0, 0);
 7227            let end_point = Point::new(
 7228                end_row.previous_row().0,
 7229                buffer.line_len(end_row.previous_row()),
 7230            );
 7231            let text = buffer
 7232                .text_for_range(start_point..end_point)
 7233                .collect::<String>();
 7234
 7235            let mut lines = text.split('\n').collect_vec();
 7236
 7237            let lines_before = lines.len();
 7238            callback(&mut lines);
 7239            let lines_after = lines.len();
 7240
 7241            edits.push((start_point..end_point, lines.join("\n")));
 7242
 7243            // Selections must change based on added and removed line count
 7244            let start_row =
 7245                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7246            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7247            new_selections.push(Selection {
 7248                id: selection.id,
 7249                start: start_row,
 7250                end: end_row,
 7251                goal: SelectionGoal::None,
 7252                reversed: selection.reversed,
 7253            });
 7254
 7255            if lines_after > lines_before {
 7256                added_lines += lines_after - lines_before;
 7257            } else if lines_before > lines_after {
 7258                removed_lines += lines_before - lines_after;
 7259            }
 7260        }
 7261
 7262        self.transact(window, cx, |this, window, cx| {
 7263            let buffer = this.buffer.update(cx, |buffer, cx| {
 7264                buffer.edit(edits, None, cx);
 7265                buffer.snapshot(cx)
 7266            });
 7267
 7268            // Recalculate offsets on newly edited buffer
 7269            let new_selections = new_selections
 7270                .iter()
 7271                .map(|s| {
 7272                    let start_point = Point::new(s.start.0, 0);
 7273                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7274                    Selection {
 7275                        id: s.id,
 7276                        start: buffer.point_to_offset(start_point),
 7277                        end: buffer.point_to_offset(end_point),
 7278                        goal: s.goal,
 7279                        reversed: s.reversed,
 7280                    }
 7281                })
 7282                .collect();
 7283
 7284            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7285                s.select(new_selections);
 7286            });
 7287
 7288            this.request_autoscroll(Autoscroll::fit(), cx);
 7289        });
 7290    }
 7291
 7292    pub fn convert_to_upper_case(
 7293        &mut self,
 7294        _: &ConvertToUpperCase,
 7295        window: &mut Window,
 7296        cx: &mut Context<Self>,
 7297    ) {
 7298        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7299    }
 7300
 7301    pub fn convert_to_lower_case(
 7302        &mut self,
 7303        _: &ConvertToLowerCase,
 7304        window: &mut Window,
 7305        cx: &mut Context<Self>,
 7306    ) {
 7307        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7308    }
 7309
 7310    pub fn convert_to_title_case(
 7311        &mut self,
 7312        _: &ConvertToTitleCase,
 7313        window: &mut Window,
 7314        cx: &mut Context<Self>,
 7315    ) {
 7316        self.manipulate_text(window, cx, |text| {
 7317            text.split('\n')
 7318                .map(|line| line.to_case(Case::Title))
 7319                .join("\n")
 7320        })
 7321    }
 7322
 7323    pub fn convert_to_snake_case(
 7324        &mut self,
 7325        _: &ConvertToSnakeCase,
 7326        window: &mut Window,
 7327        cx: &mut Context<Self>,
 7328    ) {
 7329        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7330    }
 7331
 7332    pub fn convert_to_kebab_case(
 7333        &mut self,
 7334        _: &ConvertToKebabCase,
 7335        window: &mut Window,
 7336        cx: &mut Context<Self>,
 7337    ) {
 7338        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7339    }
 7340
 7341    pub fn convert_to_upper_camel_case(
 7342        &mut self,
 7343        _: &ConvertToUpperCamelCase,
 7344        window: &mut Window,
 7345        cx: &mut Context<Self>,
 7346    ) {
 7347        self.manipulate_text(window, cx, |text| {
 7348            text.split('\n')
 7349                .map(|line| line.to_case(Case::UpperCamel))
 7350                .join("\n")
 7351        })
 7352    }
 7353
 7354    pub fn convert_to_lower_camel_case(
 7355        &mut self,
 7356        _: &ConvertToLowerCamelCase,
 7357        window: &mut Window,
 7358        cx: &mut Context<Self>,
 7359    ) {
 7360        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7361    }
 7362
 7363    pub fn convert_to_opposite_case(
 7364        &mut self,
 7365        _: &ConvertToOppositeCase,
 7366        window: &mut Window,
 7367        cx: &mut Context<Self>,
 7368    ) {
 7369        self.manipulate_text(window, cx, |text| {
 7370            text.chars()
 7371                .fold(String::with_capacity(text.len()), |mut t, c| {
 7372                    if c.is_uppercase() {
 7373                        t.extend(c.to_lowercase());
 7374                    } else {
 7375                        t.extend(c.to_uppercase());
 7376                    }
 7377                    t
 7378                })
 7379        })
 7380    }
 7381
 7382    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7383    where
 7384        Fn: FnMut(&str) -> String,
 7385    {
 7386        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7387        let buffer = self.buffer.read(cx).snapshot(cx);
 7388
 7389        let mut new_selections = Vec::new();
 7390        let mut edits = Vec::new();
 7391        let mut selection_adjustment = 0i32;
 7392
 7393        for selection in self.selections.all::<usize>(cx) {
 7394            let selection_is_empty = selection.is_empty();
 7395
 7396            let (start, end) = if selection_is_empty {
 7397                let word_range = movement::surrounding_word(
 7398                    &display_map,
 7399                    selection.start.to_display_point(&display_map),
 7400                );
 7401                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7402                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7403                (start, end)
 7404            } else {
 7405                (selection.start, selection.end)
 7406            };
 7407
 7408            let text = buffer.text_for_range(start..end).collect::<String>();
 7409            let old_length = text.len() as i32;
 7410            let text = callback(&text);
 7411
 7412            new_selections.push(Selection {
 7413                start: (start as i32 - selection_adjustment) as usize,
 7414                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7415                goal: SelectionGoal::None,
 7416                ..selection
 7417            });
 7418
 7419            selection_adjustment += old_length - text.len() as i32;
 7420
 7421            edits.push((start..end, text));
 7422        }
 7423
 7424        self.transact(window, cx, |this, window, cx| {
 7425            this.buffer.update(cx, |buffer, cx| {
 7426                buffer.edit(edits, None, cx);
 7427            });
 7428
 7429            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7430                s.select(new_selections);
 7431            });
 7432
 7433            this.request_autoscroll(Autoscroll::fit(), cx);
 7434        });
 7435    }
 7436
 7437    pub fn duplicate(
 7438        &mut self,
 7439        upwards: bool,
 7440        whole_lines: bool,
 7441        window: &mut Window,
 7442        cx: &mut Context<Self>,
 7443    ) {
 7444        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7445        let buffer = &display_map.buffer_snapshot;
 7446        let selections = self.selections.all::<Point>(cx);
 7447
 7448        let mut edits = Vec::new();
 7449        let mut selections_iter = selections.iter().peekable();
 7450        while let Some(selection) = selections_iter.next() {
 7451            let mut rows = selection.spanned_rows(false, &display_map);
 7452            // duplicate line-wise
 7453            if whole_lines || selection.start == selection.end {
 7454                // Avoid duplicating the same lines twice.
 7455                while let Some(next_selection) = selections_iter.peek() {
 7456                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7457                    if next_rows.start < rows.end {
 7458                        rows.end = next_rows.end;
 7459                        selections_iter.next().unwrap();
 7460                    } else {
 7461                        break;
 7462                    }
 7463                }
 7464
 7465                // Copy the text from the selected row region and splice it either at the start
 7466                // or end of the region.
 7467                let start = Point::new(rows.start.0, 0);
 7468                let end = Point::new(
 7469                    rows.end.previous_row().0,
 7470                    buffer.line_len(rows.end.previous_row()),
 7471                );
 7472                let text = buffer
 7473                    .text_for_range(start..end)
 7474                    .chain(Some("\n"))
 7475                    .collect::<String>();
 7476                let insert_location = if upwards {
 7477                    Point::new(rows.end.0, 0)
 7478                } else {
 7479                    start
 7480                };
 7481                edits.push((insert_location..insert_location, text));
 7482            } else {
 7483                // duplicate character-wise
 7484                let start = selection.start;
 7485                let end = selection.end;
 7486                let text = buffer.text_for_range(start..end).collect::<String>();
 7487                edits.push((selection.end..selection.end, text));
 7488            }
 7489        }
 7490
 7491        self.transact(window, cx, |this, _, cx| {
 7492            this.buffer.update(cx, |buffer, cx| {
 7493                buffer.edit(edits, None, cx);
 7494            });
 7495
 7496            this.request_autoscroll(Autoscroll::fit(), cx);
 7497        });
 7498    }
 7499
 7500    pub fn duplicate_line_up(
 7501        &mut self,
 7502        _: &DuplicateLineUp,
 7503        window: &mut Window,
 7504        cx: &mut Context<Self>,
 7505    ) {
 7506        self.duplicate(true, true, window, cx);
 7507    }
 7508
 7509    pub fn duplicate_line_down(
 7510        &mut self,
 7511        _: &DuplicateLineDown,
 7512        window: &mut Window,
 7513        cx: &mut Context<Self>,
 7514    ) {
 7515        self.duplicate(false, true, window, cx);
 7516    }
 7517
 7518    pub fn duplicate_selection(
 7519        &mut self,
 7520        _: &DuplicateSelection,
 7521        window: &mut Window,
 7522        cx: &mut Context<Self>,
 7523    ) {
 7524        self.duplicate(false, false, window, cx);
 7525    }
 7526
 7527    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7528        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7529        let buffer = self.buffer.read(cx).snapshot(cx);
 7530
 7531        let mut edits = Vec::new();
 7532        let mut unfold_ranges = Vec::new();
 7533        let mut refold_creases = Vec::new();
 7534
 7535        let selections = self.selections.all::<Point>(cx);
 7536        let mut selections = selections.iter().peekable();
 7537        let mut contiguous_row_selections = Vec::new();
 7538        let mut new_selections = Vec::new();
 7539
 7540        while let Some(selection) = selections.next() {
 7541            // Find all the selections that span a contiguous row range
 7542            let (start_row, end_row) = consume_contiguous_rows(
 7543                &mut contiguous_row_selections,
 7544                selection,
 7545                &display_map,
 7546                &mut selections,
 7547            );
 7548
 7549            // Move the text spanned by the row range to be before the line preceding the row range
 7550            if start_row.0 > 0 {
 7551                let range_to_move = Point::new(
 7552                    start_row.previous_row().0,
 7553                    buffer.line_len(start_row.previous_row()),
 7554                )
 7555                    ..Point::new(
 7556                        end_row.previous_row().0,
 7557                        buffer.line_len(end_row.previous_row()),
 7558                    );
 7559                let insertion_point = display_map
 7560                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7561                    .0;
 7562
 7563                // Don't move lines across excerpts
 7564                if buffer
 7565                    .excerpt_containing(insertion_point..range_to_move.end)
 7566                    .is_some()
 7567                {
 7568                    let text = buffer
 7569                        .text_for_range(range_to_move.clone())
 7570                        .flat_map(|s| s.chars())
 7571                        .skip(1)
 7572                        .chain(['\n'])
 7573                        .collect::<String>();
 7574
 7575                    edits.push((
 7576                        buffer.anchor_after(range_to_move.start)
 7577                            ..buffer.anchor_before(range_to_move.end),
 7578                        String::new(),
 7579                    ));
 7580                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7581                    edits.push((insertion_anchor..insertion_anchor, text));
 7582
 7583                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7584
 7585                    // Move selections up
 7586                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7587                        |mut selection| {
 7588                            selection.start.row -= row_delta;
 7589                            selection.end.row -= row_delta;
 7590                            selection
 7591                        },
 7592                    ));
 7593
 7594                    // Move folds up
 7595                    unfold_ranges.push(range_to_move.clone());
 7596                    for fold in display_map.folds_in_range(
 7597                        buffer.anchor_before(range_to_move.start)
 7598                            ..buffer.anchor_after(range_to_move.end),
 7599                    ) {
 7600                        let mut start = fold.range.start.to_point(&buffer);
 7601                        let mut end = fold.range.end.to_point(&buffer);
 7602                        start.row -= row_delta;
 7603                        end.row -= row_delta;
 7604                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7605                    }
 7606                }
 7607            }
 7608
 7609            // If we didn't move line(s), preserve the existing selections
 7610            new_selections.append(&mut contiguous_row_selections);
 7611        }
 7612
 7613        self.transact(window, cx, |this, window, cx| {
 7614            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7615            this.buffer.update(cx, |buffer, cx| {
 7616                for (range, text) in edits {
 7617                    buffer.edit([(range, text)], None, cx);
 7618                }
 7619            });
 7620            this.fold_creases(refold_creases, true, window, cx);
 7621            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7622                s.select(new_selections);
 7623            })
 7624        });
 7625    }
 7626
 7627    pub fn move_line_down(
 7628        &mut self,
 7629        _: &MoveLineDown,
 7630        window: &mut Window,
 7631        cx: &mut Context<Self>,
 7632    ) {
 7633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7634        let buffer = self.buffer.read(cx).snapshot(cx);
 7635
 7636        let mut edits = Vec::new();
 7637        let mut unfold_ranges = Vec::new();
 7638        let mut refold_creases = Vec::new();
 7639
 7640        let selections = self.selections.all::<Point>(cx);
 7641        let mut selections = selections.iter().peekable();
 7642        let mut contiguous_row_selections = Vec::new();
 7643        let mut new_selections = Vec::new();
 7644
 7645        while let Some(selection) = selections.next() {
 7646            // Find all the selections that span a contiguous row range
 7647            let (start_row, end_row) = consume_contiguous_rows(
 7648                &mut contiguous_row_selections,
 7649                selection,
 7650                &display_map,
 7651                &mut selections,
 7652            );
 7653
 7654            // Move the text spanned by the row range to be after the last line of the row range
 7655            if end_row.0 <= buffer.max_point().row {
 7656                let range_to_move =
 7657                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7658                let insertion_point = display_map
 7659                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7660                    .0;
 7661
 7662                // Don't move lines across excerpt boundaries
 7663                if buffer
 7664                    .excerpt_containing(range_to_move.start..insertion_point)
 7665                    .is_some()
 7666                {
 7667                    let mut text = String::from("\n");
 7668                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7669                    text.pop(); // Drop trailing newline
 7670                    edits.push((
 7671                        buffer.anchor_after(range_to_move.start)
 7672                            ..buffer.anchor_before(range_to_move.end),
 7673                        String::new(),
 7674                    ));
 7675                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7676                    edits.push((insertion_anchor..insertion_anchor, text));
 7677
 7678                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7679
 7680                    // Move selections down
 7681                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7682                        |mut selection| {
 7683                            selection.start.row += row_delta;
 7684                            selection.end.row += row_delta;
 7685                            selection
 7686                        },
 7687                    ));
 7688
 7689                    // Move folds down
 7690                    unfold_ranges.push(range_to_move.clone());
 7691                    for fold in display_map.folds_in_range(
 7692                        buffer.anchor_before(range_to_move.start)
 7693                            ..buffer.anchor_after(range_to_move.end),
 7694                    ) {
 7695                        let mut start = fold.range.start.to_point(&buffer);
 7696                        let mut end = fold.range.end.to_point(&buffer);
 7697                        start.row += row_delta;
 7698                        end.row += row_delta;
 7699                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7700                    }
 7701                }
 7702            }
 7703
 7704            // If we didn't move line(s), preserve the existing selections
 7705            new_selections.append(&mut contiguous_row_selections);
 7706        }
 7707
 7708        self.transact(window, cx, |this, window, cx| {
 7709            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7710            this.buffer.update(cx, |buffer, cx| {
 7711                for (range, text) in edits {
 7712                    buffer.edit([(range, text)], None, cx);
 7713                }
 7714            });
 7715            this.fold_creases(refold_creases, true, window, cx);
 7716            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7717                s.select(new_selections)
 7718            });
 7719        });
 7720    }
 7721
 7722    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7723        let text_layout_details = &self.text_layout_details(window);
 7724        self.transact(window, cx, |this, window, cx| {
 7725            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7726                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7727                let line_mode = s.line_mode;
 7728                s.move_with(|display_map, selection| {
 7729                    if !selection.is_empty() || line_mode {
 7730                        return;
 7731                    }
 7732
 7733                    let mut head = selection.head();
 7734                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7735                    if head.column() == display_map.line_len(head.row()) {
 7736                        transpose_offset = display_map
 7737                            .buffer_snapshot
 7738                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7739                    }
 7740
 7741                    if transpose_offset == 0 {
 7742                        return;
 7743                    }
 7744
 7745                    *head.column_mut() += 1;
 7746                    head = display_map.clip_point(head, Bias::Right);
 7747                    let goal = SelectionGoal::HorizontalPosition(
 7748                        display_map
 7749                            .x_for_display_point(head, text_layout_details)
 7750                            .into(),
 7751                    );
 7752                    selection.collapse_to(head, goal);
 7753
 7754                    let transpose_start = display_map
 7755                        .buffer_snapshot
 7756                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7757                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7758                        let transpose_end = display_map
 7759                            .buffer_snapshot
 7760                            .clip_offset(transpose_offset + 1, Bias::Right);
 7761                        if let Some(ch) =
 7762                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7763                        {
 7764                            edits.push((transpose_start..transpose_offset, String::new()));
 7765                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7766                        }
 7767                    }
 7768                });
 7769                edits
 7770            });
 7771            this.buffer
 7772                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7773            let selections = this.selections.all::<usize>(cx);
 7774            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7775                s.select(selections);
 7776            });
 7777        });
 7778    }
 7779
 7780    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7781        self.rewrap_impl(IsVimMode::No, cx)
 7782    }
 7783
 7784    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7785        let buffer = self.buffer.read(cx).snapshot(cx);
 7786        let selections = self.selections.all::<Point>(cx);
 7787        let mut selections = selections.iter().peekable();
 7788
 7789        let mut edits = Vec::new();
 7790        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7791
 7792        while let Some(selection) = selections.next() {
 7793            let mut start_row = selection.start.row;
 7794            let mut end_row = selection.end.row;
 7795
 7796            // Skip selections that overlap with a range that has already been rewrapped.
 7797            let selection_range = start_row..end_row;
 7798            if rewrapped_row_ranges
 7799                .iter()
 7800                .any(|range| range.overlaps(&selection_range))
 7801            {
 7802                continue;
 7803            }
 7804
 7805            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7806
 7807            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7808                match language_scope.language_name().as_ref() {
 7809                    "Markdown" | "Plain Text" => {
 7810                        should_rewrap = true;
 7811                    }
 7812                    _ => {}
 7813                }
 7814            }
 7815
 7816            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7817
 7818            // Since not all lines in the selection may be at the same indent
 7819            // level, choose the indent size that is the most common between all
 7820            // of the lines.
 7821            //
 7822            // If there is a tie, we use the deepest indent.
 7823            let (indent_size, indent_end) = {
 7824                let mut indent_size_occurrences = HashMap::default();
 7825                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7826
 7827                for row in start_row..=end_row {
 7828                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7829                    rows_by_indent_size.entry(indent).or_default().push(row);
 7830                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7831                }
 7832
 7833                let indent_size = indent_size_occurrences
 7834                    .into_iter()
 7835                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7836                    .map(|(indent, _)| indent)
 7837                    .unwrap_or_default();
 7838                let row = rows_by_indent_size[&indent_size][0];
 7839                let indent_end = Point::new(row, indent_size.len);
 7840
 7841                (indent_size, indent_end)
 7842            };
 7843
 7844            let mut line_prefix = indent_size.chars().collect::<String>();
 7845
 7846            if let Some(comment_prefix) =
 7847                buffer
 7848                    .language_scope_at(selection.head())
 7849                    .and_then(|language| {
 7850                        language
 7851                            .line_comment_prefixes()
 7852                            .iter()
 7853                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7854                            .cloned()
 7855                    })
 7856            {
 7857                line_prefix.push_str(&comment_prefix);
 7858                should_rewrap = true;
 7859            }
 7860
 7861            if !should_rewrap {
 7862                continue;
 7863            }
 7864
 7865            if selection.is_empty() {
 7866                'expand_upwards: while start_row > 0 {
 7867                    let prev_row = start_row - 1;
 7868                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7869                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7870                    {
 7871                        start_row = prev_row;
 7872                    } else {
 7873                        break 'expand_upwards;
 7874                    }
 7875                }
 7876
 7877                'expand_downwards: while end_row < buffer.max_point().row {
 7878                    let next_row = end_row + 1;
 7879                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7880                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7881                    {
 7882                        end_row = next_row;
 7883                    } else {
 7884                        break 'expand_downwards;
 7885                    }
 7886                }
 7887            }
 7888
 7889            let start = Point::new(start_row, 0);
 7890            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7891            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7892            let Some(lines_without_prefixes) = selection_text
 7893                .lines()
 7894                .map(|line| {
 7895                    line.strip_prefix(&line_prefix)
 7896                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7897                        .ok_or_else(|| {
 7898                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7899                        })
 7900                })
 7901                .collect::<Result<Vec<_>, _>>()
 7902                .log_err()
 7903            else {
 7904                continue;
 7905            };
 7906
 7907            let wrap_column = buffer
 7908                .settings_at(Point::new(start_row, 0), cx)
 7909                .preferred_line_length as usize;
 7910            let wrapped_text = wrap_with_prefix(
 7911                line_prefix,
 7912                lines_without_prefixes.join(" "),
 7913                wrap_column,
 7914                tab_size,
 7915            );
 7916
 7917            // TODO: should always use char-based diff while still supporting cursor behavior that
 7918            // matches vim.
 7919            let diff = match is_vim_mode {
 7920                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7921                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7922            };
 7923            let mut offset = start.to_offset(&buffer);
 7924            let mut moved_since_edit = true;
 7925
 7926            for change in diff.iter_all_changes() {
 7927                let value = change.value();
 7928                match change.tag() {
 7929                    ChangeTag::Equal => {
 7930                        offset += value.len();
 7931                        moved_since_edit = true;
 7932                    }
 7933                    ChangeTag::Delete => {
 7934                        let start = buffer.anchor_after(offset);
 7935                        let end = buffer.anchor_before(offset + value.len());
 7936
 7937                        if moved_since_edit {
 7938                            edits.push((start..end, String::new()));
 7939                        } else {
 7940                            edits.last_mut().unwrap().0.end = end;
 7941                        }
 7942
 7943                        offset += value.len();
 7944                        moved_since_edit = false;
 7945                    }
 7946                    ChangeTag::Insert => {
 7947                        if moved_since_edit {
 7948                            let anchor = buffer.anchor_after(offset);
 7949                            edits.push((anchor..anchor, value.to_string()));
 7950                        } else {
 7951                            edits.last_mut().unwrap().1.push_str(value);
 7952                        }
 7953
 7954                        moved_since_edit = false;
 7955                    }
 7956                }
 7957            }
 7958
 7959            rewrapped_row_ranges.push(start_row..=end_row);
 7960        }
 7961
 7962        self.buffer
 7963            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7964    }
 7965
 7966    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7967        let mut text = String::new();
 7968        let buffer = self.buffer.read(cx).snapshot(cx);
 7969        let mut selections = self.selections.all::<Point>(cx);
 7970        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7971        {
 7972            let max_point = buffer.max_point();
 7973            let mut is_first = true;
 7974            for selection in &mut selections {
 7975                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7976                if is_entire_line {
 7977                    selection.start = Point::new(selection.start.row, 0);
 7978                    if !selection.is_empty() && selection.end.column == 0 {
 7979                        selection.end = cmp::min(max_point, selection.end);
 7980                    } else {
 7981                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7982                    }
 7983                    selection.goal = SelectionGoal::None;
 7984                }
 7985                if is_first {
 7986                    is_first = false;
 7987                } else {
 7988                    text += "\n";
 7989                }
 7990                let mut len = 0;
 7991                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7992                    text.push_str(chunk);
 7993                    len += chunk.len();
 7994                }
 7995                clipboard_selections.push(ClipboardSelection {
 7996                    len,
 7997                    is_entire_line,
 7998                    first_line_indent: buffer
 7999                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 8000                        .len,
 8001                });
 8002            }
 8003        }
 8004
 8005        self.transact(window, cx, |this, window, cx| {
 8006            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8007                s.select(selections);
 8008            });
 8009            this.insert("", window, cx);
 8010        });
 8011        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8012    }
 8013
 8014    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8015        let item = self.cut_common(window, cx);
 8016        cx.write_to_clipboard(item);
 8017    }
 8018
 8019    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8020        self.change_selections(None, window, cx, |s| {
 8021            s.move_with(|snapshot, sel| {
 8022                if sel.is_empty() {
 8023                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8024                }
 8025            });
 8026        });
 8027        let item = self.cut_common(window, cx);
 8028        cx.set_global(KillRing(item))
 8029    }
 8030
 8031    pub fn kill_ring_yank(
 8032        &mut self,
 8033        _: &KillRingYank,
 8034        window: &mut Window,
 8035        cx: &mut Context<Self>,
 8036    ) {
 8037        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8038            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8039                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8040            } else {
 8041                return;
 8042            }
 8043        } else {
 8044            return;
 8045        };
 8046        self.do_paste(&text, metadata, false, window, cx);
 8047    }
 8048
 8049    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8050        let selections = self.selections.all::<Point>(cx);
 8051        let buffer = self.buffer.read(cx).read(cx);
 8052        let mut text = String::new();
 8053
 8054        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8055        {
 8056            let max_point = buffer.max_point();
 8057            let mut is_first = true;
 8058            for selection in selections.iter() {
 8059                let mut start = selection.start;
 8060                let mut end = selection.end;
 8061                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8062                if is_entire_line {
 8063                    start = Point::new(start.row, 0);
 8064                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8065                }
 8066                if is_first {
 8067                    is_first = false;
 8068                } else {
 8069                    text += "\n";
 8070                }
 8071                let mut len = 0;
 8072                for chunk in buffer.text_for_range(start..end) {
 8073                    text.push_str(chunk);
 8074                    len += chunk.len();
 8075                }
 8076                clipboard_selections.push(ClipboardSelection {
 8077                    len,
 8078                    is_entire_line,
 8079                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8080                });
 8081            }
 8082        }
 8083
 8084        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8085            text,
 8086            clipboard_selections,
 8087        ));
 8088    }
 8089
 8090    pub fn do_paste(
 8091        &mut self,
 8092        text: &String,
 8093        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8094        handle_entire_lines: bool,
 8095        window: &mut Window,
 8096        cx: &mut Context<Self>,
 8097    ) {
 8098        if self.read_only(cx) {
 8099            return;
 8100        }
 8101
 8102        let clipboard_text = Cow::Borrowed(text);
 8103
 8104        self.transact(window, cx, |this, window, cx| {
 8105            if let Some(mut clipboard_selections) = clipboard_selections {
 8106                let old_selections = this.selections.all::<usize>(cx);
 8107                let all_selections_were_entire_line =
 8108                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8109                let first_selection_indent_column =
 8110                    clipboard_selections.first().map(|s| s.first_line_indent);
 8111                if clipboard_selections.len() != old_selections.len() {
 8112                    clipboard_selections.drain(..);
 8113                }
 8114                let cursor_offset = this.selections.last::<usize>(cx).head();
 8115                let mut auto_indent_on_paste = true;
 8116
 8117                this.buffer.update(cx, |buffer, cx| {
 8118                    let snapshot = buffer.read(cx);
 8119                    auto_indent_on_paste =
 8120                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8121
 8122                    let mut start_offset = 0;
 8123                    let mut edits = Vec::new();
 8124                    let mut original_indent_columns = Vec::new();
 8125                    for (ix, selection) in old_selections.iter().enumerate() {
 8126                        let to_insert;
 8127                        let entire_line;
 8128                        let original_indent_column;
 8129                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8130                            let end_offset = start_offset + clipboard_selection.len;
 8131                            to_insert = &clipboard_text[start_offset..end_offset];
 8132                            entire_line = clipboard_selection.is_entire_line;
 8133                            start_offset = end_offset + 1;
 8134                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8135                        } else {
 8136                            to_insert = clipboard_text.as_str();
 8137                            entire_line = all_selections_were_entire_line;
 8138                            original_indent_column = first_selection_indent_column
 8139                        }
 8140
 8141                        // If the corresponding selection was empty when this slice of the
 8142                        // clipboard text was written, then the entire line containing the
 8143                        // selection was copied. If this selection is also currently empty,
 8144                        // then paste the line before the current line of the buffer.
 8145                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8146                            let column = selection.start.to_point(&snapshot).column as usize;
 8147                            let line_start = selection.start - column;
 8148                            line_start..line_start
 8149                        } else {
 8150                            selection.range()
 8151                        };
 8152
 8153                        edits.push((range, to_insert));
 8154                        original_indent_columns.extend(original_indent_column);
 8155                    }
 8156                    drop(snapshot);
 8157
 8158                    buffer.edit(
 8159                        edits,
 8160                        if auto_indent_on_paste {
 8161                            Some(AutoindentMode::Block {
 8162                                original_indent_columns,
 8163                            })
 8164                        } else {
 8165                            None
 8166                        },
 8167                        cx,
 8168                    );
 8169                });
 8170
 8171                let selections = this.selections.all::<usize>(cx);
 8172                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8173                    s.select(selections)
 8174                });
 8175            } else {
 8176                this.insert(&clipboard_text, window, cx);
 8177            }
 8178        });
 8179    }
 8180
 8181    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8182        if let Some(item) = cx.read_from_clipboard() {
 8183            let entries = item.entries();
 8184
 8185            match entries.first() {
 8186                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8187                // of all the pasted entries.
 8188                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8189                    .do_paste(
 8190                        clipboard_string.text(),
 8191                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8192                        true,
 8193                        window,
 8194                        cx,
 8195                    ),
 8196                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8197            }
 8198        }
 8199    }
 8200
 8201    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8202        if self.read_only(cx) {
 8203            return;
 8204        }
 8205
 8206        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8207            if let Some((selections, _)) =
 8208                self.selection_history.transaction(transaction_id).cloned()
 8209            {
 8210                self.change_selections(None, window, cx, |s| {
 8211                    s.select_anchors(selections.to_vec());
 8212                });
 8213            }
 8214            self.request_autoscroll(Autoscroll::fit(), cx);
 8215            self.unmark_text(window, cx);
 8216            self.refresh_inline_completion(true, false, window, cx);
 8217            cx.emit(EditorEvent::Edited { transaction_id });
 8218            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8219        }
 8220    }
 8221
 8222    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8223        if self.read_only(cx) {
 8224            return;
 8225        }
 8226
 8227        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8228            if let Some((_, Some(selections))) =
 8229                self.selection_history.transaction(transaction_id).cloned()
 8230            {
 8231                self.change_selections(None, window, cx, |s| {
 8232                    s.select_anchors(selections.to_vec());
 8233                });
 8234            }
 8235            self.request_autoscroll(Autoscroll::fit(), cx);
 8236            self.unmark_text(window, cx);
 8237            self.refresh_inline_completion(true, false, window, cx);
 8238            cx.emit(EditorEvent::Edited { transaction_id });
 8239        }
 8240    }
 8241
 8242    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8243        self.buffer
 8244            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8245    }
 8246
 8247    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8248        self.buffer
 8249            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8250    }
 8251
 8252    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8253        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8254            let line_mode = s.line_mode;
 8255            s.move_with(|map, selection| {
 8256                let cursor = if selection.is_empty() && !line_mode {
 8257                    movement::left(map, selection.start)
 8258                } else {
 8259                    selection.start
 8260                };
 8261                selection.collapse_to(cursor, SelectionGoal::None);
 8262            });
 8263        })
 8264    }
 8265
 8266    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8267        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8268            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8269        })
 8270    }
 8271
 8272    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8273        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8274            let line_mode = s.line_mode;
 8275            s.move_with(|map, selection| {
 8276                let cursor = if selection.is_empty() && !line_mode {
 8277                    movement::right(map, selection.end)
 8278                } else {
 8279                    selection.end
 8280                };
 8281                selection.collapse_to(cursor, SelectionGoal::None)
 8282            });
 8283        })
 8284    }
 8285
 8286    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8287        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8288            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8289        })
 8290    }
 8291
 8292    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8293        if self.take_rename(true, window, cx).is_some() {
 8294            return;
 8295        }
 8296
 8297        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8298            cx.propagate();
 8299            return;
 8300        }
 8301
 8302        let text_layout_details = &self.text_layout_details(window);
 8303        let selection_count = self.selections.count();
 8304        let first_selection = self.selections.first_anchor();
 8305
 8306        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8307            let line_mode = s.line_mode;
 8308            s.move_with(|map, selection| {
 8309                if !selection.is_empty() && !line_mode {
 8310                    selection.goal = SelectionGoal::None;
 8311                }
 8312                let (cursor, goal) = movement::up(
 8313                    map,
 8314                    selection.start,
 8315                    selection.goal,
 8316                    false,
 8317                    text_layout_details,
 8318                );
 8319                selection.collapse_to(cursor, goal);
 8320            });
 8321        });
 8322
 8323        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8324        {
 8325            cx.propagate();
 8326        }
 8327    }
 8328
 8329    pub fn move_up_by_lines(
 8330        &mut self,
 8331        action: &MoveUpByLines,
 8332        window: &mut Window,
 8333        cx: &mut Context<Self>,
 8334    ) {
 8335        if self.take_rename(true, window, cx).is_some() {
 8336            return;
 8337        }
 8338
 8339        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8340            cx.propagate();
 8341            return;
 8342        }
 8343
 8344        let text_layout_details = &self.text_layout_details(window);
 8345
 8346        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8347            let line_mode = s.line_mode;
 8348            s.move_with(|map, selection| {
 8349                if !selection.is_empty() && !line_mode {
 8350                    selection.goal = SelectionGoal::None;
 8351                }
 8352                let (cursor, goal) = movement::up_by_rows(
 8353                    map,
 8354                    selection.start,
 8355                    action.lines,
 8356                    selection.goal,
 8357                    false,
 8358                    text_layout_details,
 8359                );
 8360                selection.collapse_to(cursor, goal);
 8361            });
 8362        })
 8363    }
 8364
 8365    pub fn move_down_by_lines(
 8366        &mut self,
 8367        action: &MoveDownByLines,
 8368        window: &mut Window,
 8369        cx: &mut Context<Self>,
 8370    ) {
 8371        if self.take_rename(true, window, cx).is_some() {
 8372            return;
 8373        }
 8374
 8375        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8376            cx.propagate();
 8377            return;
 8378        }
 8379
 8380        let text_layout_details = &self.text_layout_details(window);
 8381
 8382        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8383            let line_mode = s.line_mode;
 8384            s.move_with(|map, selection| {
 8385                if !selection.is_empty() && !line_mode {
 8386                    selection.goal = SelectionGoal::None;
 8387                }
 8388                let (cursor, goal) = movement::down_by_rows(
 8389                    map,
 8390                    selection.start,
 8391                    action.lines,
 8392                    selection.goal,
 8393                    false,
 8394                    text_layout_details,
 8395                );
 8396                selection.collapse_to(cursor, goal);
 8397            });
 8398        })
 8399    }
 8400
 8401    pub fn select_down_by_lines(
 8402        &mut self,
 8403        action: &SelectDownByLines,
 8404        window: &mut Window,
 8405        cx: &mut Context<Self>,
 8406    ) {
 8407        let text_layout_details = &self.text_layout_details(window);
 8408        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8409            s.move_heads_with(|map, head, goal| {
 8410                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8411            })
 8412        })
 8413    }
 8414
 8415    pub fn select_up_by_lines(
 8416        &mut self,
 8417        action: &SelectUpByLines,
 8418        window: &mut Window,
 8419        cx: &mut Context<Self>,
 8420    ) {
 8421        let text_layout_details = &self.text_layout_details(window);
 8422        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8423            s.move_heads_with(|map, head, goal| {
 8424                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8425            })
 8426        })
 8427    }
 8428
 8429    pub fn select_page_up(
 8430        &mut self,
 8431        _: &SelectPageUp,
 8432        window: &mut Window,
 8433        cx: &mut Context<Self>,
 8434    ) {
 8435        let Some(row_count) = self.visible_row_count() else {
 8436            return;
 8437        };
 8438
 8439        let text_layout_details = &self.text_layout_details(window);
 8440
 8441        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8442            s.move_heads_with(|map, head, goal| {
 8443                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8444            })
 8445        })
 8446    }
 8447
 8448    pub fn move_page_up(
 8449        &mut self,
 8450        action: &MovePageUp,
 8451        window: &mut Window,
 8452        cx: &mut Context<Self>,
 8453    ) {
 8454        if self.take_rename(true, window, cx).is_some() {
 8455            return;
 8456        }
 8457
 8458        if self
 8459            .context_menu
 8460            .borrow_mut()
 8461            .as_mut()
 8462            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8463            .unwrap_or(false)
 8464        {
 8465            return;
 8466        }
 8467
 8468        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8469            cx.propagate();
 8470            return;
 8471        }
 8472
 8473        let Some(row_count) = self.visible_row_count() else {
 8474            return;
 8475        };
 8476
 8477        let autoscroll = if action.center_cursor {
 8478            Autoscroll::center()
 8479        } else {
 8480            Autoscroll::fit()
 8481        };
 8482
 8483        let text_layout_details = &self.text_layout_details(window);
 8484
 8485        self.change_selections(Some(autoscroll), window, cx, |s| {
 8486            let line_mode = s.line_mode;
 8487            s.move_with(|map, selection| {
 8488                if !selection.is_empty() && !line_mode {
 8489                    selection.goal = SelectionGoal::None;
 8490                }
 8491                let (cursor, goal) = movement::up_by_rows(
 8492                    map,
 8493                    selection.end,
 8494                    row_count,
 8495                    selection.goal,
 8496                    false,
 8497                    text_layout_details,
 8498                );
 8499                selection.collapse_to(cursor, goal);
 8500            });
 8501        });
 8502    }
 8503
 8504    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8505        let text_layout_details = &self.text_layout_details(window);
 8506        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8507            s.move_heads_with(|map, head, goal| {
 8508                movement::up(map, head, goal, false, text_layout_details)
 8509            })
 8510        })
 8511    }
 8512
 8513    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8514        self.take_rename(true, window, cx);
 8515
 8516        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8517            cx.propagate();
 8518            return;
 8519        }
 8520
 8521        let text_layout_details = &self.text_layout_details(window);
 8522        let selection_count = self.selections.count();
 8523        let first_selection = self.selections.first_anchor();
 8524
 8525        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8526            let line_mode = s.line_mode;
 8527            s.move_with(|map, selection| {
 8528                if !selection.is_empty() && !line_mode {
 8529                    selection.goal = SelectionGoal::None;
 8530                }
 8531                let (cursor, goal) = movement::down(
 8532                    map,
 8533                    selection.end,
 8534                    selection.goal,
 8535                    false,
 8536                    text_layout_details,
 8537                );
 8538                selection.collapse_to(cursor, goal);
 8539            });
 8540        });
 8541
 8542        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8543        {
 8544            cx.propagate();
 8545        }
 8546    }
 8547
 8548    pub fn select_page_down(
 8549        &mut self,
 8550        _: &SelectPageDown,
 8551        window: &mut Window,
 8552        cx: &mut Context<Self>,
 8553    ) {
 8554        let Some(row_count) = self.visible_row_count() else {
 8555            return;
 8556        };
 8557
 8558        let text_layout_details = &self.text_layout_details(window);
 8559
 8560        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8561            s.move_heads_with(|map, head, goal| {
 8562                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8563            })
 8564        })
 8565    }
 8566
 8567    pub fn move_page_down(
 8568        &mut self,
 8569        action: &MovePageDown,
 8570        window: &mut Window,
 8571        cx: &mut Context<Self>,
 8572    ) {
 8573        if self.take_rename(true, window, cx).is_some() {
 8574            return;
 8575        }
 8576
 8577        if self
 8578            .context_menu
 8579            .borrow_mut()
 8580            .as_mut()
 8581            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8582            .unwrap_or(false)
 8583        {
 8584            return;
 8585        }
 8586
 8587        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8588            cx.propagate();
 8589            return;
 8590        }
 8591
 8592        let Some(row_count) = self.visible_row_count() else {
 8593            return;
 8594        };
 8595
 8596        let autoscroll = if action.center_cursor {
 8597            Autoscroll::center()
 8598        } else {
 8599            Autoscroll::fit()
 8600        };
 8601
 8602        let text_layout_details = &self.text_layout_details(window);
 8603        self.change_selections(Some(autoscroll), window, cx, |s| {
 8604            let line_mode = s.line_mode;
 8605            s.move_with(|map, selection| {
 8606                if !selection.is_empty() && !line_mode {
 8607                    selection.goal = SelectionGoal::None;
 8608                }
 8609                let (cursor, goal) = movement::down_by_rows(
 8610                    map,
 8611                    selection.end,
 8612                    row_count,
 8613                    selection.goal,
 8614                    false,
 8615                    text_layout_details,
 8616                );
 8617                selection.collapse_to(cursor, goal);
 8618            });
 8619        });
 8620    }
 8621
 8622    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8623        let text_layout_details = &self.text_layout_details(window);
 8624        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8625            s.move_heads_with(|map, head, goal| {
 8626                movement::down(map, head, goal, false, text_layout_details)
 8627            })
 8628        });
 8629    }
 8630
 8631    pub fn context_menu_first(
 8632        &mut self,
 8633        _: &ContextMenuFirst,
 8634        _window: &mut Window,
 8635        cx: &mut Context<Self>,
 8636    ) {
 8637        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8638            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8639        }
 8640    }
 8641
 8642    pub fn context_menu_prev(
 8643        &mut self,
 8644        _: &ContextMenuPrev,
 8645        _window: &mut Window,
 8646        cx: &mut Context<Self>,
 8647    ) {
 8648        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8649            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8650        }
 8651    }
 8652
 8653    pub fn context_menu_next(
 8654        &mut self,
 8655        _: &ContextMenuNext,
 8656        _window: &mut Window,
 8657        cx: &mut Context<Self>,
 8658    ) {
 8659        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8660            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8661        }
 8662    }
 8663
 8664    pub fn context_menu_last(
 8665        &mut self,
 8666        _: &ContextMenuLast,
 8667        _window: &mut Window,
 8668        cx: &mut Context<Self>,
 8669    ) {
 8670        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8671            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8672        }
 8673    }
 8674
 8675    pub fn move_to_previous_word_start(
 8676        &mut self,
 8677        _: &MoveToPreviousWordStart,
 8678        window: &mut Window,
 8679        cx: &mut Context<Self>,
 8680    ) {
 8681        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8682            s.move_cursors_with(|map, head, _| {
 8683                (
 8684                    movement::previous_word_start(map, head),
 8685                    SelectionGoal::None,
 8686                )
 8687            });
 8688        })
 8689    }
 8690
 8691    pub fn move_to_previous_subword_start(
 8692        &mut self,
 8693        _: &MoveToPreviousSubwordStart,
 8694        window: &mut Window,
 8695        cx: &mut Context<Self>,
 8696    ) {
 8697        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8698            s.move_cursors_with(|map, head, _| {
 8699                (
 8700                    movement::previous_subword_start(map, head),
 8701                    SelectionGoal::None,
 8702                )
 8703            });
 8704        })
 8705    }
 8706
 8707    pub fn select_to_previous_word_start(
 8708        &mut self,
 8709        _: &SelectToPreviousWordStart,
 8710        window: &mut Window,
 8711        cx: &mut Context<Self>,
 8712    ) {
 8713        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8714            s.move_heads_with(|map, head, _| {
 8715                (
 8716                    movement::previous_word_start(map, head),
 8717                    SelectionGoal::None,
 8718                )
 8719            });
 8720        })
 8721    }
 8722
 8723    pub fn select_to_previous_subword_start(
 8724        &mut self,
 8725        _: &SelectToPreviousSubwordStart,
 8726        window: &mut Window,
 8727        cx: &mut Context<Self>,
 8728    ) {
 8729        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8730            s.move_heads_with(|map, head, _| {
 8731                (
 8732                    movement::previous_subword_start(map, head),
 8733                    SelectionGoal::None,
 8734                )
 8735            });
 8736        })
 8737    }
 8738
 8739    pub fn delete_to_previous_word_start(
 8740        &mut self,
 8741        action: &DeleteToPreviousWordStart,
 8742        window: &mut Window,
 8743        cx: &mut Context<Self>,
 8744    ) {
 8745        self.transact(window, cx, |this, window, cx| {
 8746            this.select_autoclose_pair(window, cx);
 8747            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8748                let line_mode = s.line_mode;
 8749                s.move_with(|map, selection| {
 8750                    if selection.is_empty() && !line_mode {
 8751                        let cursor = if action.ignore_newlines {
 8752                            movement::previous_word_start(map, selection.head())
 8753                        } else {
 8754                            movement::previous_word_start_or_newline(map, selection.head())
 8755                        };
 8756                        selection.set_head(cursor, SelectionGoal::None);
 8757                    }
 8758                });
 8759            });
 8760            this.insert("", window, cx);
 8761        });
 8762    }
 8763
 8764    pub fn delete_to_previous_subword_start(
 8765        &mut self,
 8766        _: &DeleteToPreviousSubwordStart,
 8767        window: &mut Window,
 8768        cx: &mut Context<Self>,
 8769    ) {
 8770        self.transact(window, cx, |this, window, cx| {
 8771            this.select_autoclose_pair(window, cx);
 8772            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8773                let line_mode = s.line_mode;
 8774                s.move_with(|map, selection| {
 8775                    if selection.is_empty() && !line_mode {
 8776                        let cursor = movement::previous_subword_start(map, selection.head());
 8777                        selection.set_head(cursor, SelectionGoal::None);
 8778                    }
 8779                });
 8780            });
 8781            this.insert("", window, cx);
 8782        });
 8783    }
 8784
 8785    pub fn move_to_next_word_end(
 8786        &mut self,
 8787        _: &MoveToNextWordEnd,
 8788        window: &mut Window,
 8789        cx: &mut Context<Self>,
 8790    ) {
 8791        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8792            s.move_cursors_with(|map, head, _| {
 8793                (movement::next_word_end(map, head), SelectionGoal::None)
 8794            });
 8795        })
 8796    }
 8797
 8798    pub fn move_to_next_subword_end(
 8799        &mut self,
 8800        _: &MoveToNextSubwordEnd,
 8801        window: &mut Window,
 8802        cx: &mut Context<Self>,
 8803    ) {
 8804        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8805            s.move_cursors_with(|map, head, _| {
 8806                (movement::next_subword_end(map, head), SelectionGoal::None)
 8807            });
 8808        })
 8809    }
 8810
 8811    pub fn select_to_next_word_end(
 8812        &mut self,
 8813        _: &SelectToNextWordEnd,
 8814        window: &mut Window,
 8815        cx: &mut Context<Self>,
 8816    ) {
 8817        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8818            s.move_heads_with(|map, head, _| {
 8819                (movement::next_word_end(map, head), SelectionGoal::None)
 8820            });
 8821        })
 8822    }
 8823
 8824    pub fn select_to_next_subword_end(
 8825        &mut self,
 8826        _: &SelectToNextSubwordEnd,
 8827        window: &mut Window,
 8828        cx: &mut Context<Self>,
 8829    ) {
 8830        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8831            s.move_heads_with(|map, head, _| {
 8832                (movement::next_subword_end(map, head), SelectionGoal::None)
 8833            });
 8834        })
 8835    }
 8836
 8837    pub fn delete_to_next_word_end(
 8838        &mut self,
 8839        action: &DeleteToNextWordEnd,
 8840        window: &mut Window,
 8841        cx: &mut Context<Self>,
 8842    ) {
 8843        self.transact(window, cx, |this, window, cx| {
 8844            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8845                let line_mode = s.line_mode;
 8846                s.move_with(|map, selection| {
 8847                    if selection.is_empty() && !line_mode {
 8848                        let cursor = if action.ignore_newlines {
 8849                            movement::next_word_end(map, selection.head())
 8850                        } else {
 8851                            movement::next_word_end_or_newline(map, selection.head())
 8852                        };
 8853                        selection.set_head(cursor, SelectionGoal::None);
 8854                    }
 8855                });
 8856            });
 8857            this.insert("", window, cx);
 8858        });
 8859    }
 8860
 8861    pub fn delete_to_next_subword_end(
 8862        &mut self,
 8863        _: &DeleteToNextSubwordEnd,
 8864        window: &mut Window,
 8865        cx: &mut Context<Self>,
 8866    ) {
 8867        self.transact(window, cx, |this, window, cx| {
 8868            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8869                s.move_with(|map, selection| {
 8870                    if selection.is_empty() {
 8871                        let cursor = movement::next_subword_end(map, selection.head());
 8872                        selection.set_head(cursor, SelectionGoal::None);
 8873                    }
 8874                });
 8875            });
 8876            this.insert("", window, cx);
 8877        });
 8878    }
 8879
 8880    pub fn move_to_beginning_of_line(
 8881        &mut self,
 8882        action: &MoveToBeginningOfLine,
 8883        window: &mut Window,
 8884        cx: &mut Context<Self>,
 8885    ) {
 8886        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8887            s.move_cursors_with(|map, head, _| {
 8888                (
 8889                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8890                    SelectionGoal::None,
 8891                )
 8892            });
 8893        })
 8894    }
 8895
 8896    pub fn select_to_beginning_of_line(
 8897        &mut self,
 8898        action: &SelectToBeginningOfLine,
 8899        window: &mut Window,
 8900        cx: &mut Context<Self>,
 8901    ) {
 8902        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8903            s.move_heads_with(|map, head, _| {
 8904                (
 8905                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8906                    SelectionGoal::None,
 8907                )
 8908            });
 8909        });
 8910    }
 8911
 8912    pub fn delete_to_beginning_of_line(
 8913        &mut self,
 8914        _: &DeleteToBeginningOfLine,
 8915        window: &mut Window,
 8916        cx: &mut Context<Self>,
 8917    ) {
 8918        self.transact(window, cx, |this, window, cx| {
 8919            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8920                s.move_with(|_, selection| {
 8921                    selection.reversed = true;
 8922                });
 8923            });
 8924
 8925            this.select_to_beginning_of_line(
 8926                &SelectToBeginningOfLine {
 8927                    stop_at_soft_wraps: false,
 8928                },
 8929                window,
 8930                cx,
 8931            );
 8932            this.backspace(&Backspace, window, cx);
 8933        });
 8934    }
 8935
 8936    pub fn move_to_end_of_line(
 8937        &mut self,
 8938        action: &MoveToEndOfLine,
 8939        window: &mut Window,
 8940        cx: &mut Context<Self>,
 8941    ) {
 8942        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8943            s.move_cursors_with(|map, head, _| {
 8944                (
 8945                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8946                    SelectionGoal::None,
 8947                )
 8948            });
 8949        })
 8950    }
 8951
 8952    pub fn select_to_end_of_line(
 8953        &mut self,
 8954        action: &SelectToEndOfLine,
 8955        window: &mut Window,
 8956        cx: &mut Context<Self>,
 8957    ) {
 8958        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8959            s.move_heads_with(|map, head, _| {
 8960                (
 8961                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8962                    SelectionGoal::None,
 8963                )
 8964            });
 8965        })
 8966    }
 8967
 8968    pub fn delete_to_end_of_line(
 8969        &mut self,
 8970        _: &DeleteToEndOfLine,
 8971        window: &mut Window,
 8972        cx: &mut Context<Self>,
 8973    ) {
 8974        self.transact(window, cx, |this, window, cx| {
 8975            this.select_to_end_of_line(
 8976                &SelectToEndOfLine {
 8977                    stop_at_soft_wraps: false,
 8978                },
 8979                window,
 8980                cx,
 8981            );
 8982            this.delete(&Delete, window, cx);
 8983        });
 8984    }
 8985
 8986    pub fn cut_to_end_of_line(
 8987        &mut self,
 8988        _: &CutToEndOfLine,
 8989        window: &mut Window,
 8990        cx: &mut Context<Self>,
 8991    ) {
 8992        self.transact(window, cx, |this, window, cx| {
 8993            this.select_to_end_of_line(
 8994                &SelectToEndOfLine {
 8995                    stop_at_soft_wraps: false,
 8996                },
 8997                window,
 8998                cx,
 8999            );
 9000            this.cut(&Cut, window, cx);
 9001        });
 9002    }
 9003
 9004    pub fn move_to_start_of_paragraph(
 9005        &mut self,
 9006        _: &MoveToStartOfParagraph,
 9007        window: &mut Window,
 9008        cx: &mut Context<Self>,
 9009    ) {
 9010        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9011            cx.propagate();
 9012            return;
 9013        }
 9014
 9015        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9016            s.move_with(|map, selection| {
 9017                selection.collapse_to(
 9018                    movement::start_of_paragraph(map, selection.head(), 1),
 9019                    SelectionGoal::None,
 9020                )
 9021            });
 9022        })
 9023    }
 9024
 9025    pub fn move_to_end_of_paragraph(
 9026        &mut self,
 9027        _: &MoveToEndOfParagraph,
 9028        window: &mut Window,
 9029        cx: &mut Context<Self>,
 9030    ) {
 9031        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9032            cx.propagate();
 9033            return;
 9034        }
 9035
 9036        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9037            s.move_with(|map, selection| {
 9038                selection.collapse_to(
 9039                    movement::end_of_paragraph(map, selection.head(), 1),
 9040                    SelectionGoal::None,
 9041                )
 9042            });
 9043        })
 9044    }
 9045
 9046    pub fn select_to_start_of_paragraph(
 9047        &mut self,
 9048        _: &SelectToStartOfParagraph,
 9049        window: &mut Window,
 9050        cx: &mut Context<Self>,
 9051    ) {
 9052        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9053            cx.propagate();
 9054            return;
 9055        }
 9056
 9057        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9058            s.move_heads_with(|map, head, _| {
 9059                (
 9060                    movement::start_of_paragraph(map, head, 1),
 9061                    SelectionGoal::None,
 9062                )
 9063            });
 9064        })
 9065    }
 9066
 9067    pub fn select_to_end_of_paragraph(
 9068        &mut self,
 9069        _: &SelectToEndOfParagraph,
 9070        window: &mut Window,
 9071        cx: &mut Context<Self>,
 9072    ) {
 9073        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9074            cx.propagate();
 9075            return;
 9076        }
 9077
 9078        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9079            s.move_heads_with(|map, head, _| {
 9080                (
 9081                    movement::end_of_paragraph(map, head, 1),
 9082                    SelectionGoal::None,
 9083                )
 9084            });
 9085        })
 9086    }
 9087
 9088    pub fn move_to_beginning(
 9089        &mut self,
 9090        _: &MoveToBeginning,
 9091        window: &mut Window,
 9092        cx: &mut Context<Self>,
 9093    ) {
 9094        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9095            cx.propagate();
 9096            return;
 9097        }
 9098
 9099        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9100            s.select_ranges(vec![0..0]);
 9101        });
 9102    }
 9103
 9104    pub fn select_to_beginning(
 9105        &mut self,
 9106        _: &SelectToBeginning,
 9107        window: &mut Window,
 9108        cx: &mut Context<Self>,
 9109    ) {
 9110        let mut selection = self.selections.last::<Point>(cx);
 9111        selection.set_head(Point::zero(), SelectionGoal::None);
 9112
 9113        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9114            s.select(vec![selection]);
 9115        });
 9116    }
 9117
 9118    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9119        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9120            cx.propagate();
 9121            return;
 9122        }
 9123
 9124        let cursor = self.buffer.read(cx).read(cx).len();
 9125        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9126            s.select_ranges(vec![cursor..cursor])
 9127        });
 9128    }
 9129
 9130    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9131        self.nav_history = nav_history;
 9132    }
 9133
 9134    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9135        self.nav_history.as_ref()
 9136    }
 9137
 9138    fn push_to_nav_history(
 9139        &mut self,
 9140        cursor_anchor: Anchor,
 9141        new_position: Option<Point>,
 9142        cx: &mut Context<Self>,
 9143    ) {
 9144        if let Some(nav_history) = self.nav_history.as_mut() {
 9145            let buffer = self.buffer.read(cx).read(cx);
 9146            let cursor_position = cursor_anchor.to_point(&buffer);
 9147            let scroll_state = self.scroll_manager.anchor();
 9148            let scroll_top_row = scroll_state.top_row(&buffer);
 9149            drop(buffer);
 9150
 9151            if let Some(new_position) = new_position {
 9152                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9153                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9154                    return;
 9155                }
 9156            }
 9157
 9158            nav_history.push(
 9159                Some(NavigationData {
 9160                    cursor_anchor,
 9161                    cursor_position,
 9162                    scroll_anchor: scroll_state,
 9163                    scroll_top_row,
 9164                }),
 9165                cx,
 9166            );
 9167        }
 9168    }
 9169
 9170    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9171        let buffer = self.buffer.read(cx).snapshot(cx);
 9172        let mut selection = self.selections.first::<usize>(cx);
 9173        selection.set_head(buffer.len(), SelectionGoal::None);
 9174        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9175            s.select(vec![selection]);
 9176        });
 9177    }
 9178
 9179    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9180        let end = self.buffer.read(cx).read(cx).len();
 9181        self.change_selections(None, window, cx, |s| {
 9182            s.select_ranges(vec![0..end]);
 9183        });
 9184    }
 9185
 9186    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9187        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9188        let mut selections = self.selections.all::<Point>(cx);
 9189        let max_point = display_map.buffer_snapshot.max_point();
 9190        for selection in &mut selections {
 9191            let rows = selection.spanned_rows(true, &display_map);
 9192            selection.start = Point::new(rows.start.0, 0);
 9193            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9194            selection.reversed = false;
 9195        }
 9196        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9197            s.select(selections);
 9198        });
 9199    }
 9200
 9201    pub fn split_selection_into_lines(
 9202        &mut self,
 9203        _: &SplitSelectionIntoLines,
 9204        window: &mut Window,
 9205        cx: &mut Context<Self>,
 9206    ) {
 9207        let selections = self
 9208            .selections
 9209            .all::<Point>(cx)
 9210            .into_iter()
 9211            .map(|selection| selection.start..selection.end)
 9212            .collect::<Vec<_>>();
 9213        self.unfold_ranges(&selections, true, true, cx);
 9214
 9215        let mut new_selection_ranges = Vec::new();
 9216        {
 9217            let buffer = self.buffer.read(cx).read(cx);
 9218            for selection in selections {
 9219                for row in selection.start.row..selection.end.row {
 9220                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9221                    new_selection_ranges.push(cursor..cursor);
 9222                }
 9223
 9224                let is_multiline_selection = selection.start.row != selection.end.row;
 9225                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9226                // so this action feels more ergonomic when paired with other selection operations
 9227                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9228                if !should_skip_last {
 9229                    new_selection_ranges.push(selection.end..selection.end);
 9230                }
 9231            }
 9232        }
 9233        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9234            s.select_ranges(new_selection_ranges);
 9235        });
 9236    }
 9237
 9238    pub fn add_selection_above(
 9239        &mut self,
 9240        _: &AddSelectionAbove,
 9241        window: &mut Window,
 9242        cx: &mut Context<Self>,
 9243    ) {
 9244        self.add_selection(true, window, cx);
 9245    }
 9246
 9247    pub fn add_selection_below(
 9248        &mut self,
 9249        _: &AddSelectionBelow,
 9250        window: &mut Window,
 9251        cx: &mut Context<Self>,
 9252    ) {
 9253        self.add_selection(false, window, cx);
 9254    }
 9255
 9256    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9257        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9258        let mut selections = self.selections.all::<Point>(cx);
 9259        let text_layout_details = self.text_layout_details(window);
 9260        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9261            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9262            let range = oldest_selection.display_range(&display_map).sorted();
 9263
 9264            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9265            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9266            let positions = start_x.min(end_x)..start_x.max(end_x);
 9267
 9268            selections.clear();
 9269            let mut stack = Vec::new();
 9270            for row in range.start.row().0..=range.end.row().0 {
 9271                if let Some(selection) = self.selections.build_columnar_selection(
 9272                    &display_map,
 9273                    DisplayRow(row),
 9274                    &positions,
 9275                    oldest_selection.reversed,
 9276                    &text_layout_details,
 9277                ) {
 9278                    stack.push(selection.id);
 9279                    selections.push(selection);
 9280                }
 9281            }
 9282
 9283            if above {
 9284                stack.reverse();
 9285            }
 9286
 9287            AddSelectionsState { above, stack }
 9288        });
 9289
 9290        let last_added_selection = *state.stack.last().unwrap();
 9291        let mut new_selections = Vec::new();
 9292        if above == state.above {
 9293            let end_row = if above {
 9294                DisplayRow(0)
 9295            } else {
 9296                display_map.max_point().row()
 9297            };
 9298
 9299            'outer: for selection in selections {
 9300                if selection.id == last_added_selection {
 9301                    let range = selection.display_range(&display_map).sorted();
 9302                    debug_assert_eq!(range.start.row(), range.end.row());
 9303                    let mut row = range.start.row();
 9304                    let positions =
 9305                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9306                            px(start)..px(end)
 9307                        } else {
 9308                            let start_x =
 9309                                display_map.x_for_display_point(range.start, &text_layout_details);
 9310                            let end_x =
 9311                                display_map.x_for_display_point(range.end, &text_layout_details);
 9312                            start_x.min(end_x)..start_x.max(end_x)
 9313                        };
 9314
 9315                    while row != end_row {
 9316                        if above {
 9317                            row.0 -= 1;
 9318                        } else {
 9319                            row.0 += 1;
 9320                        }
 9321
 9322                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9323                            &display_map,
 9324                            row,
 9325                            &positions,
 9326                            selection.reversed,
 9327                            &text_layout_details,
 9328                        ) {
 9329                            state.stack.push(new_selection.id);
 9330                            if above {
 9331                                new_selections.push(new_selection);
 9332                                new_selections.push(selection);
 9333                            } else {
 9334                                new_selections.push(selection);
 9335                                new_selections.push(new_selection);
 9336                            }
 9337
 9338                            continue 'outer;
 9339                        }
 9340                    }
 9341                }
 9342
 9343                new_selections.push(selection);
 9344            }
 9345        } else {
 9346            new_selections = selections;
 9347            new_selections.retain(|s| s.id != last_added_selection);
 9348            state.stack.pop();
 9349        }
 9350
 9351        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9352            s.select(new_selections);
 9353        });
 9354        if state.stack.len() > 1 {
 9355            self.add_selections_state = Some(state);
 9356        }
 9357    }
 9358
 9359    pub fn select_next_match_internal(
 9360        &mut self,
 9361        display_map: &DisplaySnapshot,
 9362        replace_newest: bool,
 9363        autoscroll: Option<Autoscroll>,
 9364        window: &mut Window,
 9365        cx: &mut Context<Self>,
 9366    ) -> Result<()> {
 9367        fn select_next_match_ranges(
 9368            this: &mut Editor,
 9369            range: Range<usize>,
 9370            replace_newest: bool,
 9371            auto_scroll: Option<Autoscroll>,
 9372            window: &mut Window,
 9373            cx: &mut Context<Editor>,
 9374        ) {
 9375            this.unfold_ranges(&[range.clone()], false, true, cx);
 9376            this.change_selections(auto_scroll, window, cx, |s| {
 9377                if replace_newest {
 9378                    s.delete(s.newest_anchor().id);
 9379                }
 9380                s.insert_range(range.clone());
 9381            });
 9382        }
 9383
 9384        let buffer = &display_map.buffer_snapshot;
 9385        let mut selections = self.selections.all::<usize>(cx);
 9386        if let Some(mut select_next_state) = self.select_next_state.take() {
 9387            let query = &select_next_state.query;
 9388            if !select_next_state.done {
 9389                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9390                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9391                let mut next_selected_range = None;
 9392
 9393                let bytes_after_last_selection =
 9394                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9395                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9396                let query_matches = query
 9397                    .stream_find_iter(bytes_after_last_selection)
 9398                    .map(|result| (last_selection.end, result))
 9399                    .chain(
 9400                        query
 9401                            .stream_find_iter(bytes_before_first_selection)
 9402                            .map(|result| (0, result)),
 9403                    );
 9404
 9405                for (start_offset, query_match) in query_matches {
 9406                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9407                    let offset_range =
 9408                        start_offset + query_match.start()..start_offset + query_match.end();
 9409                    let display_range = offset_range.start.to_display_point(display_map)
 9410                        ..offset_range.end.to_display_point(display_map);
 9411
 9412                    if !select_next_state.wordwise
 9413                        || (!movement::is_inside_word(display_map, display_range.start)
 9414                            && !movement::is_inside_word(display_map, display_range.end))
 9415                    {
 9416                        // TODO: This is n^2, because we might check all the selections
 9417                        if !selections
 9418                            .iter()
 9419                            .any(|selection| selection.range().overlaps(&offset_range))
 9420                        {
 9421                            next_selected_range = Some(offset_range);
 9422                            break;
 9423                        }
 9424                    }
 9425                }
 9426
 9427                if let Some(next_selected_range) = next_selected_range {
 9428                    select_next_match_ranges(
 9429                        self,
 9430                        next_selected_range,
 9431                        replace_newest,
 9432                        autoscroll,
 9433                        window,
 9434                        cx,
 9435                    );
 9436                } else {
 9437                    select_next_state.done = true;
 9438                }
 9439            }
 9440
 9441            self.select_next_state = Some(select_next_state);
 9442        } else {
 9443            let mut only_carets = true;
 9444            let mut same_text_selected = true;
 9445            let mut selected_text = None;
 9446
 9447            let mut selections_iter = selections.iter().peekable();
 9448            while let Some(selection) = selections_iter.next() {
 9449                if selection.start != selection.end {
 9450                    only_carets = false;
 9451                }
 9452
 9453                if same_text_selected {
 9454                    if selected_text.is_none() {
 9455                        selected_text =
 9456                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9457                    }
 9458
 9459                    if let Some(next_selection) = selections_iter.peek() {
 9460                        if next_selection.range().len() == selection.range().len() {
 9461                            let next_selected_text = buffer
 9462                                .text_for_range(next_selection.range())
 9463                                .collect::<String>();
 9464                            if Some(next_selected_text) != selected_text {
 9465                                same_text_selected = false;
 9466                                selected_text = None;
 9467                            }
 9468                        } else {
 9469                            same_text_selected = false;
 9470                            selected_text = None;
 9471                        }
 9472                    }
 9473                }
 9474            }
 9475
 9476            if only_carets {
 9477                for selection in &mut selections {
 9478                    let word_range = movement::surrounding_word(
 9479                        display_map,
 9480                        selection.start.to_display_point(display_map),
 9481                    );
 9482                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9483                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9484                    selection.goal = SelectionGoal::None;
 9485                    selection.reversed = false;
 9486                    select_next_match_ranges(
 9487                        self,
 9488                        selection.start..selection.end,
 9489                        replace_newest,
 9490                        autoscroll,
 9491                        window,
 9492                        cx,
 9493                    );
 9494                }
 9495
 9496                if selections.len() == 1 {
 9497                    let selection = selections
 9498                        .last()
 9499                        .expect("ensured that there's only one selection");
 9500                    let query = buffer
 9501                        .text_for_range(selection.start..selection.end)
 9502                        .collect::<String>();
 9503                    let is_empty = query.is_empty();
 9504                    let select_state = SelectNextState {
 9505                        query: AhoCorasick::new(&[query])?,
 9506                        wordwise: true,
 9507                        done: is_empty,
 9508                    };
 9509                    self.select_next_state = Some(select_state);
 9510                } else {
 9511                    self.select_next_state = None;
 9512                }
 9513            } else if let Some(selected_text) = selected_text {
 9514                self.select_next_state = Some(SelectNextState {
 9515                    query: AhoCorasick::new(&[selected_text])?,
 9516                    wordwise: false,
 9517                    done: false,
 9518                });
 9519                self.select_next_match_internal(
 9520                    display_map,
 9521                    replace_newest,
 9522                    autoscroll,
 9523                    window,
 9524                    cx,
 9525                )?;
 9526            }
 9527        }
 9528        Ok(())
 9529    }
 9530
 9531    pub fn select_all_matches(
 9532        &mut self,
 9533        _action: &SelectAllMatches,
 9534        window: &mut Window,
 9535        cx: &mut Context<Self>,
 9536    ) -> Result<()> {
 9537        self.push_to_selection_history();
 9538        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9539
 9540        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9541        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9542            return Ok(());
 9543        };
 9544        if select_next_state.done {
 9545            return Ok(());
 9546        }
 9547
 9548        let mut new_selections = self.selections.all::<usize>(cx);
 9549
 9550        let buffer = &display_map.buffer_snapshot;
 9551        let query_matches = select_next_state
 9552            .query
 9553            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9554
 9555        for query_match in query_matches {
 9556            let query_match = query_match.unwrap(); // can only fail due to I/O
 9557            let offset_range = query_match.start()..query_match.end();
 9558            let display_range = offset_range.start.to_display_point(&display_map)
 9559                ..offset_range.end.to_display_point(&display_map);
 9560
 9561            if !select_next_state.wordwise
 9562                || (!movement::is_inside_word(&display_map, display_range.start)
 9563                    && !movement::is_inside_word(&display_map, display_range.end))
 9564            {
 9565                self.selections.change_with(cx, |selections| {
 9566                    new_selections.push(Selection {
 9567                        id: selections.new_selection_id(),
 9568                        start: offset_range.start,
 9569                        end: offset_range.end,
 9570                        reversed: false,
 9571                        goal: SelectionGoal::None,
 9572                    });
 9573                });
 9574            }
 9575        }
 9576
 9577        new_selections.sort_by_key(|selection| selection.start);
 9578        let mut ix = 0;
 9579        while ix + 1 < new_selections.len() {
 9580            let current_selection = &new_selections[ix];
 9581            let next_selection = &new_selections[ix + 1];
 9582            if current_selection.range().overlaps(&next_selection.range()) {
 9583                if current_selection.id < next_selection.id {
 9584                    new_selections.remove(ix + 1);
 9585                } else {
 9586                    new_selections.remove(ix);
 9587                }
 9588            } else {
 9589                ix += 1;
 9590            }
 9591        }
 9592
 9593        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9594
 9595        for selection in new_selections.iter_mut() {
 9596            selection.reversed = reversed;
 9597        }
 9598
 9599        select_next_state.done = true;
 9600        self.unfold_ranges(
 9601            &new_selections
 9602                .iter()
 9603                .map(|selection| selection.range())
 9604                .collect::<Vec<_>>(),
 9605            false,
 9606            false,
 9607            cx,
 9608        );
 9609        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9610            selections.select(new_selections)
 9611        });
 9612
 9613        Ok(())
 9614    }
 9615
 9616    pub fn select_next(
 9617        &mut self,
 9618        action: &SelectNext,
 9619        window: &mut Window,
 9620        cx: &mut Context<Self>,
 9621    ) -> Result<()> {
 9622        self.push_to_selection_history();
 9623        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9624        self.select_next_match_internal(
 9625            &display_map,
 9626            action.replace_newest,
 9627            Some(Autoscroll::newest()),
 9628            window,
 9629            cx,
 9630        )?;
 9631        Ok(())
 9632    }
 9633
 9634    pub fn select_previous(
 9635        &mut self,
 9636        action: &SelectPrevious,
 9637        window: &mut Window,
 9638        cx: &mut Context<Self>,
 9639    ) -> Result<()> {
 9640        self.push_to_selection_history();
 9641        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9642        let buffer = &display_map.buffer_snapshot;
 9643        let mut selections = self.selections.all::<usize>(cx);
 9644        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9645            let query = &select_prev_state.query;
 9646            if !select_prev_state.done {
 9647                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9648                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9649                let mut next_selected_range = None;
 9650                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9651                let bytes_before_last_selection =
 9652                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9653                let bytes_after_first_selection =
 9654                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9655                let query_matches = query
 9656                    .stream_find_iter(bytes_before_last_selection)
 9657                    .map(|result| (last_selection.start, result))
 9658                    .chain(
 9659                        query
 9660                            .stream_find_iter(bytes_after_first_selection)
 9661                            .map(|result| (buffer.len(), result)),
 9662                    );
 9663                for (end_offset, query_match) in query_matches {
 9664                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9665                    let offset_range =
 9666                        end_offset - query_match.end()..end_offset - query_match.start();
 9667                    let display_range = offset_range.start.to_display_point(&display_map)
 9668                        ..offset_range.end.to_display_point(&display_map);
 9669
 9670                    if !select_prev_state.wordwise
 9671                        || (!movement::is_inside_word(&display_map, display_range.start)
 9672                            && !movement::is_inside_word(&display_map, display_range.end))
 9673                    {
 9674                        next_selected_range = Some(offset_range);
 9675                        break;
 9676                    }
 9677                }
 9678
 9679                if let Some(next_selected_range) = next_selected_range {
 9680                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9681                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9682                        if action.replace_newest {
 9683                            s.delete(s.newest_anchor().id);
 9684                        }
 9685                        s.insert_range(next_selected_range);
 9686                    });
 9687                } else {
 9688                    select_prev_state.done = true;
 9689                }
 9690            }
 9691
 9692            self.select_prev_state = Some(select_prev_state);
 9693        } else {
 9694            let mut only_carets = true;
 9695            let mut same_text_selected = true;
 9696            let mut selected_text = None;
 9697
 9698            let mut selections_iter = selections.iter().peekable();
 9699            while let Some(selection) = selections_iter.next() {
 9700                if selection.start != selection.end {
 9701                    only_carets = false;
 9702                }
 9703
 9704                if same_text_selected {
 9705                    if selected_text.is_none() {
 9706                        selected_text =
 9707                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9708                    }
 9709
 9710                    if let Some(next_selection) = selections_iter.peek() {
 9711                        if next_selection.range().len() == selection.range().len() {
 9712                            let next_selected_text = buffer
 9713                                .text_for_range(next_selection.range())
 9714                                .collect::<String>();
 9715                            if Some(next_selected_text) != selected_text {
 9716                                same_text_selected = false;
 9717                                selected_text = None;
 9718                            }
 9719                        } else {
 9720                            same_text_selected = false;
 9721                            selected_text = None;
 9722                        }
 9723                    }
 9724                }
 9725            }
 9726
 9727            if only_carets {
 9728                for selection in &mut selections {
 9729                    let word_range = movement::surrounding_word(
 9730                        &display_map,
 9731                        selection.start.to_display_point(&display_map),
 9732                    );
 9733                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9734                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9735                    selection.goal = SelectionGoal::None;
 9736                    selection.reversed = false;
 9737                }
 9738                if selections.len() == 1 {
 9739                    let selection = selections
 9740                        .last()
 9741                        .expect("ensured that there's only one selection");
 9742                    let query = buffer
 9743                        .text_for_range(selection.start..selection.end)
 9744                        .collect::<String>();
 9745                    let is_empty = query.is_empty();
 9746                    let select_state = SelectNextState {
 9747                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9748                        wordwise: true,
 9749                        done: is_empty,
 9750                    };
 9751                    self.select_prev_state = Some(select_state);
 9752                } else {
 9753                    self.select_prev_state = None;
 9754                }
 9755
 9756                self.unfold_ranges(
 9757                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9758                    false,
 9759                    true,
 9760                    cx,
 9761                );
 9762                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9763                    s.select(selections);
 9764                });
 9765            } else if let Some(selected_text) = selected_text {
 9766                self.select_prev_state = Some(SelectNextState {
 9767                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9768                    wordwise: false,
 9769                    done: false,
 9770                });
 9771                self.select_previous(action, window, cx)?;
 9772            }
 9773        }
 9774        Ok(())
 9775    }
 9776
 9777    pub fn toggle_comments(
 9778        &mut self,
 9779        action: &ToggleComments,
 9780        window: &mut Window,
 9781        cx: &mut Context<Self>,
 9782    ) {
 9783        if self.read_only(cx) {
 9784            return;
 9785        }
 9786        let text_layout_details = &self.text_layout_details(window);
 9787        self.transact(window, cx, |this, window, cx| {
 9788            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9789            let mut edits = Vec::new();
 9790            let mut selection_edit_ranges = Vec::new();
 9791            let mut last_toggled_row = None;
 9792            let snapshot = this.buffer.read(cx).read(cx);
 9793            let empty_str: Arc<str> = Arc::default();
 9794            let mut suffixes_inserted = Vec::new();
 9795            let ignore_indent = action.ignore_indent;
 9796
 9797            fn comment_prefix_range(
 9798                snapshot: &MultiBufferSnapshot,
 9799                row: MultiBufferRow,
 9800                comment_prefix: &str,
 9801                comment_prefix_whitespace: &str,
 9802                ignore_indent: bool,
 9803            ) -> Range<Point> {
 9804                let indent_size = if ignore_indent {
 9805                    0
 9806                } else {
 9807                    snapshot.indent_size_for_line(row).len
 9808                };
 9809
 9810                let start = Point::new(row.0, indent_size);
 9811
 9812                let mut line_bytes = snapshot
 9813                    .bytes_in_range(start..snapshot.max_point())
 9814                    .flatten()
 9815                    .copied();
 9816
 9817                // If this line currently begins with the line comment prefix, then record
 9818                // the range containing the prefix.
 9819                if line_bytes
 9820                    .by_ref()
 9821                    .take(comment_prefix.len())
 9822                    .eq(comment_prefix.bytes())
 9823                {
 9824                    // Include any whitespace that matches the comment prefix.
 9825                    let matching_whitespace_len = line_bytes
 9826                        .zip(comment_prefix_whitespace.bytes())
 9827                        .take_while(|(a, b)| a == b)
 9828                        .count() as u32;
 9829                    let end = Point::new(
 9830                        start.row,
 9831                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9832                    );
 9833                    start..end
 9834                } else {
 9835                    start..start
 9836                }
 9837            }
 9838
 9839            fn comment_suffix_range(
 9840                snapshot: &MultiBufferSnapshot,
 9841                row: MultiBufferRow,
 9842                comment_suffix: &str,
 9843                comment_suffix_has_leading_space: bool,
 9844            ) -> Range<Point> {
 9845                let end = Point::new(row.0, snapshot.line_len(row));
 9846                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9847
 9848                let mut line_end_bytes = snapshot
 9849                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9850                    .flatten()
 9851                    .copied();
 9852
 9853                let leading_space_len = if suffix_start_column > 0
 9854                    && line_end_bytes.next() == Some(b' ')
 9855                    && comment_suffix_has_leading_space
 9856                {
 9857                    1
 9858                } else {
 9859                    0
 9860                };
 9861
 9862                // If this line currently begins with the line comment prefix, then record
 9863                // the range containing the prefix.
 9864                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9865                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9866                    start..end
 9867                } else {
 9868                    end..end
 9869                }
 9870            }
 9871
 9872            // TODO: Handle selections that cross excerpts
 9873            for selection in &mut selections {
 9874                let start_column = snapshot
 9875                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9876                    .len;
 9877                let language = if let Some(language) =
 9878                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9879                {
 9880                    language
 9881                } else {
 9882                    continue;
 9883                };
 9884
 9885                selection_edit_ranges.clear();
 9886
 9887                // If multiple selections contain a given row, avoid processing that
 9888                // row more than once.
 9889                let mut start_row = MultiBufferRow(selection.start.row);
 9890                if last_toggled_row == Some(start_row) {
 9891                    start_row = start_row.next_row();
 9892                }
 9893                let end_row =
 9894                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9895                        MultiBufferRow(selection.end.row - 1)
 9896                    } else {
 9897                        MultiBufferRow(selection.end.row)
 9898                    };
 9899                last_toggled_row = Some(end_row);
 9900
 9901                if start_row > end_row {
 9902                    continue;
 9903                }
 9904
 9905                // If the language has line comments, toggle those.
 9906                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9907
 9908                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9909                if ignore_indent {
 9910                    full_comment_prefixes = full_comment_prefixes
 9911                        .into_iter()
 9912                        .map(|s| Arc::from(s.trim_end()))
 9913                        .collect();
 9914                }
 9915
 9916                if !full_comment_prefixes.is_empty() {
 9917                    let first_prefix = full_comment_prefixes
 9918                        .first()
 9919                        .expect("prefixes is non-empty");
 9920                    let prefix_trimmed_lengths = full_comment_prefixes
 9921                        .iter()
 9922                        .map(|p| p.trim_end_matches(' ').len())
 9923                        .collect::<SmallVec<[usize; 4]>>();
 9924
 9925                    let mut all_selection_lines_are_comments = true;
 9926
 9927                    for row in start_row.0..=end_row.0 {
 9928                        let row = MultiBufferRow(row);
 9929                        if start_row < end_row && snapshot.is_line_blank(row) {
 9930                            continue;
 9931                        }
 9932
 9933                        let prefix_range = full_comment_prefixes
 9934                            .iter()
 9935                            .zip(prefix_trimmed_lengths.iter().copied())
 9936                            .map(|(prefix, trimmed_prefix_len)| {
 9937                                comment_prefix_range(
 9938                                    snapshot.deref(),
 9939                                    row,
 9940                                    &prefix[..trimmed_prefix_len],
 9941                                    &prefix[trimmed_prefix_len..],
 9942                                    ignore_indent,
 9943                                )
 9944                            })
 9945                            .max_by_key(|range| range.end.column - range.start.column)
 9946                            .expect("prefixes is non-empty");
 9947
 9948                        if prefix_range.is_empty() {
 9949                            all_selection_lines_are_comments = false;
 9950                        }
 9951
 9952                        selection_edit_ranges.push(prefix_range);
 9953                    }
 9954
 9955                    if all_selection_lines_are_comments {
 9956                        edits.extend(
 9957                            selection_edit_ranges
 9958                                .iter()
 9959                                .cloned()
 9960                                .map(|range| (range, empty_str.clone())),
 9961                        );
 9962                    } else {
 9963                        let min_column = selection_edit_ranges
 9964                            .iter()
 9965                            .map(|range| range.start.column)
 9966                            .min()
 9967                            .unwrap_or(0);
 9968                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9969                            let position = Point::new(range.start.row, min_column);
 9970                            (position..position, first_prefix.clone())
 9971                        }));
 9972                    }
 9973                } else if let Some((full_comment_prefix, comment_suffix)) =
 9974                    language.block_comment_delimiters()
 9975                {
 9976                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9977                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9978                    let prefix_range = comment_prefix_range(
 9979                        snapshot.deref(),
 9980                        start_row,
 9981                        comment_prefix,
 9982                        comment_prefix_whitespace,
 9983                        ignore_indent,
 9984                    );
 9985                    let suffix_range = comment_suffix_range(
 9986                        snapshot.deref(),
 9987                        end_row,
 9988                        comment_suffix.trim_start_matches(' '),
 9989                        comment_suffix.starts_with(' '),
 9990                    );
 9991
 9992                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9993                        edits.push((
 9994                            prefix_range.start..prefix_range.start,
 9995                            full_comment_prefix.clone(),
 9996                        ));
 9997                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9998                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9999                    } else {
10000                        edits.push((prefix_range, empty_str.clone()));
10001                        edits.push((suffix_range, empty_str.clone()));
10002                    }
10003                } else {
10004                    continue;
10005                }
10006            }
10007
10008            drop(snapshot);
10009            this.buffer.update(cx, |buffer, cx| {
10010                buffer.edit(edits, None, cx);
10011            });
10012
10013            // Adjust selections so that they end before any comment suffixes that
10014            // were inserted.
10015            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10016            let mut selections = this.selections.all::<Point>(cx);
10017            let snapshot = this.buffer.read(cx).read(cx);
10018            for selection in &mut selections {
10019                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10020                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10021                        Ordering::Less => {
10022                            suffixes_inserted.next();
10023                            continue;
10024                        }
10025                        Ordering::Greater => break,
10026                        Ordering::Equal => {
10027                            if selection.end.column == snapshot.line_len(row) {
10028                                if selection.is_empty() {
10029                                    selection.start.column -= suffix_len as u32;
10030                                }
10031                                selection.end.column -= suffix_len as u32;
10032                            }
10033                            break;
10034                        }
10035                    }
10036                }
10037            }
10038
10039            drop(snapshot);
10040            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10041                s.select(selections)
10042            });
10043
10044            let selections = this.selections.all::<Point>(cx);
10045            let selections_on_single_row = selections.windows(2).all(|selections| {
10046                selections[0].start.row == selections[1].start.row
10047                    && selections[0].end.row == selections[1].end.row
10048                    && selections[0].start.row == selections[0].end.row
10049            });
10050            let selections_selecting = selections
10051                .iter()
10052                .any(|selection| selection.start != selection.end);
10053            let advance_downwards = action.advance_downwards
10054                && selections_on_single_row
10055                && !selections_selecting
10056                && !matches!(this.mode, EditorMode::SingleLine { .. });
10057
10058            if advance_downwards {
10059                let snapshot = this.buffer.read(cx).snapshot(cx);
10060
10061                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10062                    s.move_cursors_with(|display_snapshot, display_point, _| {
10063                        let mut point = display_point.to_point(display_snapshot);
10064                        point.row += 1;
10065                        point = snapshot.clip_point(point, Bias::Left);
10066                        let display_point = point.to_display_point(display_snapshot);
10067                        let goal = SelectionGoal::HorizontalPosition(
10068                            display_snapshot
10069                                .x_for_display_point(display_point, text_layout_details)
10070                                .into(),
10071                        );
10072                        (display_point, goal)
10073                    })
10074                });
10075            }
10076        });
10077    }
10078
10079    pub fn select_enclosing_symbol(
10080        &mut self,
10081        _: &SelectEnclosingSymbol,
10082        window: &mut Window,
10083        cx: &mut Context<Self>,
10084    ) {
10085        let buffer = self.buffer.read(cx).snapshot(cx);
10086        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10087
10088        fn update_selection(
10089            selection: &Selection<usize>,
10090            buffer_snap: &MultiBufferSnapshot,
10091        ) -> Option<Selection<usize>> {
10092            let cursor = selection.head();
10093            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10094            for symbol in symbols.iter().rev() {
10095                let start = symbol.range.start.to_offset(buffer_snap);
10096                let end = symbol.range.end.to_offset(buffer_snap);
10097                let new_range = start..end;
10098                if start < selection.start || end > selection.end {
10099                    return Some(Selection {
10100                        id: selection.id,
10101                        start: new_range.start,
10102                        end: new_range.end,
10103                        goal: SelectionGoal::None,
10104                        reversed: selection.reversed,
10105                    });
10106                }
10107            }
10108            None
10109        }
10110
10111        let mut selected_larger_symbol = false;
10112        let new_selections = old_selections
10113            .iter()
10114            .map(|selection| match update_selection(selection, &buffer) {
10115                Some(new_selection) => {
10116                    if new_selection.range() != selection.range() {
10117                        selected_larger_symbol = true;
10118                    }
10119                    new_selection
10120                }
10121                None => selection.clone(),
10122            })
10123            .collect::<Vec<_>>();
10124
10125        if selected_larger_symbol {
10126            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10127                s.select(new_selections);
10128            });
10129        }
10130    }
10131
10132    pub fn select_larger_syntax_node(
10133        &mut self,
10134        _: &SelectLargerSyntaxNode,
10135        window: &mut Window,
10136        cx: &mut Context<Self>,
10137    ) {
10138        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10139        let buffer = self.buffer.read(cx).snapshot(cx);
10140        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10141
10142        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10143        let mut selected_larger_node = false;
10144        let new_selections = old_selections
10145            .iter()
10146            .map(|selection| {
10147                let old_range = selection.start..selection.end;
10148                let mut new_range = old_range.clone();
10149                let mut new_node = None;
10150                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10151                {
10152                    new_node = Some(node);
10153                    new_range = containing_range;
10154                    if !display_map.intersects_fold(new_range.start)
10155                        && !display_map.intersects_fold(new_range.end)
10156                    {
10157                        break;
10158                    }
10159                }
10160
10161                if let Some(node) = new_node {
10162                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10163                    // nodes. Parent and grandparent are also logged because this operation will not
10164                    // visit nodes that have the same range as their parent.
10165                    log::info!("Node: {node:?}");
10166                    let parent = node.parent();
10167                    log::info!("Parent: {parent:?}");
10168                    let grandparent = parent.and_then(|x| x.parent());
10169                    log::info!("Grandparent: {grandparent:?}");
10170                }
10171
10172                selected_larger_node |= new_range != old_range;
10173                Selection {
10174                    id: selection.id,
10175                    start: new_range.start,
10176                    end: new_range.end,
10177                    goal: SelectionGoal::None,
10178                    reversed: selection.reversed,
10179                }
10180            })
10181            .collect::<Vec<_>>();
10182
10183        if selected_larger_node {
10184            stack.push(old_selections);
10185            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10186                s.select(new_selections);
10187            });
10188        }
10189        self.select_larger_syntax_node_stack = stack;
10190    }
10191
10192    pub fn select_smaller_syntax_node(
10193        &mut self,
10194        _: &SelectSmallerSyntaxNode,
10195        window: &mut Window,
10196        cx: &mut Context<Self>,
10197    ) {
10198        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10199        if let Some(selections) = stack.pop() {
10200            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10201                s.select(selections.to_vec());
10202            });
10203        }
10204        self.select_larger_syntax_node_stack = stack;
10205    }
10206
10207    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10208        if !EditorSettings::get_global(cx).gutter.runnables {
10209            self.clear_tasks();
10210            return Task::ready(());
10211        }
10212        let project = self.project.as_ref().map(Entity::downgrade);
10213        cx.spawn_in(window, |this, mut cx| async move {
10214            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10215            let Some(project) = project.and_then(|p| p.upgrade()) else {
10216                return;
10217            };
10218            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10219                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10220            }) else {
10221                return;
10222            };
10223
10224            let hide_runnables = project
10225                .update(&mut cx, |project, cx| {
10226                    // Do not display any test indicators in non-dev server remote projects.
10227                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10228                })
10229                .unwrap_or(true);
10230            if hide_runnables {
10231                return;
10232            }
10233            let new_rows =
10234                cx.background_spawn({
10235                    let snapshot = display_snapshot.clone();
10236                    async move {
10237                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10238                    }
10239                })
10240                    .await;
10241
10242            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10243            this.update(&mut cx, |this, _| {
10244                this.clear_tasks();
10245                for (key, value) in rows {
10246                    this.insert_tasks(key, value);
10247                }
10248            })
10249            .ok();
10250        })
10251    }
10252    fn fetch_runnable_ranges(
10253        snapshot: &DisplaySnapshot,
10254        range: Range<Anchor>,
10255    ) -> Vec<language::RunnableRange> {
10256        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10257    }
10258
10259    fn runnable_rows(
10260        project: Entity<Project>,
10261        snapshot: DisplaySnapshot,
10262        runnable_ranges: Vec<RunnableRange>,
10263        mut cx: AsyncWindowContext,
10264    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10265        runnable_ranges
10266            .into_iter()
10267            .filter_map(|mut runnable| {
10268                let tasks = cx
10269                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10270                    .ok()?;
10271                if tasks.is_empty() {
10272                    return None;
10273                }
10274
10275                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10276
10277                let row = snapshot
10278                    .buffer_snapshot
10279                    .buffer_line_for_row(MultiBufferRow(point.row))?
10280                    .1
10281                    .start
10282                    .row;
10283
10284                let context_range =
10285                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10286                Some((
10287                    (runnable.buffer_id, row),
10288                    RunnableTasks {
10289                        templates: tasks,
10290                        offset: MultiBufferOffset(runnable.run_range.start),
10291                        context_range,
10292                        column: point.column,
10293                        extra_variables: runnable.extra_captures,
10294                    },
10295                ))
10296            })
10297            .collect()
10298    }
10299
10300    fn templates_with_tags(
10301        project: &Entity<Project>,
10302        runnable: &mut Runnable,
10303        cx: &mut App,
10304    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10305        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10306            let (worktree_id, file) = project
10307                .buffer_for_id(runnable.buffer, cx)
10308                .and_then(|buffer| buffer.read(cx).file())
10309                .map(|file| (file.worktree_id(cx), file.clone()))
10310                .unzip();
10311
10312            (
10313                project.task_store().read(cx).task_inventory().cloned(),
10314                worktree_id,
10315                file,
10316            )
10317        });
10318
10319        let tags = mem::take(&mut runnable.tags);
10320        let mut tags: Vec<_> = tags
10321            .into_iter()
10322            .flat_map(|tag| {
10323                let tag = tag.0.clone();
10324                inventory
10325                    .as_ref()
10326                    .into_iter()
10327                    .flat_map(|inventory| {
10328                        inventory.read(cx).list_tasks(
10329                            file.clone(),
10330                            Some(runnable.language.clone()),
10331                            worktree_id,
10332                            cx,
10333                        )
10334                    })
10335                    .filter(move |(_, template)| {
10336                        template.tags.iter().any(|source_tag| source_tag == &tag)
10337                    })
10338            })
10339            .sorted_by_key(|(kind, _)| kind.to_owned())
10340            .collect();
10341        if let Some((leading_tag_source, _)) = tags.first() {
10342            // Strongest source wins; if we have worktree tag binding, prefer that to
10343            // global and language bindings;
10344            // if we have a global binding, prefer that to language binding.
10345            let first_mismatch = tags
10346                .iter()
10347                .position(|(tag_source, _)| tag_source != leading_tag_source);
10348            if let Some(index) = first_mismatch {
10349                tags.truncate(index);
10350            }
10351        }
10352
10353        tags
10354    }
10355
10356    pub fn move_to_enclosing_bracket(
10357        &mut self,
10358        _: &MoveToEnclosingBracket,
10359        window: &mut Window,
10360        cx: &mut Context<Self>,
10361    ) {
10362        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10363            s.move_offsets_with(|snapshot, selection| {
10364                let Some(enclosing_bracket_ranges) =
10365                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10366                else {
10367                    return;
10368                };
10369
10370                let mut best_length = usize::MAX;
10371                let mut best_inside = false;
10372                let mut best_in_bracket_range = false;
10373                let mut best_destination = None;
10374                for (open, close) in enclosing_bracket_ranges {
10375                    let close = close.to_inclusive();
10376                    let length = close.end() - open.start;
10377                    let inside = selection.start >= open.end && selection.end <= *close.start();
10378                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10379                        || close.contains(&selection.head());
10380
10381                    // If best is next to a bracket and current isn't, skip
10382                    if !in_bracket_range && best_in_bracket_range {
10383                        continue;
10384                    }
10385
10386                    // Prefer smaller lengths unless best is inside and current isn't
10387                    if length > best_length && (best_inside || !inside) {
10388                        continue;
10389                    }
10390
10391                    best_length = length;
10392                    best_inside = inside;
10393                    best_in_bracket_range = in_bracket_range;
10394                    best_destination = Some(
10395                        if close.contains(&selection.start) && close.contains(&selection.end) {
10396                            if inside {
10397                                open.end
10398                            } else {
10399                                open.start
10400                            }
10401                        } else if inside {
10402                            *close.start()
10403                        } else {
10404                            *close.end()
10405                        },
10406                    );
10407                }
10408
10409                if let Some(destination) = best_destination {
10410                    selection.collapse_to(destination, SelectionGoal::None);
10411                }
10412            })
10413        });
10414    }
10415
10416    pub fn undo_selection(
10417        &mut self,
10418        _: &UndoSelection,
10419        window: &mut Window,
10420        cx: &mut Context<Self>,
10421    ) {
10422        self.end_selection(window, cx);
10423        self.selection_history.mode = SelectionHistoryMode::Undoing;
10424        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10425            self.change_selections(None, window, cx, |s| {
10426                s.select_anchors(entry.selections.to_vec())
10427            });
10428            self.select_next_state = entry.select_next_state;
10429            self.select_prev_state = entry.select_prev_state;
10430            self.add_selections_state = entry.add_selections_state;
10431            self.request_autoscroll(Autoscroll::newest(), cx);
10432        }
10433        self.selection_history.mode = SelectionHistoryMode::Normal;
10434    }
10435
10436    pub fn redo_selection(
10437        &mut self,
10438        _: &RedoSelection,
10439        window: &mut Window,
10440        cx: &mut Context<Self>,
10441    ) {
10442        self.end_selection(window, cx);
10443        self.selection_history.mode = SelectionHistoryMode::Redoing;
10444        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10445            self.change_selections(None, window, cx, |s| {
10446                s.select_anchors(entry.selections.to_vec())
10447            });
10448            self.select_next_state = entry.select_next_state;
10449            self.select_prev_state = entry.select_prev_state;
10450            self.add_selections_state = entry.add_selections_state;
10451            self.request_autoscroll(Autoscroll::newest(), cx);
10452        }
10453        self.selection_history.mode = SelectionHistoryMode::Normal;
10454    }
10455
10456    pub fn expand_excerpts(
10457        &mut self,
10458        action: &ExpandExcerpts,
10459        _: &mut Window,
10460        cx: &mut Context<Self>,
10461    ) {
10462        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10463    }
10464
10465    pub fn expand_excerpts_down(
10466        &mut self,
10467        action: &ExpandExcerptsDown,
10468        _: &mut Window,
10469        cx: &mut Context<Self>,
10470    ) {
10471        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10472    }
10473
10474    pub fn expand_excerpts_up(
10475        &mut self,
10476        action: &ExpandExcerptsUp,
10477        _: &mut Window,
10478        cx: &mut Context<Self>,
10479    ) {
10480        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10481    }
10482
10483    pub fn expand_excerpts_for_direction(
10484        &mut self,
10485        lines: u32,
10486        direction: ExpandExcerptDirection,
10487
10488        cx: &mut Context<Self>,
10489    ) {
10490        let selections = self.selections.disjoint_anchors();
10491
10492        let lines = if lines == 0 {
10493            EditorSettings::get_global(cx).expand_excerpt_lines
10494        } else {
10495            lines
10496        };
10497
10498        self.buffer.update(cx, |buffer, cx| {
10499            let snapshot = buffer.snapshot(cx);
10500            let mut excerpt_ids = selections
10501                .iter()
10502                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10503                .collect::<Vec<_>>();
10504            excerpt_ids.sort();
10505            excerpt_ids.dedup();
10506            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10507        })
10508    }
10509
10510    pub fn expand_excerpt(
10511        &mut self,
10512        excerpt: ExcerptId,
10513        direction: ExpandExcerptDirection,
10514        cx: &mut Context<Self>,
10515    ) {
10516        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10517        self.buffer.update(cx, |buffer, cx| {
10518            buffer.expand_excerpts([excerpt], lines, direction, cx)
10519        })
10520    }
10521
10522    pub fn go_to_singleton_buffer_point(
10523        &mut self,
10524        point: Point,
10525        window: &mut Window,
10526        cx: &mut Context<Self>,
10527    ) {
10528        self.go_to_singleton_buffer_range(point..point, window, cx);
10529    }
10530
10531    pub fn go_to_singleton_buffer_range(
10532        &mut self,
10533        range: Range<Point>,
10534        window: &mut Window,
10535        cx: &mut Context<Self>,
10536    ) {
10537        let multibuffer = self.buffer().read(cx);
10538        let Some(buffer) = multibuffer.as_singleton() else {
10539            return;
10540        };
10541        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10542            return;
10543        };
10544        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10545            return;
10546        };
10547        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10548            s.select_anchor_ranges([start..end])
10549        });
10550    }
10551
10552    fn go_to_diagnostic(
10553        &mut self,
10554        _: &GoToDiagnostic,
10555        window: &mut Window,
10556        cx: &mut Context<Self>,
10557    ) {
10558        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10559    }
10560
10561    fn go_to_prev_diagnostic(
10562        &mut self,
10563        _: &GoToPrevDiagnostic,
10564        window: &mut Window,
10565        cx: &mut Context<Self>,
10566    ) {
10567        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10568    }
10569
10570    pub fn go_to_diagnostic_impl(
10571        &mut self,
10572        direction: Direction,
10573        window: &mut Window,
10574        cx: &mut Context<Self>,
10575    ) {
10576        let buffer = self.buffer.read(cx).snapshot(cx);
10577        let selection = self.selections.newest::<usize>(cx);
10578
10579        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10580        if direction == Direction::Next {
10581            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10582                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10583                    return;
10584                };
10585                self.activate_diagnostics(
10586                    buffer_id,
10587                    popover.local_diagnostic.diagnostic.group_id,
10588                    window,
10589                    cx,
10590                );
10591                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10592                    let primary_range_start = active_diagnostics.primary_range.start;
10593                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10594                        let mut new_selection = s.newest_anchor().clone();
10595                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10596                        s.select_anchors(vec![new_selection.clone()]);
10597                    });
10598                    self.refresh_inline_completion(false, true, window, cx);
10599                }
10600                return;
10601            }
10602        }
10603
10604        let active_group_id = self
10605            .active_diagnostics
10606            .as_ref()
10607            .map(|active_group| active_group.group_id);
10608        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10609            active_diagnostics
10610                .primary_range
10611                .to_offset(&buffer)
10612                .to_inclusive()
10613        });
10614        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10615            if active_primary_range.contains(&selection.head()) {
10616                *active_primary_range.start()
10617            } else {
10618                selection.head()
10619            }
10620        } else {
10621            selection.head()
10622        };
10623
10624        let snapshot = self.snapshot(window, cx);
10625        let primary_diagnostics_before = buffer
10626            .diagnostics_in_range::<usize>(0..search_start)
10627            .filter(|entry| entry.diagnostic.is_primary)
10628            .filter(|entry| entry.range.start != entry.range.end)
10629            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10630            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10631            .collect::<Vec<_>>();
10632        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10633            primary_diagnostics_before
10634                .iter()
10635                .position(|entry| entry.diagnostic.group_id == active_group_id)
10636        });
10637
10638        let primary_diagnostics_after = buffer
10639            .diagnostics_in_range::<usize>(search_start..buffer.len())
10640            .filter(|entry| entry.diagnostic.is_primary)
10641            .filter(|entry| entry.range.start != entry.range.end)
10642            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10643            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10644            .collect::<Vec<_>>();
10645        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10646            primary_diagnostics_after
10647                .iter()
10648                .enumerate()
10649                .rev()
10650                .find_map(|(i, entry)| {
10651                    if entry.diagnostic.group_id == active_group_id {
10652                        Some(i)
10653                    } else {
10654                        None
10655                    }
10656                })
10657        });
10658
10659        let next_primary_diagnostic = match direction {
10660            Direction::Prev => primary_diagnostics_before
10661                .iter()
10662                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10663                .rev()
10664                .next(),
10665            Direction::Next => primary_diagnostics_after
10666                .iter()
10667                .skip(
10668                    last_same_group_diagnostic_after
10669                        .map(|index| index + 1)
10670                        .unwrap_or(0),
10671                )
10672                .next(),
10673        };
10674
10675        // Cycle around to the start of the buffer, potentially moving back to the start of
10676        // the currently active diagnostic.
10677        let cycle_around = || match direction {
10678            Direction::Prev => primary_diagnostics_after
10679                .iter()
10680                .rev()
10681                .chain(primary_diagnostics_before.iter().rev())
10682                .next(),
10683            Direction::Next => primary_diagnostics_before
10684                .iter()
10685                .chain(primary_diagnostics_after.iter())
10686                .next(),
10687        };
10688
10689        if let Some((primary_range, group_id)) = next_primary_diagnostic
10690            .or_else(cycle_around)
10691            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10692        {
10693            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10694                return;
10695            };
10696            self.activate_diagnostics(buffer_id, group_id, window, cx);
10697            if self.active_diagnostics.is_some() {
10698                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10699                    s.select(vec![Selection {
10700                        id: selection.id,
10701                        start: primary_range.start,
10702                        end: primary_range.start,
10703                        reversed: false,
10704                        goal: SelectionGoal::None,
10705                    }]);
10706                });
10707                self.refresh_inline_completion(false, true, window, cx);
10708            }
10709        }
10710    }
10711
10712    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10713        let snapshot = self.snapshot(window, cx);
10714        let selection = self.selections.newest::<Point>(cx);
10715        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10716    }
10717
10718    fn go_to_hunk_after_position(
10719        &mut self,
10720        snapshot: &EditorSnapshot,
10721        position: Point,
10722        window: &mut Window,
10723        cx: &mut Context<Editor>,
10724    ) -> Option<MultiBufferDiffHunk> {
10725        let mut hunk = snapshot
10726            .buffer_snapshot
10727            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10728            .find(|hunk| hunk.row_range.start.0 > position.row);
10729        if hunk.is_none() {
10730            hunk = snapshot
10731                .buffer_snapshot
10732                .diff_hunks_in_range(Point::zero()..position)
10733                .find(|hunk| hunk.row_range.end.0 < position.row)
10734        }
10735        if let Some(hunk) = &hunk {
10736            let destination = Point::new(hunk.row_range.start.0, 0);
10737            self.unfold_ranges(&[destination..destination], false, false, cx);
10738            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10739                s.select_ranges(vec![destination..destination]);
10740            });
10741        }
10742
10743        hunk
10744    }
10745
10746    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10747        let snapshot = self.snapshot(window, cx);
10748        let selection = self.selections.newest::<Point>(cx);
10749        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10750    }
10751
10752    fn go_to_hunk_before_position(
10753        &mut self,
10754        snapshot: &EditorSnapshot,
10755        position: Point,
10756        window: &mut Window,
10757        cx: &mut Context<Editor>,
10758    ) -> Option<MultiBufferDiffHunk> {
10759        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10760        if hunk.is_none() {
10761            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10762        }
10763        if let Some(hunk) = &hunk {
10764            let destination = Point::new(hunk.row_range.start.0, 0);
10765            self.unfold_ranges(&[destination..destination], false, false, cx);
10766            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10767                s.select_ranges(vec![destination..destination]);
10768            });
10769        }
10770
10771        hunk
10772    }
10773
10774    pub fn go_to_definition(
10775        &mut self,
10776        _: &GoToDefinition,
10777        window: &mut Window,
10778        cx: &mut Context<Self>,
10779    ) -> Task<Result<Navigated>> {
10780        let definition =
10781            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10782        cx.spawn_in(window, |editor, mut cx| async move {
10783            if definition.await? == Navigated::Yes {
10784                return Ok(Navigated::Yes);
10785            }
10786            match editor.update_in(&mut cx, |editor, window, cx| {
10787                editor.find_all_references(&FindAllReferences, window, cx)
10788            })? {
10789                Some(references) => references.await,
10790                None => Ok(Navigated::No),
10791            }
10792        })
10793    }
10794
10795    pub fn go_to_declaration(
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, false, window, cx)
10802    }
10803
10804    pub fn go_to_declaration_split(
10805        &mut self,
10806        _: &GoToDeclaration,
10807        window: &mut Window,
10808        cx: &mut Context<Self>,
10809    ) -> Task<Result<Navigated>> {
10810        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10811    }
10812
10813    pub fn go_to_implementation(
10814        &mut self,
10815        _: &GoToImplementation,
10816        window: &mut Window,
10817        cx: &mut Context<Self>,
10818    ) -> Task<Result<Navigated>> {
10819        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10820    }
10821
10822    pub fn go_to_implementation_split(
10823        &mut self,
10824        _: &GoToImplementationSplit,
10825        window: &mut Window,
10826        cx: &mut Context<Self>,
10827    ) -> Task<Result<Navigated>> {
10828        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10829    }
10830
10831    pub fn go_to_type_definition(
10832        &mut self,
10833        _: &GoToTypeDefinition,
10834        window: &mut Window,
10835        cx: &mut Context<Self>,
10836    ) -> Task<Result<Navigated>> {
10837        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10838    }
10839
10840    pub fn go_to_definition_split(
10841        &mut self,
10842        _: &GoToDefinitionSplit,
10843        window: &mut Window,
10844        cx: &mut Context<Self>,
10845    ) -> Task<Result<Navigated>> {
10846        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10847    }
10848
10849    pub fn go_to_type_definition_split(
10850        &mut self,
10851        _: &GoToTypeDefinitionSplit,
10852        window: &mut Window,
10853        cx: &mut Context<Self>,
10854    ) -> Task<Result<Navigated>> {
10855        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10856    }
10857
10858    fn go_to_definition_of_kind(
10859        &mut self,
10860        kind: GotoDefinitionKind,
10861        split: bool,
10862        window: &mut Window,
10863        cx: &mut Context<Self>,
10864    ) -> Task<Result<Navigated>> {
10865        let Some(provider) = self.semantics_provider.clone() else {
10866            return Task::ready(Ok(Navigated::No));
10867        };
10868        let head = self.selections.newest::<usize>(cx).head();
10869        let buffer = self.buffer.read(cx);
10870        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10871            text_anchor
10872        } else {
10873            return Task::ready(Ok(Navigated::No));
10874        };
10875
10876        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10877            return Task::ready(Ok(Navigated::No));
10878        };
10879
10880        cx.spawn_in(window, |editor, mut cx| async move {
10881            let definitions = definitions.await?;
10882            let navigated = editor
10883                .update_in(&mut cx, |editor, window, cx| {
10884                    editor.navigate_to_hover_links(
10885                        Some(kind),
10886                        definitions
10887                            .into_iter()
10888                            .filter(|location| {
10889                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10890                            })
10891                            .map(HoverLink::Text)
10892                            .collect::<Vec<_>>(),
10893                        split,
10894                        window,
10895                        cx,
10896                    )
10897                })?
10898                .await?;
10899            anyhow::Ok(navigated)
10900        })
10901    }
10902
10903    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10904        let selection = self.selections.newest_anchor();
10905        let head = selection.head();
10906        let tail = selection.tail();
10907
10908        let Some((buffer, start_position)) =
10909            self.buffer.read(cx).text_anchor_for_position(head, cx)
10910        else {
10911            return;
10912        };
10913
10914        let end_position = if head != tail {
10915            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10916                return;
10917            };
10918            Some(pos)
10919        } else {
10920            None
10921        };
10922
10923        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10924            let url = if let Some(end_pos) = end_position {
10925                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10926            } else {
10927                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10928            };
10929
10930            if let Some(url) = url {
10931                editor.update(&mut cx, |_, cx| {
10932                    cx.open_url(&url);
10933                })
10934            } else {
10935                Ok(())
10936            }
10937        });
10938
10939        url_finder.detach();
10940    }
10941
10942    pub fn open_selected_filename(
10943        &mut self,
10944        _: &OpenSelectedFilename,
10945        window: &mut Window,
10946        cx: &mut Context<Self>,
10947    ) {
10948        let Some(workspace) = self.workspace() else {
10949            return;
10950        };
10951
10952        let position = self.selections.newest_anchor().head();
10953
10954        let Some((buffer, buffer_position)) =
10955            self.buffer.read(cx).text_anchor_for_position(position, cx)
10956        else {
10957            return;
10958        };
10959
10960        let project = self.project.clone();
10961
10962        cx.spawn_in(window, |_, mut cx| async move {
10963            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10964
10965            if let Some((_, path)) = result {
10966                workspace
10967                    .update_in(&mut cx, |workspace, window, cx| {
10968                        workspace.open_resolved_path(path, window, cx)
10969                    })?
10970                    .await?;
10971            }
10972            anyhow::Ok(())
10973        })
10974        .detach();
10975    }
10976
10977    pub(crate) fn navigate_to_hover_links(
10978        &mut self,
10979        kind: Option<GotoDefinitionKind>,
10980        mut definitions: Vec<HoverLink>,
10981        split: bool,
10982        window: &mut Window,
10983        cx: &mut Context<Editor>,
10984    ) -> Task<Result<Navigated>> {
10985        // If there is one definition, just open it directly
10986        if definitions.len() == 1 {
10987            let definition = definitions.pop().unwrap();
10988
10989            enum TargetTaskResult {
10990                Location(Option<Location>),
10991                AlreadyNavigated,
10992            }
10993
10994            let target_task = match definition {
10995                HoverLink::Text(link) => {
10996                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10997                }
10998                HoverLink::InlayHint(lsp_location, server_id) => {
10999                    let computation =
11000                        self.compute_target_location(lsp_location, server_id, window, cx);
11001                    cx.background_spawn(async move {
11002                        let location = computation.await?;
11003                        Ok(TargetTaskResult::Location(location))
11004                    })
11005                }
11006                HoverLink::Url(url) => {
11007                    cx.open_url(&url);
11008                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11009                }
11010                HoverLink::File(path) => {
11011                    if let Some(workspace) = self.workspace() {
11012                        cx.spawn_in(window, |_, mut cx| async move {
11013                            workspace
11014                                .update_in(&mut cx, |workspace, window, cx| {
11015                                    workspace.open_resolved_path(path, window, cx)
11016                                })?
11017                                .await
11018                                .map(|_| TargetTaskResult::AlreadyNavigated)
11019                        })
11020                    } else {
11021                        Task::ready(Ok(TargetTaskResult::Location(None)))
11022                    }
11023                }
11024            };
11025            cx.spawn_in(window, |editor, mut cx| async move {
11026                let target = match target_task.await.context("target resolution task")? {
11027                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11028                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11029                    TargetTaskResult::Location(Some(target)) => target,
11030                };
11031
11032                editor.update_in(&mut cx, |editor, window, cx| {
11033                    let Some(workspace) = editor.workspace() else {
11034                        return Navigated::No;
11035                    };
11036                    let pane = workspace.read(cx).active_pane().clone();
11037
11038                    let range = target.range.to_point(target.buffer.read(cx));
11039                    let range = editor.range_for_match(&range);
11040                    let range = collapse_multiline_range(range);
11041
11042                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11043                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11044                    } else {
11045                        window.defer(cx, move |window, cx| {
11046                            let target_editor: Entity<Self> =
11047                                workspace.update(cx, |workspace, cx| {
11048                                    let pane = if split {
11049                                        workspace.adjacent_pane(window, cx)
11050                                    } else {
11051                                        workspace.active_pane().clone()
11052                                    };
11053
11054                                    workspace.open_project_item(
11055                                        pane,
11056                                        target.buffer.clone(),
11057                                        true,
11058                                        true,
11059                                        window,
11060                                        cx,
11061                                    )
11062                                });
11063                            target_editor.update(cx, |target_editor, cx| {
11064                                // When selecting a definition in a different buffer, disable the nav history
11065                                // to avoid creating a history entry at the previous cursor location.
11066                                pane.update(cx, |pane, _| pane.disable_history());
11067                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11068                                pane.update(cx, |pane, _| pane.enable_history());
11069                            });
11070                        });
11071                    }
11072                    Navigated::Yes
11073                })
11074            })
11075        } else if !definitions.is_empty() {
11076            cx.spawn_in(window, |editor, mut cx| async move {
11077                let (title, location_tasks, workspace) = editor
11078                    .update_in(&mut cx, |editor, window, cx| {
11079                        let tab_kind = match kind {
11080                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11081                            _ => "Definitions",
11082                        };
11083                        let title = definitions
11084                            .iter()
11085                            .find_map(|definition| match definition {
11086                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11087                                    let buffer = origin.buffer.read(cx);
11088                                    format!(
11089                                        "{} for {}",
11090                                        tab_kind,
11091                                        buffer
11092                                            .text_for_range(origin.range.clone())
11093                                            .collect::<String>()
11094                                    )
11095                                }),
11096                                HoverLink::InlayHint(_, _) => None,
11097                                HoverLink::Url(_) => None,
11098                                HoverLink::File(_) => None,
11099                            })
11100                            .unwrap_or(tab_kind.to_string());
11101                        let location_tasks = definitions
11102                            .into_iter()
11103                            .map(|definition| match definition {
11104                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11105                                HoverLink::InlayHint(lsp_location, server_id) => editor
11106                                    .compute_target_location(lsp_location, server_id, window, cx),
11107                                HoverLink::Url(_) => Task::ready(Ok(None)),
11108                                HoverLink::File(_) => Task::ready(Ok(None)),
11109                            })
11110                            .collect::<Vec<_>>();
11111                        (title, location_tasks, editor.workspace().clone())
11112                    })
11113                    .context("location tasks preparation")?;
11114
11115                let locations = future::join_all(location_tasks)
11116                    .await
11117                    .into_iter()
11118                    .filter_map(|location| location.transpose())
11119                    .collect::<Result<_>>()
11120                    .context("location tasks")?;
11121
11122                let Some(workspace) = workspace else {
11123                    return Ok(Navigated::No);
11124                };
11125                let opened = workspace
11126                    .update_in(&mut cx, |workspace, window, cx| {
11127                        Self::open_locations_in_multibuffer(
11128                            workspace,
11129                            locations,
11130                            title,
11131                            split,
11132                            MultibufferSelectionMode::First,
11133                            window,
11134                            cx,
11135                        )
11136                    })
11137                    .ok();
11138
11139                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11140            })
11141        } else {
11142            Task::ready(Ok(Navigated::No))
11143        }
11144    }
11145
11146    fn compute_target_location(
11147        &self,
11148        lsp_location: lsp::Location,
11149        server_id: LanguageServerId,
11150        window: &mut Window,
11151        cx: &mut Context<Self>,
11152    ) -> Task<anyhow::Result<Option<Location>>> {
11153        let Some(project) = self.project.clone() else {
11154            return Task::ready(Ok(None));
11155        };
11156
11157        cx.spawn_in(window, move |editor, mut cx| async move {
11158            let location_task = editor.update(&mut cx, |_, cx| {
11159                project.update(cx, |project, cx| {
11160                    let language_server_name = project
11161                        .language_server_statuses(cx)
11162                        .find(|(id, _)| server_id == *id)
11163                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11164                    language_server_name.map(|language_server_name| {
11165                        project.open_local_buffer_via_lsp(
11166                            lsp_location.uri.clone(),
11167                            server_id,
11168                            language_server_name,
11169                            cx,
11170                        )
11171                    })
11172                })
11173            })?;
11174            let location = match location_task {
11175                Some(task) => Some({
11176                    let target_buffer_handle = task.await.context("open local buffer")?;
11177                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11178                        let target_start = target_buffer
11179                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11180                        let target_end = target_buffer
11181                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11182                        target_buffer.anchor_after(target_start)
11183                            ..target_buffer.anchor_before(target_end)
11184                    })?;
11185                    Location {
11186                        buffer: target_buffer_handle,
11187                        range,
11188                    }
11189                }),
11190                None => None,
11191            };
11192            Ok(location)
11193        })
11194    }
11195
11196    pub fn find_all_references(
11197        &mut self,
11198        _: &FindAllReferences,
11199        window: &mut Window,
11200        cx: &mut Context<Self>,
11201    ) -> Option<Task<Result<Navigated>>> {
11202        let selection = self.selections.newest::<usize>(cx);
11203        let multi_buffer = self.buffer.read(cx);
11204        let head = selection.head();
11205
11206        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11207        let head_anchor = multi_buffer_snapshot.anchor_at(
11208            head,
11209            if head < selection.tail() {
11210                Bias::Right
11211            } else {
11212                Bias::Left
11213            },
11214        );
11215
11216        match self
11217            .find_all_references_task_sources
11218            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11219        {
11220            Ok(_) => {
11221                log::info!(
11222                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11223                );
11224                return None;
11225            }
11226            Err(i) => {
11227                self.find_all_references_task_sources.insert(i, head_anchor);
11228            }
11229        }
11230
11231        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11232        let workspace = self.workspace()?;
11233        let project = workspace.read(cx).project().clone();
11234        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11235        Some(cx.spawn_in(window, |editor, mut cx| async move {
11236            let _cleanup = defer({
11237                let mut cx = cx.clone();
11238                move || {
11239                    let _ = editor.update(&mut cx, |editor, _| {
11240                        if let Ok(i) =
11241                            editor
11242                                .find_all_references_task_sources
11243                                .binary_search_by(|anchor| {
11244                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11245                                })
11246                        {
11247                            editor.find_all_references_task_sources.remove(i);
11248                        }
11249                    });
11250                }
11251            });
11252
11253            let locations = references.await?;
11254            if locations.is_empty() {
11255                return anyhow::Ok(Navigated::No);
11256            }
11257
11258            workspace.update_in(&mut cx, |workspace, window, cx| {
11259                let title = locations
11260                    .first()
11261                    .as_ref()
11262                    .map(|location| {
11263                        let buffer = location.buffer.read(cx);
11264                        format!(
11265                            "References to `{}`",
11266                            buffer
11267                                .text_for_range(location.range.clone())
11268                                .collect::<String>()
11269                        )
11270                    })
11271                    .unwrap();
11272                Self::open_locations_in_multibuffer(
11273                    workspace,
11274                    locations,
11275                    title,
11276                    false,
11277                    MultibufferSelectionMode::First,
11278                    window,
11279                    cx,
11280                );
11281                Navigated::Yes
11282            })
11283        }))
11284    }
11285
11286    /// Opens a multibuffer with the given project locations in it
11287    pub fn open_locations_in_multibuffer(
11288        workspace: &mut Workspace,
11289        mut locations: Vec<Location>,
11290        title: String,
11291        split: bool,
11292        multibuffer_selection_mode: MultibufferSelectionMode,
11293        window: &mut Window,
11294        cx: &mut Context<Workspace>,
11295    ) {
11296        // If there are multiple definitions, open them in a multibuffer
11297        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11298        let mut locations = locations.into_iter().peekable();
11299        let mut ranges = Vec::new();
11300        let capability = workspace.project().read(cx).capability();
11301
11302        let excerpt_buffer = cx.new(|cx| {
11303            let mut multibuffer = MultiBuffer::new(capability);
11304            while let Some(location) = locations.next() {
11305                let buffer = location.buffer.read(cx);
11306                let mut ranges_for_buffer = Vec::new();
11307                let range = location.range.to_offset(buffer);
11308                ranges_for_buffer.push(range.clone());
11309
11310                while let Some(next_location) = locations.peek() {
11311                    if next_location.buffer == location.buffer {
11312                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11313                        locations.next();
11314                    } else {
11315                        break;
11316                    }
11317                }
11318
11319                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11320                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11321                    location.buffer.clone(),
11322                    ranges_for_buffer,
11323                    DEFAULT_MULTIBUFFER_CONTEXT,
11324                    cx,
11325                ))
11326            }
11327
11328            multibuffer.with_title(title)
11329        });
11330
11331        let editor = cx.new(|cx| {
11332            Editor::for_multibuffer(
11333                excerpt_buffer,
11334                Some(workspace.project().clone()),
11335                true,
11336                window,
11337                cx,
11338            )
11339        });
11340        editor.update(cx, |editor, cx| {
11341            match multibuffer_selection_mode {
11342                MultibufferSelectionMode::First => {
11343                    if let Some(first_range) = ranges.first() {
11344                        editor.change_selections(None, window, cx, |selections| {
11345                            selections.clear_disjoint();
11346                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11347                        });
11348                    }
11349                    editor.highlight_background::<Self>(
11350                        &ranges,
11351                        |theme| theme.editor_highlighted_line_background,
11352                        cx,
11353                    );
11354                }
11355                MultibufferSelectionMode::All => {
11356                    editor.change_selections(None, window, cx, |selections| {
11357                        selections.clear_disjoint();
11358                        selections.select_anchor_ranges(ranges);
11359                    });
11360                }
11361            }
11362            editor.register_buffers_with_language_servers(cx);
11363        });
11364
11365        let item = Box::new(editor);
11366        let item_id = item.item_id();
11367
11368        if split {
11369            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11370        } else {
11371            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11372                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11373                    pane.close_current_preview_item(window, cx)
11374                } else {
11375                    None
11376                }
11377            });
11378            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11379        }
11380        workspace.active_pane().update(cx, |pane, cx| {
11381            pane.set_preview_item_id(Some(item_id), cx);
11382        });
11383    }
11384
11385    pub fn rename(
11386        &mut self,
11387        _: &Rename,
11388        window: &mut Window,
11389        cx: &mut Context<Self>,
11390    ) -> Option<Task<Result<()>>> {
11391        use language::ToOffset as _;
11392
11393        let provider = self.semantics_provider.clone()?;
11394        let selection = self.selections.newest_anchor().clone();
11395        let (cursor_buffer, cursor_buffer_position) = self
11396            .buffer
11397            .read(cx)
11398            .text_anchor_for_position(selection.head(), cx)?;
11399        let (tail_buffer, cursor_buffer_position_end) = self
11400            .buffer
11401            .read(cx)
11402            .text_anchor_for_position(selection.tail(), cx)?;
11403        if tail_buffer != cursor_buffer {
11404            return None;
11405        }
11406
11407        let snapshot = cursor_buffer.read(cx).snapshot();
11408        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11409        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11410        let prepare_rename = provider
11411            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11412            .unwrap_or_else(|| Task::ready(Ok(None)));
11413        drop(snapshot);
11414
11415        Some(cx.spawn_in(window, |this, mut cx| async move {
11416            let rename_range = if let Some(range) = prepare_rename.await? {
11417                Some(range)
11418            } else {
11419                this.update(&mut cx, |this, cx| {
11420                    let buffer = this.buffer.read(cx).snapshot(cx);
11421                    let mut buffer_highlights = this
11422                        .document_highlights_for_position(selection.head(), &buffer)
11423                        .filter(|highlight| {
11424                            highlight.start.excerpt_id == selection.head().excerpt_id
11425                                && highlight.end.excerpt_id == selection.head().excerpt_id
11426                        });
11427                    buffer_highlights
11428                        .next()
11429                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11430                })?
11431            };
11432            if let Some(rename_range) = rename_range {
11433                this.update_in(&mut cx, |this, window, cx| {
11434                    let snapshot = cursor_buffer.read(cx).snapshot();
11435                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11436                    let cursor_offset_in_rename_range =
11437                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11438                    let cursor_offset_in_rename_range_end =
11439                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11440
11441                    this.take_rename(false, window, cx);
11442                    let buffer = this.buffer.read(cx).read(cx);
11443                    let cursor_offset = selection.head().to_offset(&buffer);
11444                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11445                    let rename_end = rename_start + rename_buffer_range.len();
11446                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11447                    let mut old_highlight_id = None;
11448                    let old_name: Arc<str> = buffer
11449                        .chunks(rename_start..rename_end, true)
11450                        .map(|chunk| {
11451                            if old_highlight_id.is_none() {
11452                                old_highlight_id = chunk.syntax_highlight_id;
11453                            }
11454                            chunk.text
11455                        })
11456                        .collect::<String>()
11457                        .into();
11458
11459                    drop(buffer);
11460
11461                    // Position the selection in the rename editor so that it matches the current selection.
11462                    this.show_local_selections = false;
11463                    let rename_editor = cx.new(|cx| {
11464                        let mut editor = Editor::single_line(window, cx);
11465                        editor.buffer.update(cx, |buffer, cx| {
11466                            buffer.edit([(0..0, old_name.clone())], None, cx)
11467                        });
11468                        let rename_selection_range = match cursor_offset_in_rename_range
11469                            .cmp(&cursor_offset_in_rename_range_end)
11470                        {
11471                            Ordering::Equal => {
11472                                editor.select_all(&SelectAll, window, cx);
11473                                return editor;
11474                            }
11475                            Ordering::Less => {
11476                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11477                            }
11478                            Ordering::Greater => {
11479                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11480                            }
11481                        };
11482                        if rename_selection_range.end > old_name.len() {
11483                            editor.select_all(&SelectAll, window, cx);
11484                        } else {
11485                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11486                                s.select_ranges([rename_selection_range]);
11487                            });
11488                        }
11489                        editor
11490                    });
11491                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11492                        if e == &EditorEvent::Focused {
11493                            cx.emit(EditorEvent::FocusedIn)
11494                        }
11495                    })
11496                    .detach();
11497
11498                    let write_highlights =
11499                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11500                    let read_highlights =
11501                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11502                    let ranges = write_highlights
11503                        .iter()
11504                        .flat_map(|(_, ranges)| ranges.iter())
11505                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11506                        .cloned()
11507                        .collect();
11508
11509                    this.highlight_text::<Rename>(
11510                        ranges,
11511                        HighlightStyle {
11512                            fade_out: Some(0.6),
11513                            ..Default::default()
11514                        },
11515                        cx,
11516                    );
11517                    let rename_focus_handle = rename_editor.focus_handle(cx);
11518                    window.focus(&rename_focus_handle);
11519                    let block_id = this.insert_blocks(
11520                        [BlockProperties {
11521                            style: BlockStyle::Flex,
11522                            placement: BlockPlacement::Below(range.start),
11523                            height: 1,
11524                            render: Arc::new({
11525                                let rename_editor = rename_editor.clone();
11526                                move |cx: &mut BlockContext| {
11527                                    let mut text_style = cx.editor_style.text.clone();
11528                                    if let Some(highlight_style) = old_highlight_id
11529                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11530                                    {
11531                                        text_style = text_style.highlight(highlight_style);
11532                                    }
11533                                    div()
11534                                        .block_mouse_down()
11535                                        .pl(cx.anchor_x)
11536                                        .child(EditorElement::new(
11537                                            &rename_editor,
11538                                            EditorStyle {
11539                                                background: cx.theme().system().transparent,
11540                                                local_player: cx.editor_style.local_player,
11541                                                text: text_style,
11542                                                scrollbar_width: cx.editor_style.scrollbar_width,
11543                                                syntax: cx.editor_style.syntax.clone(),
11544                                                status: cx.editor_style.status.clone(),
11545                                                inlay_hints_style: HighlightStyle {
11546                                                    font_weight: Some(FontWeight::BOLD),
11547                                                    ..make_inlay_hints_style(cx.app)
11548                                                },
11549                                                inline_completion_styles: make_suggestion_styles(
11550                                                    cx.app,
11551                                                ),
11552                                                ..EditorStyle::default()
11553                                            },
11554                                        ))
11555                                        .into_any_element()
11556                                }
11557                            }),
11558                            priority: 0,
11559                        }],
11560                        Some(Autoscroll::fit()),
11561                        cx,
11562                    )[0];
11563                    this.pending_rename = Some(RenameState {
11564                        range,
11565                        old_name,
11566                        editor: rename_editor,
11567                        block_id,
11568                    });
11569                })?;
11570            }
11571
11572            Ok(())
11573        }))
11574    }
11575
11576    pub fn confirm_rename(
11577        &mut self,
11578        _: &ConfirmRename,
11579        window: &mut Window,
11580        cx: &mut Context<Self>,
11581    ) -> Option<Task<Result<()>>> {
11582        let rename = self.take_rename(false, window, cx)?;
11583        let workspace = self.workspace()?.downgrade();
11584        let (buffer, start) = self
11585            .buffer
11586            .read(cx)
11587            .text_anchor_for_position(rename.range.start, cx)?;
11588        let (end_buffer, _) = self
11589            .buffer
11590            .read(cx)
11591            .text_anchor_for_position(rename.range.end, cx)?;
11592        if buffer != end_buffer {
11593            return None;
11594        }
11595
11596        let old_name = rename.old_name;
11597        let new_name = rename.editor.read(cx).text(cx);
11598
11599        let rename = self.semantics_provider.as_ref()?.perform_rename(
11600            &buffer,
11601            start,
11602            new_name.clone(),
11603            cx,
11604        )?;
11605
11606        Some(cx.spawn_in(window, |editor, mut cx| async move {
11607            let project_transaction = rename.await?;
11608            Self::open_project_transaction(
11609                &editor,
11610                workspace,
11611                project_transaction,
11612                format!("Rename: {}{}", old_name, new_name),
11613                cx.clone(),
11614            )
11615            .await?;
11616
11617            editor.update(&mut cx, |editor, cx| {
11618                editor.refresh_document_highlights(cx);
11619            })?;
11620            Ok(())
11621        }))
11622    }
11623
11624    fn take_rename(
11625        &mut self,
11626        moving_cursor: bool,
11627        window: &mut Window,
11628        cx: &mut Context<Self>,
11629    ) -> Option<RenameState> {
11630        let rename = self.pending_rename.take()?;
11631        if rename.editor.focus_handle(cx).is_focused(window) {
11632            window.focus(&self.focus_handle);
11633        }
11634
11635        self.remove_blocks(
11636            [rename.block_id].into_iter().collect(),
11637            Some(Autoscroll::fit()),
11638            cx,
11639        );
11640        self.clear_highlights::<Rename>(cx);
11641        self.show_local_selections = true;
11642
11643        if moving_cursor {
11644            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11645                editor.selections.newest::<usize>(cx).head()
11646            });
11647
11648            // Update the selection to match the position of the selection inside
11649            // the rename editor.
11650            let snapshot = self.buffer.read(cx).read(cx);
11651            let rename_range = rename.range.to_offset(&snapshot);
11652            let cursor_in_editor = snapshot
11653                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11654                .min(rename_range.end);
11655            drop(snapshot);
11656
11657            self.change_selections(None, window, cx, |s| {
11658                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11659            });
11660        } else {
11661            self.refresh_document_highlights(cx);
11662        }
11663
11664        Some(rename)
11665    }
11666
11667    pub fn pending_rename(&self) -> Option<&RenameState> {
11668        self.pending_rename.as_ref()
11669    }
11670
11671    fn format(
11672        &mut self,
11673        _: &Format,
11674        window: &mut Window,
11675        cx: &mut Context<Self>,
11676    ) -> Option<Task<Result<()>>> {
11677        let project = match &self.project {
11678            Some(project) => project.clone(),
11679            None => return None,
11680        };
11681
11682        Some(self.perform_format(
11683            project,
11684            FormatTrigger::Manual,
11685            FormatTarget::Buffers,
11686            window,
11687            cx,
11688        ))
11689    }
11690
11691    fn format_selections(
11692        &mut self,
11693        _: &FormatSelections,
11694        window: &mut Window,
11695        cx: &mut Context<Self>,
11696    ) -> Option<Task<Result<()>>> {
11697        let project = match &self.project {
11698            Some(project) => project.clone(),
11699            None => return None,
11700        };
11701
11702        let ranges = self
11703            .selections
11704            .all_adjusted(cx)
11705            .into_iter()
11706            .map(|selection| selection.range())
11707            .collect_vec();
11708
11709        Some(self.perform_format(
11710            project,
11711            FormatTrigger::Manual,
11712            FormatTarget::Ranges(ranges),
11713            window,
11714            cx,
11715        ))
11716    }
11717
11718    fn perform_format(
11719        &mut self,
11720        project: Entity<Project>,
11721        trigger: FormatTrigger,
11722        target: FormatTarget,
11723        window: &mut Window,
11724        cx: &mut Context<Self>,
11725    ) -> Task<Result<()>> {
11726        let buffer = self.buffer.clone();
11727        let (buffers, target) = match target {
11728            FormatTarget::Buffers => {
11729                let mut buffers = buffer.read(cx).all_buffers();
11730                if trigger == FormatTrigger::Save {
11731                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11732                }
11733                (buffers, LspFormatTarget::Buffers)
11734            }
11735            FormatTarget::Ranges(selection_ranges) => {
11736                let multi_buffer = buffer.read(cx);
11737                let snapshot = multi_buffer.read(cx);
11738                let mut buffers = HashSet::default();
11739                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11740                    BTreeMap::new();
11741                for selection_range in selection_ranges {
11742                    for (buffer, buffer_range, _) in
11743                        snapshot.range_to_buffer_ranges(selection_range)
11744                    {
11745                        let buffer_id = buffer.remote_id();
11746                        let start = buffer.anchor_before(buffer_range.start);
11747                        let end = buffer.anchor_after(buffer_range.end);
11748                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11749                        buffer_id_to_ranges
11750                            .entry(buffer_id)
11751                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11752                            .or_insert_with(|| vec![start..end]);
11753                    }
11754                }
11755                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11756            }
11757        };
11758
11759        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11760        let format = project.update(cx, |project, cx| {
11761            project.format(buffers, target, true, trigger, cx)
11762        });
11763
11764        cx.spawn_in(window, |_, mut cx| async move {
11765            let transaction = futures::select_biased! {
11766                () = timeout => {
11767                    log::warn!("timed out waiting for formatting");
11768                    None
11769                }
11770                transaction = format.log_err().fuse() => transaction,
11771            };
11772
11773            buffer
11774                .update(&mut cx, |buffer, cx| {
11775                    if let Some(transaction) = transaction {
11776                        if !buffer.is_singleton() {
11777                            buffer.push_transaction(&transaction.0, cx);
11778                        }
11779                    }
11780
11781                    cx.notify();
11782                })
11783                .ok();
11784
11785            Ok(())
11786        })
11787    }
11788
11789    fn restart_language_server(
11790        &mut self,
11791        _: &RestartLanguageServer,
11792        _: &mut Window,
11793        cx: &mut Context<Self>,
11794    ) {
11795        if let Some(project) = self.project.clone() {
11796            self.buffer.update(cx, |multi_buffer, cx| {
11797                project.update(cx, |project, cx| {
11798                    project.restart_language_servers_for_buffers(
11799                        multi_buffer.all_buffers().into_iter().collect(),
11800                        cx,
11801                    );
11802                });
11803            })
11804        }
11805    }
11806
11807    fn cancel_language_server_work(
11808        workspace: &mut Workspace,
11809        _: &actions::CancelLanguageServerWork,
11810        _: &mut Window,
11811        cx: &mut Context<Workspace>,
11812    ) {
11813        let project = workspace.project();
11814        let buffers = workspace
11815            .active_item(cx)
11816            .and_then(|item| item.act_as::<Editor>(cx))
11817            .map_or(HashSet::default(), |editor| {
11818                editor.read(cx).buffer.read(cx).all_buffers()
11819            });
11820        project.update(cx, |project, cx| {
11821            project.cancel_language_server_work_for_buffers(buffers, cx);
11822        });
11823    }
11824
11825    fn show_character_palette(
11826        &mut self,
11827        _: &ShowCharacterPalette,
11828        window: &mut Window,
11829        _: &mut Context<Self>,
11830    ) {
11831        window.show_character_palette();
11832    }
11833
11834    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11835        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11836            let buffer = self.buffer.read(cx).snapshot(cx);
11837            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11838            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11839            let is_valid = buffer
11840                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11841                .any(|entry| {
11842                    entry.diagnostic.is_primary
11843                        && !entry.range.is_empty()
11844                        && entry.range.start == primary_range_start
11845                        && entry.diagnostic.message == active_diagnostics.primary_message
11846                });
11847
11848            if is_valid != active_diagnostics.is_valid {
11849                active_diagnostics.is_valid = is_valid;
11850                let mut new_styles = HashMap::default();
11851                for (block_id, diagnostic) in &active_diagnostics.blocks {
11852                    new_styles.insert(
11853                        *block_id,
11854                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11855                    );
11856                }
11857                self.display_map.update(cx, |display_map, _cx| {
11858                    display_map.replace_blocks(new_styles)
11859                });
11860            }
11861        }
11862    }
11863
11864    fn activate_diagnostics(
11865        &mut self,
11866        buffer_id: BufferId,
11867        group_id: usize,
11868        window: &mut Window,
11869        cx: &mut Context<Self>,
11870    ) {
11871        self.dismiss_diagnostics(cx);
11872        let snapshot = self.snapshot(window, cx);
11873        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11874            let buffer = self.buffer.read(cx).snapshot(cx);
11875
11876            let mut primary_range = None;
11877            let mut primary_message = None;
11878            let diagnostic_group = buffer
11879                .diagnostic_group(buffer_id, group_id)
11880                .filter_map(|entry| {
11881                    let start = entry.range.start;
11882                    let end = entry.range.end;
11883                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11884                        && (start.row == end.row
11885                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11886                    {
11887                        return None;
11888                    }
11889                    if entry.diagnostic.is_primary {
11890                        primary_range = Some(entry.range.clone());
11891                        primary_message = Some(entry.diagnostic.message.clone());
11892                    }
11893                    Some(entry)
11894                })
11895                .collect::<Vec<_>>();
11896            let primary_range = primary_range?;
11897            let primary_message = primary_message?;
11898
11899            let blocks = display_map
11900                .insert_blocks(
11901                    diagnostic_group.iter().map(|entry| {
11902                        let diagnostic = entry.diagnostic.clone();
11903                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11904                        BlockProperties {
11905                            style: BlockStyle::Fixed,
11906                            placement: BlockPlacement::Below(
11907                                buffer.anchor_after(entry.range.start),
11908                            ),
11909                            height: message_height,
11910                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11911                            priority: 0,
11912                        }
11913                    }),
11914                    cx,
11915                )
11916                .into_iter()
11917                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11918                .collect();
11919
11920            Some(ActiveDiagnosticGroup {
11921                primary_range: buffer.anchor_before(primary_range.start)
11922                    ..buffer.anchor_after(primary_range.end),
11923                primary_message,
11924                group_id,
11925                blocks,
11926                is_valid: true,
11927            })
11928        });
11929    }
11930
11931    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11932        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11933            self.display_map.update(cx, |display_map, cx| {
11934                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11935            });
11936            cx.notify();
11937        }
11938    }
11939
11940    pub fn set_selections_from_remote(
11941        &mut self,
11942        selections: Vec<Selection<Anchor>>,
11943        pending_selection: Option<Selection<Anchor>>,
11944        window: &mut Window,
11945        cx: &mut Context<Self>,
11946    ) {
11947        let old_cursor_position = self.selections.newest_anchor().head();
11948        self.selections.change_with(cx, |s| {
11949            s.select_anchors(selections);
11950            if let Some(pending_selection) = pending_selection {
11951                s.set_pending(pending_selection, SelectMode::Character);
11952            } else {
11953                s.clear_pending();
11954            }
11955        });
11956        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11957    }
11958
11959    fn push_to_selection_history(&mut self) {
11960        self.selection_history.push(SelectionHistoryEntry {
11961            selections: self.selections.disjoint_anchors(),
11962            select_next_state: self.select_next_state.clone(),
11963            select_prev_state: self.select_prev_state.clone(),
11964            add_selections_state: self.add_selections_state.clone(),
11965        });
11966    }
11967
11968    pub fn transact(
11969        &mut self,
11970        window: &mut Window,
11971        cx: &mut Context<Self>,
11972        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11973    ) -> Option<TransactionId> {
11974        self.start_transaction_at(Instant::now(), window, cx);
11975        update(self, window, cx);
11976        self.end_transaction_at(Instant::now(), cx)
11977    }
11978
11979    pub fn start_transaction_at(
11980        &mut self,
11981        now: Instant,
11982        window: &mut Window,
11983        cx: &mut Context<Self>,
11984    ) {
11985        self.end_selection(window, cx);
11986        if let Some(tx_id) = self
11987            .buffer
11988            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11989        {
11990            self.selection_history
11991                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11992            cx.emit(EditorEvent::TransactionBegun {
11993                transaction_id: tx_id,
11994            })
11995        }
11996    }
11997
11998    pub fn end_transaction_at(
11999        &mut self,
12000        now: Instant,
12001        cx: &mut Context<Self>,
12002    ) -> Option<TransactionId> {
12003        if let Some(transaction_id) = self
12004            .buffer
12005            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12006        {
12007            if let Some((_, end_selections)) =
12008                self.selection_history.transaction_mut(transaction_id)
12009            {
12010                *end_selections = Some(self.selections.disjoint_anchors());
12011            } else {
12012                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12013            }
12014
12015            cx.emit(EditorEvent::Edited { transaction_id });
12016            Some(transaction_id)
12017        } else {
12018            None
12019        }
12020    }
12021
12022    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12023        if self.selection_mark_mode {
12024            self.change_selections(None, window, cx, |s| {
12025                s.move_with(|_, sel| {
12026                    sel.collapse_to(sel.head(), SelectionGoal::None);
12027                });
12028            })
12029        }
12030        self.selection_mark_mode = true;
12031        cx.notify();
12032    }
12033
12034    pub fn swap_selection_ends(
12035        &mut self,
12036        _: &actions::SwapSelectionEnds,
12037        window: &mut Window,
12038        cx: &mut Context<Self>,
12039    ) {
12040        self.change_selections(None, window, cx, |s| {
12041            s.move_with(|_, sel| {
12042                if sel.start != sel.end {
12043                    sel.reversed = !sel.reversed
12044                }
12045            });
12046        });
12047        self.request_autoscroll(Autoscroll::newest(), cx);
12048        cx.notify();
12049    }
12050
12051    pub fn toggle_fold(
12052        &mut self,
12053        _: &actions::ToggleFold,
12054        window: &mut Window,
12055        cx: &mut Context<Self>,
12056    ) {
12057        if self.is_singleton(cx) {
12058            let selection = self.selections.newest::<Point>(cx);
12059
12060            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12061            let range = if selection.is_empty() {
12062                let point = selection.head().to_display_point(&display_map);
12063                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12064                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12065                    .to_point(&display_map);
12066                start..end
12067            } else {
12068                selection.range()
12069            };
12070            if display_map.folds_in_range(range).next().is_some() {
12071                self.unfold_lines(&Default::default(), window, cx)
12072            } else {
12073                self.fold(&Default::default(), window, cx)
12074            }
12075        } else {
12076            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12077            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12078                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12079                .map(|(snapshot, _, _)| snapshot.remote_id())
12080                .collect();
12081
12082            for buffer_id in buffer_ids {
12083                if self.is_buffer_folded(buffer_id, cx) {
12084                    self.unfold_buffer(buffer_id, cx);
12085                } else {
12086                    self.fold_buffer(buffer_id, cx);
12087                }
12088            }
12089        }
12090    }
12091
12092    pub fn toggle_fold_recursive(
12093        &mut self,
12094        _: &actions::ToggleFoldRecursive,
12095        window: &mut Window,
12096        cx: &mut Context<Self>,
12097    ) {
12098        let selection = self.selections.newest::<Point>(cx);
12099
12100        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12101        let range = if selection.is_empty() {
12102            let point = selection.head().to_display_point(&display_map);
12103            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12104            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12105                .to_point(&display_map);
12106            start..end
12107        } else {
12108            selection.range()
12109        };
12110        if display_map.folds_in_range(range).next().is_some() {
12111            self.unfold_recursive(&Default::default(), window, cx)
12112        } else {
12113            self.fold_recursive(&Default::default(), window, cx)
12114        }
12115    }
12116
12117    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12118        if self.is_singleton(cx) {
12119            let mut to_fold = Vec::new();
12120            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12121            let selections = self.selections.all_adjusted(cx);
12122
12123            for selection in selections {
12124                let range = selection.range().sorted();
12125                let buffer_start_row = range.start.row;
12126
12127                if range.start.row != range.end.row {
12128                    let mut found = false;
12129                    let mut row = range.start.row;
12130                    while row <= range.end.row {
12131                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12132                        {
12133                            found = true;
12134                            row = crease.range().end.row + 1;
12135                            to_fold.push(crease);
12136                        } else {
12137                            row += 1
12138                        }
12139                    }
12140                    if found {
12141                        continue;
12142                    }
12143                }
12144
12145                for row in (0..=range.start.row).rev() {
12146                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12147                        if crease.range().end.row >= buffer_start_row {
12148                            to_fold.push(crease);
12149                            if row <= range.start.row {
12150                                break;
12151                            }
12152                        }
12153                    }
12154                }
12155            }
12156
12157            self.fold_creases(to_fold, true, window, cx);
12158        } else {
12159            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12160
12161            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12162                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12163                .map(|(snapshot, _, _)| snapshot.remote_id())
12164                .collect();
12165            for buffer_id in buffer_ids {
12166                self.fold_buffer(buffer_id, cx);
12167            }
12168        }
12169    }
12170
12171    fn fold_at_level(
12172        &mut self,
12173        fold_at: &FoldAtLevel,
12174        window: &mut Window,
12175        cx: &mut Context<Self>,
12176    ) {
12177        if !self.buffer.read(cx).is_singleton() {
12178            return;
12179        }
12180
12181        let fold_at_level = fold_at.0;
12182        let snapshot = self.buffer.read(cx).snapshot(cx);
12183        let mut to_fold = Vec::new();
12184        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12185
12186        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12187            while start_row < end_row {
12188                match self
12189                    .snapshot(window, cx)
12190                    .crease_for_buffer_row(MultiBufferRow(start_row))
12191                {
12192                    Some(crease) => {
12193                        let nested_start_row = crease.range().start.row + 1;
12194                        let nested_end_row = crease.range().end.row;
12195
12196                        if current_level < fold_at_level {
12197                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12198                        } else if current_level == fold_at_level {
12199                            to_fold.push(crease);
12200                        }
12201
12202                        start_row = nested_end_row + 1;
12203                    }
12204                    None => start_row += 1,
12205                }
12206            }
12207        }
12208
12209        self.fold_creases(to_fold, true, window, cx);
12210    }
12211
12212    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12213        if self.buffer.read(cx).is_singleton() {
12214            let mut fold_ranges = Vec::new();
12215            let snapshot = self.buffer.read(cx).snapshot(cx);
12216
12217            for row in 0..snapshot.max_row().0 {
12218                if let Some(foldable_range) = self
12219                    .snapshot(window, cx)
12220                    .crease_for_buffer_row(MultiBufferRow(row))
12221                {
12222                    fold_ranges.push(foldable_range);
12223                }
12224            }
12225
12226            self.fold_creases(fold_ranges, true, window, cx);
12227        } else {
12228            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12229                editor
12230                    .update_in(&mut cx, |editor, _, cx| {
12231                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12232                            editor.fold_buffer(buffer_id, cx);
12233                        }
12234                    })
12235                    .ok();
12236            });
12237        }
12238    }
12239
12240    pub fn fold_function_bodies(
12241        &mut self,
12242        _: &actions::FoldFunctionBodies,
12243        window: &mut Window,
12244        cx: &mut Context<Self>,
12245    ) {
12246        let snapshot = self.buffer.read(cx).snapshot(cx);
12247
12248        let ranges = snapshot
12249            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12250            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12251            .collect::<Vec<_>>();
12252
12253        let creases = ranges
12254            .into_iter()
12255            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12256            .collect();
12257
12258        self.fold_creases(creases, true, window, cx);
12259    }
12260
12261    pub fn fold_recursive(
12262        &mut self,
12263        _: &actions::FoldRecursive,
12264        window: &mut Window,
12265        cx: &mut Context<Self>,
12266    ) {
12267        let mut to_fold = Vec::new();
12268        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12269        let selections = self.selections.all_adjusted(cx);
12270
12271        for selection in selections {
12272            let range = selection.range().sorted();
12273            let buffer_start_row = range.start.row;
12274
12275            if range.start.row != range.end.row {
12276                let mut found = false;
12277                for row in range.start.row..=range.end.row {
12278                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12279                        found = true;
12280                        to_fold.push(crease);
12281                    }
12282                }
12283                if found {
12284                    continue;
12285                }
12286            }
12287
12288            for row in (0..=range.start.row).rev() {
12289                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12290                    if crease.range().end.row >= buffer_start_row {
12291                        to_fold.push(crease);
12292                    } else {
12293                        break;
12294                    }
12295                }
12296            }
12297        }
12298
12299        self.fold_creases(to_fold, true, window, cx);
12300    }
12301
12302    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12303        let buffer_row = fold_at.buffer_row;
12304        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12305
12306        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12307            let autoscroll = self
12308                .selections
12309                .all::<Point>(cx)
12310                .iter()
12311                .any(|selection| crease.range().overlaps(&selection.range()));
12312
12313            self.fold_creases(vec![crease], autoscroll, window, cx);
12314        }
12315    }
12316
12317    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12318        if self.is_singleton(cx) {
12319            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12320            let buffer = &display_map.buffer_snapshot;
12321            let selections = self.selections.all::<Point>(cx);
12322            let ranges = selections
12323                .iter()
12324                .map(|s| {
12325                    let range = s.display_range(&display_map).sorted();
12326                    let mut start = range.start.to_point(&display_map);
12327                    let mut end = range.end.to_point(&display_map);
12328                    start.column = 0;
12329                    end.column = buffer.line_len(MultiBufferRow(end.row));
12330                    start..end
12331                })
12332                .collect::<Vec<_>>();
12333
12334            self.unfold_ranges(&ranges, true, true, cx);
12335        } else {
12336            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12337            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12338                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12339                .map(|(snapshot, _, _)| snapshot.remote_id())
12340                .collect();
12341            for buffer_id in buffer_ids {
12342                self.unfold_buffer(buffer_id, cx);
12343            }
12344        }
12345    }
12346
12347    pub fn unfold_recursive(
12348        &mut self,
12349        _: &UnfoldRecursive,
12350        _window: &mut Window,
12351        cx: &mut Context<Self>,
12352    ) {
12353        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12354        let selections = self.selections.all::<Point>(cx);
12355        let ranges = selections
12356            .iter()
12357            .map(|s| {
12358                let mut range = s.display_range(&display_map).sorted();
12359                *range.start.column_mut() = 0;
12360                *range.end.column_mut() = display_map.line_len(range.end.row());
12361                let start = range.start.to_point(&display_map);
12362                let end = range.end.to_point(&display_map);
12363                start..end
12364            })
12365            .collect::<Vec<_>>();
12366
12367        self.unfold_ranges(&ranges, true, true, cx);
12368    }
12369
12370    pub fn unfold_at(
12371        &mut self,
12372        unfold_at: &UnfoldAt,
12373        _window: &mut Window,
12374        cx: &mut Context<Self>,
12375    ) {
12376        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12377
12378        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12379            ..Point::new(
12380                unfold_at.buffer_row.0,
12381                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12382            );
12383
12384        let autoscroll = self
12385            .selections
12386            .all::<Point>(cx)
12387            .iter()
12388            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12389
12390        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12391    }
12392
12393    pub fn unfold_all(
12394        &mut self,
12395        _: &actions::UnfoldAll,
12396        _window: &mut Window,
12397        cx: &mut Context<Self>,
12398    ) {
12399        if self.buffer.read(cx).is_singleton() {
12400            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12401            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12402        } else {
12403            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12404                editor
12405                    .update(&mut cx, |editor, cx| {
12406                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12407                            editor.unfold_buffer(buffer_id, cx);
12408                        }
12409                    })
12410                    .ok();
12411            });
12412        }
12413    }
12414
12415    pub fn fold_selected_ranges(
12416        &mut self,
12417        _: &FoldSelectedRanges,
12418        window: &mut Window,
12419        cx: &mut Context<Self>,
12420    ) {
12421        let selections = self.selections.all::<Point>(cx);
12422        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12423        let line_mode = self.selections.line_mode;
12424        let ranges = selections
12425            .into_iter()
12426            .map(|s| {
12427                if line_mode {
12428                    let start = Point::new(s.start.row, 0);
12429                    let end = Point::new(
12430                        s.end.row,
12431                        display_map
12432                            .buffer_snapshot
12433                            .line_len(MultiBufferRow(s.end.row)),
12434                    );
12435                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12436                } else {
12437                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12438                }
12439            })
12440            .collect::<Vec<_>>();
12441        self.fold_creases(ranges, true, window, cx);
12442    }
12443
12444    pub fn fold_ranges<T: ToOffset + Clone>(
12445        &mut self,
12446        ranges: Vec<Range<T>>,
12447        auto_scroll: bool,
12448        window: &mut Window,
12449        cx: &mut Context<Self>,
12450    ) {
12451        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12452        let ranges = ranges
12453            .into_iter()
12454            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12455            .collect::<Vec<_>>();
12456        self.fold_creases(ranges, auto_scroll, window, cx);
12457    }
12458
12459    pub fn fold_creases<T: ToOffset + Clone>(
12460        &mut self,
12461        creases: Vec<Crease<T>>,
12462        auto_scroll: bool,
12463        window: &mut Window,
12464        cx: &mut Context<Self>,
12465    ) {
12466        if creases.is_empty() {
12467            return;
12468        }
12469
12470        let mut buffers_affected = HashSet::default();
12471        let multi_buffer = self.buffer().read(cx);
12472        for crease in &creases {
12473            if let Some((_, buffer, _)) =
12474                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12475            {
12476                buffers_affected.insert(buffer.read(cx).remote_id());
12477            };
12478        }
12479
12480        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12481
12482        if auto_scroll {
12483            self.request_autoscroll(Autoscroll::fit(), cx);
12484        }
12485
12486        cx.notify();
12487
12488        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12489            // Clear diagnostics block when folding a range that contains it.
12490            let snapshot = self.snapshot(window, cx);
12491            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12492                drop(snapshot);
12493                self.active_diagnostics = Some(active_diagnostics);
12494                self.dismiss_diagnostics(cx);
12495            } else {
12496                self.active_diagnostics = Some(active_diagnostics);
12497            }
12498        }
12499
12500        self.scrollbar_marker_state.dirty = true;
12501    }
12502
12503    /// Removes any folds whose ranges intersect any of the given ranges.
12504    pub fn unfold_ranges<T: ToOffset + Clone>(
12505        &mut self,
12506        ranges: &[Range<T>],
12507        inclusive: bool,
12508        auto_scroll: bool,
12509        cx: &mut Context<Self>,
12510    ) {
12511        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12512            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12513        });
12514    }
12515
12516    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12517        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12518            return;
12519        }
12520        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12521        self.display_map
12522            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12523        cx.emit(EditorEvent::BufferFoldToggled {
12524            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12525            folded: true,
12526        });
12527        cx.notify();
12528    }
12529
12530    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12531        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12532            return;
12533        }
12534        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12535        self.display_map.update(cx, |display_map, cx| {
12536            display_map.unfold_buffer(buffer_id, cx);
12537        });
12538        cx.emit(EditorEvent::BufferFoldToggled {
12539            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12540            folded: false,
12541        });
12542        cx.notify();
12543    }
12544
12545    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12546        self.display_map.read(cx).is_buffer_folded(buffer)
12547    }
12548
12549    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12550        self.display_map.read(cx).folded_buffers()
12551    }
12552
12553    /// Removes any folds with the given ranges.
12554    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12555        &mut self,
12556        ranges: &[Range<T>],
12557        type_id: TypeId,
12558        auto_scroll: bool,
12559        cx: &mut Context<Self>,
12560    ) {
12561        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12562            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12563        });
12564    }
12565
12566    fn remove_folds_with<T: ToOffset + Clone>(
12567        &mut self,
12568        ranges: &[Range<T>],
12569        auto_scroll: bool,
12570        cx: &mut Context<Self>,
12571        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12572    ) {
12573        if ranges.is_empty() {
12574            return;
12575        }
12576
12577        let mut buffers_affected = HashSet::default();
12578        let multi_buffer = self.buffer().read(cx);
12579        for range in ranges {
12580            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12581                buffers_affected.insert(buffer.read(cx).remote_id());
12582            };
12583        }
12584
12585        self.display_map.update(cx, update);
12586
12587        if auto_scroll {
12588            self.request_autoscroll(Autoscroll::fit(), cx);
12589        }
12590
12591        cx.notify();
12592        self.scrollbar_marker_state.dirty = true;
12593        self.active_indent_guides_state.dirty = true;
12594    }
12595
12596    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12597        self.display_map.read(cx).fold_placeholder.clone()
12598    }
12599
12600    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12601        self.buffer.update(cx, |buffer, cx| {
12602            buffer.set_all_diff_hunks_expanded(cx);
12603        });
12604    }
12605
12606    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12607        self.distinguish_unstaged_diff_hunks = true;
12608    }
12609
12610    pub fn expand_all_diff_hunks(
12611        &mut self,
12612        _: &ExpandAllHunkDiffs,
12613        _window: &mut Window,
12614        cx: &mut Context<Self>,
12615    ) {
12616        self.buffer.update(cx, |buffer, cx| {
12617            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12618        });
12619    }
12620
12621    pub fn toggle_selected_diff_hunks(
12622        &mut self,
12623        _: &ToggleSelectedDiffHunks,
12624        _window: &mut Window,
12625        cx: &mut Context<Self>,
12626    ) {
12627        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12628        self.toggle_diff_hunks_in_ranges(ranges, cx);
12629    }
12630
12631    fn diff_hunks_in_ranges<'a>(
12632        &'a self,
12633        ranges: &'a [Range<Anchor>],
12634        buffer: &'a MultiBufferSnapshot,
12635    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12636        ranges.iter().flat_map(move |range| {
12637            let end_excerpt_id = range.end.excerpt_id;
12638            let range = range.to_point(buffer);
12639            let mut peek_end = range.end;
12640            if range.end.row < buffer.max_row().0 {
12641                peek_end = Point::new(range.end.row + 1, 0);
12642            }
12643            buffer
12644                .diff_hunks_in_range(range.start..peek_end)
12645                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12646        })
12647    }
12648
12649    pub fn has_stageable_diff_hunks_in_ranges(
12650        &self,
12651        ranges: &[Range<Anchor>],
12652        snapshot: &MultiBufferSnapshot,
12653    ) -> bool {
12654        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12655        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12656    }
12657
12658    pub fn toggle_staged_selected_diff_hunks(
12659        &mut self,
12660        _: &ToggleStagedSelectedDiffHunks,
12661        _window: &mut Window,
12662        cx: &mut Context<Self>,
12663    ) {
12664        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12665        self.stage_or_unstage_diff_hunks(&ranges, cx);
12666    }
12667
12668    pub fn stage_or_unstage_diff_hunks(
12669        &mut self,
12670        ranges: &[Range<Anchor>],
12671        cx: &mut Context<Self>,
12672    ) {
12673        let Some(project) = &self.project else {
12674            return;
12675        };
12676        let snapshot = self.buffer.read(cx).snapshot(cx);
12677        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12678
12679        let chunk_by = self
12680            .diff_hunks_in_ranges(&ranges, &snapshot)
12681            .chunk_by(|hunk| hunk.buffer_id);
12682        for (buffer_id, hunks) in &chunk_by {
12683            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12684                log::debug!("no buffer for id");
12685                continue;
12686            };
12687            let buffer = buffer.read(cx).snapshot();
12688            let Some((repo, path)) = project
12689                .read(cx)
12690                .repository_and_path_for_buffer_id(buffer_id, cx)
12691            else {
12692                log::debug!("no git repo for buffer id");
12693                continue;
12694            };
12695            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12696                log::debug!("no diff for buffer id");
12697                continue;
12698            };
12699            let Some(secondary_diff) = diff.secondary_diff() else {
12700                log::debug!("no secondary diff for buffer id");
12701                continue;
12702            };
12703
12704            let edits = diff.secondary_edits_for_stage_or_unstage(
12705                stage,
12706                hunks.map(|hunk| {
12707                    (
12708                        hunk.diff_base_byte_range.clone(),
12709                        hunk.secondary_diff_base_byte_range.clone(),
12710                        hunk.buffer_range.clone(),
12711                    )
12712                }),
12713                &buffer,
12714            );
12715
12716            let index_base = secondary_diff.base_text().map_or_else(
12717                || Rope::from(""),
12718                |snapshot| snapshot.text.as_rope().clone(),
12719            );
12720            let index_buffer = cx.new(|cx| {
12721                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12722            });
12723            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12724                index_buffer.edit(edits, None, cx);
12725                index_buffer.snapshot().as_rope().to_string()
12726            });
12727            let new_index_text = if new_index_text.is_empty()
12728                && (diff.is_single_insertion
12729                    || buffer
12730                        .file()
12731                        .map_or(false, |file| file.disk_state() == DiskState::New))
12732            {
12733                log::debug!("removing from index");
12734                None
12735            } else {
12736                Some(new_index_text)
12737            };
12738
12739            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12740        }
12741    }
12742
12743    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12744        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12745        self.buffer
12746            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12747    }
12748
12749    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12750        self.buffer.update(cx, |buffer, cx| {
12751            let ranges = vec![Anchor::min()..Anchor::max()];
12752            if !buffer.all_diff_hunks_expanded()
12753                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12754            {
12755                buffer.collapse_diff_hunks(ranges, cx);
12756                true
12757            } else {
12758                false
12759            }
12760        })
12761    }
12762
12763    fn toggle_diff_hunks_in_ranges(
12764        &mut self,
12765        ranges: Vec<Range<Anchor>>,
12766        cx: &mut Context<'_, Editor>,
12767    ) {
12768        self.buffer.update(cx, |buffer, cx| {
12769            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12770            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12771        })
12772    }
12773
12774    fn toggle_diff_hunks_in_ranges_narrow(
12775        &mut self,
12776        ranges: Vec<Range<Anchor>>,
12777        cx: &mut Context<'_, Editor>,
12778    ) {
12779        self.buffer.update(cx, |buffer, cx| {
12780            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12781            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12782        })
12783    }
12784
12785    pub(crate) fn apply_all_diff_hunks(
12786        &mut self,
12787        _: &ApplyAllDiffHunks,
12788        window: &mut Window,
12789        cx: &mut Context<Self>,
12790    ) {
12791        let buffers = self.buffer.read(cx).all_buffers();
12792        for branch_buffer in buffers {
12793            branch_buffer.update(cx, |branch_buffer, cx| {
12794                branch_buffer.merge_into_base(Vec::new(), cx);
12795            });
12796        }
12797
12798        if let Some(project) = self.project.clone() {
12799            self.save(true, project, window, cx).detach_and_log_err(cx);
12800        }
12801    }
12802
12803    pub(crate) fn apply_selected_diff_hunks(
12804        &mut self,
12805        _: &ApplyDiffHunk,
12806        window: &mut Window,
12807        cx: &mut Context<Self>,
12808    ) {
12809        let snapshot = self.snapshot(window, cx);
12810        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12811        let mut ranges_by_buffer = HashMap::default();
12812        self.transact(window, cx, |editor, _window, cx| {
12813            for hunk in hunks {
12814                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12815                    ranges_by_buffer
12816                        .entry(buffer.clone())
12817                        .or_insert_with(Vec::new)
12818                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12819                }
12820            }
12821
12822            for (buffer, ranges) in ranges_by_buffer {
12823                buffer.update(cx, |buffer, cx| {
12824                    buffer.merge_into_base(ranges, cx);
12825                });
12826            }
12827        });
12828
12829        if let Some(project) = self.project.clone() {
12830            self.save(true, project, window, cx).detach_and_log_err(cx);
12831        }
12832    }
12833
12834    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12835        if hovered != self.gutter_hovered {
12836            self.gutter_hovered = hovered;
12837            cx.notify();
12838        }
12839    }
12840
12841    pub fn insert_blocks(
12842        &mut self,
12843        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12844        autoscroll: Option<Autoscroll>,
12845        cx: &mut Context<Self>,
12846    ) -> Vec<CustomBlockId> {
12847        let blocks = self
12848            .display_map
12849            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12850        if let Some(autoscroll) = autoscroll {
12851            self.request_autoscroll(autoscroll, cx);
12852        }
12853        cx.notify();
12854        blocks
12855    }
12856
12857    pub fn resize_blocks(
12858        &mut self,
12859        heights: HashMap<CustomBlockId, u32>,
12860        autoscroll: Option<Autoscroll>,
12861        cx: &mut Context<Self>,
12862    ) {
12863        self.display_map
12864            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12865        if let Some(autoscroll) = autoscroll {
12866            self.request_autoscroll(autoscroll, cx);
12867        }
12868        cx.notify();
12869    }
12870
12871    pub fn replace_blocks(
12872        &mut self,
12873        renderers: HashMap<CustomBlockId, RenderBlock>,
12874        autoscroll: Option<Autoscroll>,
12875        cx: &mut Context<Self>,
12876    ) {
12877        self.display_map
12878            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12879        if let Some(autoscroll) = autoscroll {
12880            self.request_autoscroll(autoscroll, cx);
12881        }
12882        cx.notify();
12883    }
12884
12885    pub fn remove_blocks(
12886        &mut self,
12887        block_ids: HashSet<CustomBlockId>,
12888        autoscroll: Option<Autoscroll>,
12889        cx: &mut Context<Self>,
12890    ) {
12891        self.display_map.update(cx, |display_map, cx| {
12892            display_map.remove_blocks(block_ids, cx)
12893        });
12894        if let Some(autoscroll) = autoscroll {
12895            self.request_autoscroll(autoscroll, cx);
12896        }
12897        cx.notify();
12898    }
12899
12900    pub fn row_for_block(
12901        &self,
12902        block_id: CustomBlockId,
12903        cx: &mut Context<Self>,
12904    ) -> Option<DisplayRow> {
12905        self.display_map
12906            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12907    }
12908
12909    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12910        self.focused_block = Some(focused_block);
12911    }
12912
12913    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12914        self.focused_block.take()
12915    }
12916
12917    pub fn insert_creases(
12918        &mut self,
12919        creases: impl IntoIterator<Item = Crease<Anchor>>,
12920        cx: &mut Context<Self>,
12921    ) -> Vec<CreaseId> {
12922        self.display_map
12923            .update(cx, |map, cx| map.insert_creases(creases, cx))
12924    }
12925
12926    pub fn remove_creases(
12927        &mut self,
12928        ids: impl IntoIterator<Item = CreaseId>,
12929        cx: &mut Context<Self>,
12930    ) {
12931        self.display_map
12932            .update(cx, |map, cx| map.remove_creases(ids, cx));
12933    }
12934
12935    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12936        self.display_map
12937            .update(cx, |map, cx| map.snapshot(cx))
12938            .longest_row()
12939    }
12940
12941    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12942        self.display_map
12943            .update(cx, |map, cx| map.snapshot(cx))
12944            .max_point()
12945    }
12946
12947    pub fn text(&self, cx: &App) -> String {
12948        self.buffer.read(cx).read(cx).text()
12949    }
12950
12951    pub fn is_empty(&self, cx: &App) -> bool {
12952        self.buffer.read(cx).read(cx).is_empty()
12953    }
12954
12955    pub fn text_option(&self, cx: &App) -> Option<String> {
12956        let text = self.text(cx);
12957        let text = text.trim();
12958
12959        if text.is_empty() {
12960            return None;
12961        }
12962
12963        Some(text.to_string())
12964    }
12965
12966    pub fn set_text(
12967        &mut self,
12968        text: impl Into<Arc<str>>,
12969        window: &mut Window,
12970        cx: &mut Context<Self>,
12971    ) {
12972        self.transact(window, cx, |this, _, cx| {
12973            this.buffer
12974                .read(cx)
12975                .as_singleton()
12976                .expect("you can only call set_text on editors for singleton buffers")
12977                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12978        });
12979    }
12980
12981    pub fn display_text(&self, cx: &mut App) -> String {
12982        self.display_map
12983            .update(cx, |map, cx| map.snapshot(cx))
12984            .text()
12985    }
12986
12987    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12988        let mut wrap_guides = smallvec::smallvec![];
12989
12990        if self.show_wrap_guides == Some(false) {
12991            return wrap_guides;
12992        }
12993
12994        let settings = self.buffer.read(cx).settings_at(0, cx);
12995        if settings.show_wrap_guides {
12996            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12997                wrap_guides.push((soft_wrap as usize, true));
12998            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12999                wrap_guides.push((soft_wrap as usize, true));
13000            }
13001            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13002        }
13003
13004        wrap_guides
13005    }
13006
13007    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13008        let settings = self.buffer.read(cx).settings_at(0, cx);
13009        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13010        match mode {
13011            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13012                SoftWrap::None
13013            }
13014            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13015            language_settings::SoftWrap::PreferredLineLength => {
13016                SoftWrap::Column(settings.preferred_line_length)
13017            }
13018            language_settings::SoftWrap::Bounded => {
13019                SoftWrap::Bounded(settings.preferred_line_length)
13020            }
13021        }
13022    }
13023
13024    pub fn set_soft_wrap_mode(
13025        &mut self,
13026        mode: language_settings::SoftWrap,
13027
13028        cx: &mut Context<Self>,
13029    ) {
13030        self.soft_wrap_mode_override = Some(mode);
13031        cx.notify();
13032    }
13033
13034    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13035        self.text_style_refinement = Some(style);
13036    }
13037
13038    /// called by the Element so we know what style we were most recently rendered with.
13039    pub(crate) fn set_style(
13040        &mut self,
13041        style: EditorStyle,
13042        window: &mut Window,
13043        cx: &mut Context<Self>,
13044    ) {
13045        let rem_size = window.rem_size();
13046        self.display_map.update(cx, |map, cx| {
13047            map.set_font(
13048                style.text.font(),
13049                style.text.font_size.to_pixels(rem_size),
13050                cx,
13051            )
13052        });
13053        self.style = Some(style);
13054    }
13055
13056    pub fn style(&self) -> Option<&EditorStyle> {
13057        self.style.as_ref()
13058    }
13059
13060    // Called by the element. This method is not designed to be called outside of the editor
13061    // element's layout code because it does not notify when rewrapping is computed synchronously.
13062    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13063        self.display_map
13064            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13065    }
13066
13067    pub fn set_soft_wrap(&mut self) {
13068        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13069    }
13070
13071    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13072        if self.soft_wrap_mode_override.is_some() {
13073            self.soft_wrap_mode_override.take();
13074        } else {
13075            let soft_wrap = match self.soft_wrap_mode(cx) {
13076                SoftWrap::GitDiff => return,
13077                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13078                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13079                    language_settings::SoftWrap::None
13080                }
13081            };
13082            self.soft_wrap_mode_override = Some(soft_wrap);
13083        }
13084        cx.notify();
13085    }
13086
13087    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13088        let Some(workspace) = self.workspace() else {
13089            return;
13090        };
13091        let fs = workspace.read(cx).app_state().fs.clone();
13092        let current_show = TabBarSettings::get_global(cx).show;
13093        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13094            setting.show = Some(!current_show);
13095        });
13096    }
13097
13098    pub fn toggle_indent_guides(
13099        &mut self,
13100        _: &ToggleIndentGuides,
13101        _: &mut Window,
13102        cx: &mut Context<Self>,
13103    ) {
13104        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13105            self.buffer
13106                .read(cx)
13107                .settings_at(0, cx)
13108                .indent_guides
13109                .enabled
13110        });
13111        self.show_indent_guides = Some(!currently_enabled);
13112        cx.notify();
13113    }
13114
13115    fn should_show_indent_guides(&self) -> Option<bool> {
13116        self.show_indent_guides
13117    }
13118
13119    pub fn toggle_line_numbers(
13120        &mut self,
13121        _: &ToggleLineNumbers,
13122        _: &mut Window,
13123        cx: &mut Context<Self>,
13124    ) {
13125        let mut editor_settings = EditorSettings::get_global(cx).clone();
13126        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13127        EditorSettings::override_global(editor_settings, cx);
13128    }
13129
13130    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13131        self.use_relative_line_numbers
13132            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13133    }
13134
13135    pub fn toggle_relative_line_numbers(
13136        &mut self,
13137        _: &ToggleRelativeLineNumbers,
13138        _: &mut Window,
13139        cx: &mut Context<Self>,
13140    ) {
13141        let is_relative = self.should_use_relative_line_numbers(cx);
13142        self.set_relative_line_number(Some(!is_relative), cx)
13143    }
13144
13145    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13146        self.use_relative_line_numbers = is_relative;
13147        cx.notify();
13148    }
13149
13150    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13151        self.show_gutter = show_gutter;
13152        cx.notify();
13153    }
13154
13155    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13156        self.show_scrollbars = show_scrollbars;
13157        cx.notify();
13158    }
13159
13160    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13161        self.show_line_numbers = Some(show_line_numbers);
13162        cx.notify();
13163    }
13164
13165    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13166        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13167        cx.notify();
13168    }
13169
13170    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13171        self.show_code_actions = Some(show_code_actions);
13172        cx.notify();
13173    }
13174
13175    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13176        self.show_runnables = Some(show_runnables);
13177        cx.notify();
13178    }
13179
13180    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13181        if self.display_map.read(cx).masked != masked {
13182            self.display_map.update(cx, |map, _| map.masked = masked);
13183        }
13184        cx.notify()
13185    }
13186
13187    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13188        self.show_wrap_guides = Some(show_wrap_guides);
13189        cx.notify();
13190    }
13191
13192    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13193        self.show_indent_guides = Some(show_indent_guides);
13194        cx.notify();
13195    }
13196
13197    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13198        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13199            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13200                if let Some(dir) = file.abs_path(cx).parent() {
13201                    return Some(dir.to_owned());
13202                }
13203            }
13204
13205            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13206                return Some(project_path.path.to_path_buf());
13207            }
13208        }
13209
13210        None
13211    }
13212
13213    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13214        self.active_excerpt(cx)?
13215            .1
13216            .read(cx)
13217            .file()
13218            .and_then(|f| f.as_local())
13219    }
13220
13221    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13222        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13223            let buffer = buffer.read(cx);
13224            if let Some(project_path) = buffer.project_path(cx) {
13225                let project = self.project.as_ref()?.read(cx);
13226                project.absolute_path(&project_path, cx)
13227            } else {
13228                buffer
13229                    .file()
13230                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13231            }
13232        })
13233    }
13234
13235    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13236        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13237            let project_path = buffer.read(cx).project_path(cx)?;
13238            let project = self.project.as_ref()?.read(cx);
13239            let entry = project.entry_for_path(&project_path, cx)?;
13240            let path = entry.path.to_path_buf();
13241            Some(path)
13242        })
13243    }
13244
13245    pub fn reveal_in_finder(
13246        &mut self,
13247        _: &RevealInFileManager,
13248        _window: &mut Window,
13249        cx: &mut Context<Self>,
13250    ) {
13251        if let Some(target) = self.target_file(cx) {
13252            cx.reveal_path(&target.abs_path(cx));
13253        }
13254    }
13255
13256    pub fn copy_path(
13257        &mut self,
13258        _: &zed_actions::workspace::CopyPath,
13259        _window: &mut Window,
13260        cx: &mut Context<Self>,
13261    ) {
13262        if let Some(path) = self.target_file_abs_path(cx) {
13263            if let Some(path) = path.to_str() {
13264                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13265            }
13266        }
13267    }
13268
13269    pub fn copy_relative_path(
13270        &mut self,
13271        _: &zed_actions::workspace::CopyRelativePath,
13272        _window: &mut Window,
13273        cx: &mut Context<Self>,
13274    ) {
13275        if let Some(path) = self.target_file_path(cx) {
13276            if let Some(path) = path.to_str() {
13277                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13278            }
13279        }
13280    }
13281
13282    pub fn copy_file_name_without_extension(
13283        &mut self,
13284        _: &CopyFileNameWithoutExtension,
13285        _: &mut Window,
13286        cx: &mut Context<Self>,
13287    ) {
13288        if let Some(file) = self.target_file(cx) {
13289            if let Some(file_stem) = file.path().file_stem() {
13290                if let Some(name) = file_stem.to_str() {
13291                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13292                }
13293            }
13294        }
13295    }
13296
13297    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13298        if let Some(file) = self.target_file(cx) {
13299            if let Some(file_name) = file.path().file_name() {
13300                if let Some(name) = file_name.to_str() {
13301                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13302                }
13303            }
13304        }
13305    }
13306
13307    pub fn toggle_git_blame(
13308        &mut self,
13309        _: &ToggleGitBlame,
13310        window: &mut Window,
13311        cx: &mut Context<Self>,
13312    ) {
13313        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13314
13315        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13316            self.start_git_blame(true, window, cx);
13317        }
13318
13319        cx.notify();
13320    }
13321
13322    pub fn toggle_git_blame_inline(
13323        &mut self,
13324        _: &ToggleGitBlameInline,
13325        window: &mut Window,
13326        cx: &mut Context<Self>,
13327    ) {
13328        self.toggle_git_blame_inline_internal(true, window, cx);
13329        cx.notify();
13330    }
13331
13332    pub fn git_blame_inline_enabled(&self) -> bool {
13333        self.git_blame_inline_enabled
13334    }
13335
13336    pub fn toggle_selection_menu(
13337        &mut self,
13338        _: &ToggleSelectionMenu,
13339        _: &mut Window,
13340        cx: &mut Context<Self>,
13341    ) {
13342        self.show_selection_menu = self
13343            .show_selection_menu
13344            .map(|show_selections_menu| !show_selections_menu)
13345            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13346
13347        cx.notify();
13348    }
13349
13350    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13351        self.show_selection_menu
13352            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13353    }
13354
13355    fn start_git_blame(
13356        &mut self,
13357        user_triggered: bool,
13358        window: &mut Window,
13359        cx: &mut Context<Self>,
13360    ) {
13361        if let Some(project) = self.project.as_ref() {
13362            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13363                return;
13364            };
13365
13366            if buffer.read(cx).file().is_none() {
13367                return;
13368            }
13369
13370            let focused = self.focus_handle(cx).contains_focused(window, cx);
13371
13372            let project = project.clone();
13373            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13374            self.blame_subscription =
13375                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13376            self.blame = Some(blame);
13377        }
13378    }
13379
13380    fn toggle_git_blame_inline_internal(
13381        &mut self,
13382        user_triggered: bool,
13383        window: &mut Window,
13384        cx: &mut Context<Self>,
13385    ) {
13386        if self.git_blame_inline_enabled {
13387            self.git_blame_inline_enabled = false;
13388            self.show_git_blame_inline = false;
13389            self.show_git_blame_inline_delay_task.take();
13390        } else {
13391            self.git_blame_inline_enabled = true;
13392            self.start_git_blame_inline(user_triggered, window, cx);
13393        }
13394
13395        cx.notify();
13396    }
13397
13398    fn start_git_blame_inline(
13399        &mut self,
13400        user_triggered: bool,
13401        window: &mut Window,
13402        cx: &mut Context<Self>,
13403    ) {
13404        self.start_git_blame(user_triggered, window, cx);
13405
13406        if ProjectSettings::get_global(cx)
13407            .git
13408            .inline_blame_delay()
13409            .is_some()
13410        {
13411            self.start_inline_blame_timer(window, cx);
13412        } else {
13413            self.show_git_blame_inline = true
13414        }
13415    }
13416
13417    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13418        self.blame.as_ref()
13419    }
13420
13421    pub fn show_git_blame_gutter(&self) -> bool {
13422        self.show_git_blame_gutter
13423    }
13424
13425    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13426        self.show_git_blame_gutter && self.has_blame_entries(cx)
13427    }
13428
13429    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13430        self.show_git_blame_inline
13431            && self.focus_handle.is_focused(window)
13432            && !self.newest_selection_head_on_empty_line(cx)
13433            && self.has_blame_entries(cx)
13434    }
13435
13436    fn has_blame_entries(&self, cx: &App) -> bool {
13437        self.blame()
13438            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13439    }
13440
13441    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13442        let cursor_anchor = self.selections.newest_anchor().head();
13443
13444        let snapshot = self.buffer.read(cx).snapshot(cx);
13445        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13446
13447        snapshot.line_len(buffer_row) == 0
13448    }
13449
13450    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13451        let buffer_and_selection = maybe!({
13452            let selection = self.selections.newest::<Point>(cx);
13453            let selection_range = selection.range();
13454
13455            let multi_buffer = self.buffer().read(cx);
13456            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13457            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13458
13459            let (buffer, range, _) = if selection.reversed {
13460                buffer_ranges.first()
13461            } else {
13462                buffer_ranges.last()
13463            }?;
13464
13465            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13466                ..text::ToPoint::to_point(&range.end, &buffer).row;
13467            Some((
13468                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13469                selection,
13470            ))
13471        });
13472
13473        let Some((buffer, selection)) = buffer_and_selection else {
13474            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13475        };
13476
13477        let Some(project) = self.project.as_ref() else {
13478            return Task::ready(Err(anyhow!("editor does not have project")));
13479        };
13480
13481        project.update(cx, |project, cx| {
13482            project.get_permalink_to_line(&buffer, selection, cx)
13483        })
13484    }
13485
13486    pub fn copy_permalink_to_line(
13487        &mut self,
13488        _: &CopyPermalinkToLine,
13489        window: &mut Window,
13490        cx: &mut Context<Self>,
13491    ) {
13492        let permalink_task = self.get_permalink_to_line(cx);
13493        let workspace = self.workspace();
13494
13495        cx.spawn_in(window, |_, mut cx| async move {
13496            match permalink_task.await {
13497                Ok(permalink) => {
13498                    cx.update(|_, cx| {
13499                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13500                    })
13501                    .ok();
13502                }
13503                Err(err) => {
13504                    let message = format!("Failed to copy permalink: {err}");
13505
13506                    Err::<(), anyhow::Error>(err).log_err();
13507
13508                    if let Some(workspace) = workspace {
13509                        workspace
13510                            .update_in(&mut cx, |workspace, _, cx| {
13511                                struct CopyPermalinkToLine;
13512
13513                                workspace.show_toast(
13514                                    Toast::new(
13515                                        NotificationId::unique::<CopyPermalinkToLine>(),
13516                                        message,
13517                                    ),
13518                                    cx,
13519                                )
13520                            })
13521                            .ok();
13522                    }
13523                }
13524            }
13525        })
13526        .detach();
13527    }
13528
13529    pub fn copy_file_location(
13530        &mut self,
13531        _: &CopyFileLocation,
13532        _: &mut Window,
13533        cx: &mut Context<Self>,
13534    ) {
13535        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13536        if let Some(file) = self.target_file(cx) {
13537            if let Some(path) = file.path().to_str() {
13538                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13539            }
13540        }
13541    }
13542
13543    pub fn open_permalink_to_line(
13544        &mut self,
13545        _: &OpenPermalinkToLine,
13546        window: &mut Window,
13547        cx: &mut Context<Self>,
13548    ) {
13549        let permalink_task = self.get_permalink_to_line(cx);
13550        let workspace = self.workspace();
13551
13552        cx.spawn_in(window, |_, mut cx| async move {
13553            match permalink_task.await {
13554                Ok(permalink) => {
13555                    cx.update(|_, cx| {
13556                        cx.open_url(permalink.as_ref());
13557                    })
13558                    .ok();
13559                }
13560                Err(err) => {
13561                    let message = format!("Failed to open permalink: {err}");
13562
13563                    Err::<(), anyhow::Error>(err).log_err();
13564
13565                    if let Some(workspace) = workspace {
13566                        workspace
13567                            .update(&mut cx, |workspace, cx| {
13568                                struct OpenPermalinkToLine;
13569
13570                                workspace.show_toast(
13571                                    Toast::new(
13572                                        NotificationId::unique::<OpenPermalinkToLine>(),
13573                                        message,
13574                                    ),
13575                                    cx,
13576                                )
13577                            })
13578                            .ok();
13579                    }
13580                }
13581            }
13582        })
13583        .detach();
13584    }
13585
13586    pub fn insert_uuid_v4(
13587        &mut self,
13588        _: &InsertUuidV4,
13589        window: &mut Window,
13590        cx: &mut Context<Self>,
13591    ) {
13592        self.insert_uuid(UuidVersion::V4, window, cx);
13593    }
13594
13595    pub fn insert_uuid_v7(
13596        &mut self,
13597        _: &InsertUuidV7,
13598        window: &mut Window,
13599        cx: &mut Context<Self>,
13600    ) {
13601        self.insert_uuid(UuidVersion::V7, window, cx);
13602    }
13603
13604    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13605        self.transact(window, cx, |this, window, cx| {
13606            let edits = this
13607                .selections
13608                .all::<Point>(cx)
13609                .into_iter()
13610                .map(|selection| {
13611                    let uuid = match version {
13612                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13613                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13614                    };
13615
13616                    (selection.range(), uuid.to_string())
13617                });
13618            this.edit(edits, cx);
13619            this.refresh_inline_completion(true, false, window, cx);
13620        });
13621    }
13622
13623    pub fn open_selections_in_multibuffer(
13624        &mut self,
13625        _: &OpenSelectionsInMultibuffer,
13626        window: &mut Window,
13627        cx: &mut Context<Self>,
13628    ) {
13629        let multibuffer = self.buffer.read(cx);
13630
13631        let Some(buffer) = multibuffer.as_singleton() else {
13632            return;
13633        };
13634
13635        let Some(workspace) = self.workspace() else {
13636            return;
13637        };
13638
13639        let locations = self
13640            .selections
13641            .disjoint_anchors()
13642            .iter()
13643            .map(|range| Location {
13644                buffer: buffer.clone(),
13645                range: range.start.text_anchor..range.end.text_anchor,
13646            })
13647            .collect::<Vec<_>>();
13648
13649        let title = multibuffer.title(cx).to_string();
13650
13651        cx.spawn_in(window, |_, mut cx| async move {
13652            workspace.update_in(&mut cx, |workspace, window, cx| {
13653                Self::open_locations_in_multibuffer(
13654                    workspace,
13655                    locations,
13656                    format!("Selections for '{title}'"),
13657                    false,
13658                    MultibufferSelectionMode::All,
13659                    window,
13660                    cx,
13661                );
13662            })
13663        })
13664        .detach();
13665    }
13666
13667    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13668    /// last highlight added will be used.
13669    ///
13670    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13671    pub fn highlight_rows<T: 'static>(
13672        &mut self,
13673        range: Range<Anchor>,
13674        color: Hsla,
13675        should_autoscroll: bool,
13676        cx: &mut Context<Self>,
13677    ) {
13678        let snapshot = self.buffer().read(cx).snapshot(cx);
13679        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13680        let ix = row_highlights.binary_search_by(|highlight| {
13681            Ordering::Equal
13682                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13683                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13684        });
13685
13686        if let Err(mut ix) = ix {
13687            let index = post_inc(&mut self.highlight_order);
13688
13689            // If this range intersects with the preceding highlight, then merge it with
13690            // the preceding highlight. Otherwise insert a new highlight.
13691            let mut merged = false;
13692            if ix > 0 {
13693                let prev_highlight = &mut row_highlights[ix - 1];
13694                if prev_highlight
13695                    .range
13696                    .end
13697                    .cmp(&range.start, &snapshot)
13698                    .is_ge()
13699                {
13700                    ix -= 1;
13701                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13702                        prev_highlight.range.end = range.end;
13703                    }
13704                    merged = true;
13705                    prev_highlight.index = index;
13706                    prev_highlight.color = color;
13707                    prev_highlight.should_autoscroll = should_autoscroll;
13708                }
13709            }
13710
13711            if !merged {
13712                row_highlights.insert(
13713                    ix,
13714                    RowHighlight {
13715                        range: range.clone(),
13716                        index,
13717                        color,
13718                        should_autoscroll,
13719                    },
13720                );
13721            }
13722
13723            // If any of the following highlights intersect with this one, merge them.
13724            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13725                let highlight = &row_highlights[ix];
13726                if next_highlight
13727                    .range
13728                    .start
13729                    .cmp(&highlight.range.end, &snapshot)
13730                    .is_le()
13731                {
13732                    if next_highlight
13733                        .range
13734                        .end
13735                        .cmp(&highlight.range.end, &snapshot)
13736                        .is_gt()
13737                    {
13738                        row_highlights[ix].range.end = next_highlight.range.end;
13739                    }
13740                    row_highlights.remove(ix + 1);
13741                } else {
13742                    break;
13743                }
13744            }
13745        }
13746    }
13747
13748    /// Remove any highlighted row ranges of the given type that intersect the
13749    /// given ranges.
13750    pub fn remove_highlighted_rows<T: 'static>(
13751        &mut self,
13752        ranges_to_remove: Vec<Range<Anchor>>,
13753        cx: &mut Context<Self>,
13754    ) {
13755        let snapshot = self.buffer().read(cx).snapshot(cx);
13756        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13757        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13758        row_highlights.retain(|highlight| {
13759            while let Some(range_to_remove) = ranges_to_remove.peek() {
13760                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13761                    Ordering::Less | Ordering::Equal => {
13762                        ranges_to_remove.next();
13763                    }
13764                    Ordering::Greater => {
13765                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13766                            Ordering::Less | Ordering::Equal => {
13767                                return false;
13768                            }
13769                            Ordering::Greater => break,
13770                        }
13771                    }
13772                }
13773            }
13774
13775            true
13776        })
13777    }
13778
13779    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13780    pub fn clear_row_highlights<T: 'static>(&mut self) {
13781        self.highlighted_rows.remove(&TypeId::of::<T>());
13782    }
13783
13784    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13785    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13786        self.highlighted_rows
13787            .get(&TypeId::of::<T>())
13788            .map_or(&[] as &[_], |vec| vec.as_slice())
13789            .iter()
13790            .map(|highlight| (highlight.range.clone(), highlight.color))
13791    }
13792
13793    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13794    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13795    /// Allows to ignore certain kinds of highlights.
13796    pub fn highlighted_display_rows(
13797        &self,
13798        window: &mut Window,
13799        cx: &mut App,
13800    ) -> BTreeMap<DisplayRow, Background> {
13801        let snapshot = self.snapshot(window, cx);
13802        let mut used_highlight_orders = HashMap::default();
13803        self.highlighted_rows
13804            .iter()
13805            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13806            .fold(
13807                BTreeMap::<DisplayRow, Background>::new(),
13808                |mut unique_rows, highlight| {
13809                    let start = highlight.range.start.to_display_point(&snapshot);
13810                    let end = highlight.range.end.to_display_point(&snapshot);
13811                    let start_row = start.row().0;
13812                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13813                        && end.column() == 0
13814                    {
13815                        end.row().0.saturating_sub(1)
13816                    } else {
13817                        end.row().0
13818                    };
13819                    for row in start_row..=end_row {
13820                        let used_index =
13821                            used_highlight_orders.entry(row).or_insert(highlight.index);
13822                        if highlight.index >= *used_index {
13823                            *used_index = highlight.index;
13824                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13825                        }
13826                    }
13827                    unique_rows
13828                },
13829            )
13830    }
13831
13832    pub fn highlighted_display_row_for_autoscroll(
13833        &self,
13834        snapshot: &DisplaySnapshot,
13835    ) -> Option<DisplayRow> {
13836        self.highlighted_rows
13837            .values()
13838            .flat_map(|highlighted_rows| highlighted_rows.iter())
13839            .filter_map(|highlight| {
13840                if highlight.should_autoscroll {
13841                    Some(highlight.range.start.to_display_point(snapshot).row())
13842                } else {
13843                    None
13844                }
13845            })
13846            .min()
13847    }
13848
13849    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13850        self.highlight_background::<SearchWithinRange>(
13851            ranges,
13852            |colors| colors.editor_document_highlight_read_background,
13853            cx,
13854        )
13855    }
13856
13857    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13858        self.breadcrumb_header = Some(new_header);
13859    }
13860
13861    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13862        self.clear_background_highlights::<SearchWithinRange>(cx);
13863    }
13864
13865    pub fn highlight_background<T: 'static>(
13866        &mut self,
13867        ranges: &[Range<Anchor>],
13868        color_fetcher: fn(&ThemeColors) -> Hsla,
13869        cx: &mut Context<Self>,
13870    ) {
13871        self.background_highlights
13872            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13873        self.scrollbar_marker_state.dirty = true;
13874        cx.notify();
13875    }
13876
13877    pub fn clear_background_highlights<T: 'static>(
13878        &mut self,
13879        cx: &mut Context<Self>,
13880    ) -> Option<BackgroundHighlight> {
13881        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13882        if !text_highlights.1.is_empty() {
13883            self.scrollbar_marker_state.dirty = true;
13884            cx.notify();
13885        }
13886        Some(text_highlights)
13887    }
13888
13889    pub fn highlight_gutter<T: 'static>(
13890        &mut self,
13891        ranges: &[Range<Anchor>],
13892        color_fetcher: fn(&App) -> Hsla,
13893        cx: &mut Context<Self>,
13894    ) {
13895        self.gutter_highlights
13896            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13897        cx.notify();
13898    }
13899
13900    pub fn clear_gutter_highlights<T: 'static>(
13901        &mut self,
13902        cx: &mut Context<Self>,
13903    ) -> Option<GutterHighlight> {
13904        cx.notify();
13905        self.gutter_highlights.remove(&TypeId::of::<T>())
13906    }
13907
13908    #[cfg(feature = "test-support")]
13909    pub fn all_text_background_highlights(
13910        &self,
13911        window: &mut Window,
13912        cx: &mut Context<Self>,
13913    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13914        let snapshot = self.snapshot(window, cx);
13915        let buffer = &snapshot.buffer_snapshot;
13916        let start = buffer.anchor_before(0);
13917        let end = buffer.anchor_after(buffer.len());
13918        let theme = cx.theme().colors();
13919        self.background_highlights_in_range(start..end, &snapshot, theme)
13920    }
13921
13922    #[cfg(feature = "test-support")]
13923    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13924        let snapshot = self.buffer().read(cx).snapshot(cx);
13925
13926        let highlights = self
13927            .background_highlights
13928            .get(&TypeId::of::<items::BufferSearchHighlights>());
13929
13930        if let Some((_color, ranges)) = highlights {
13931            ranges
13932                .iter()
13933                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13934                .collect_vec()
13935        } else {
13936            vec![]
13937        }
13938    }
13939
13940    fn document_highlights_for_position<'a>(
13941        &'a self,
13942        position: Anchor,
13943        buffer: &'a MultiBufferSnapshot,
13944    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13945        let read_highlights = self
13946            .background_highlights
13947            .get(&TypeId::of::<DocumentHighlightRead>())
13948            .map(|h| &h.1);
13949        let write_highlights = self
13950            .background_highlights
13951            .get(&TypeId::of::<DocumentHighlightWrite>())
13952            .map(|h| &h.1);
13953        let left_position = position.bias_left(buffer);
13954        let right_position = position.bias_right(buffer);
13955        read_highlights
13956            .into_iter()
13957            .chain(write_highlights)
13958            .flat_map(move |ranges| {
13959                let start_ix = match ranges.binary_search_by(|probe| {
13960                    let cmp = probe.end.cmp(&left_position, buffer);
13961                    if cmp.is_ge() {
13962                        Ordering::Greater
13963                    } else {
13964                        Ordering::Less
13965                    }
13966                }) {
13967                    Ok(i) | Err(i) => i,
13968                };
13969
13970                ranges[start_ix..]
13971                    .iter()
13972                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13973            })
13974    }
13975
13976    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13977        self.background_highlights
13978            .get(&TypeId::of::<T>())
13979            .map_or(false, |(_, highlights)| !highlights.is_empty())
13980    }
13981
13982    pub fn background_highlights_in_range(
13983        &self,
13984        search_range: Range<Anchor>,
13985        display_snapshot: &DisplaySnapshot,
13986        theme: &ThemeColors,
13987    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13988        let mut results = Vec::new();
13989        for (color_fetcher, ranges) in self.background_highlights.values() {
13990            let color = color_fetcher(theme);
13991            let start_ix = match ranges.binary_search_by(|probe| {
13992                let cmp = probe
13993                    .end
13994                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13995                if cmp.is_gt() {
13996                    Ordering::Greater
13997                } else {
13998                    Ordering::Less
13999                }
14000            }) {
14001                Ok(i) | Err(i) => i,
14002            };
14003            for range in &ranges[start_ix..] {
14004                if range
14005                    .start
14006                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14007                    .is_ge()
14008                {
14009                    break;
14010                }
14011
14012                let start = range.start.to_display_point(display_snapshot);
14013                let end = range.end.to_display_point(display_snapshot);
14014                results.push((start..end, color))
14015            }
14016        }
14017        results
14018    }
14019
14020    pub fn background_highlight_row_ranges<T: 'static>(
14021        &self,
14022        search_range: Range<Anchor>,
14023        display_snapshot: &DisplaySnapshot,
14024        count: usize,
14025    ) -> Vec<RangeInclusive<DisplayPoint>> {
14026        let mut results = Vec::new();
14027        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14028            return vec![];
14029        };
14030
14031        let start_ix = match ranges.binary_search_by(|probe| {
14032            let cmp = probe
14033                .end
14034                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14035            if cmp.is_gt() {
14036                Ordering::Greater
14037            } else {
14038                Ordering::Less
14039            }
14040        }) {
14041            Ok(i) | Err(i) => i,
14042        };
14043        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14044            if let (Some(start_display), Some(end_display)) = (start, end) {
14045                results.push(
14046                    start_display.to_display_point(display_snapshot)
14047                        ..=end_display.to_display_point(display_snapshot),
14048                );
14049            }
14050        };
14051        let mut start_row: Option<Point> = None;
14052        let mut end_row: Option<Point> = None;
14053        if ranges.len() > count {
14054            return Vec::new();
14055        }
14056        for range in &ranges[start_ix..] {
14057            if range
14058                .start
14059                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14060                .is_ge()
14061            {
14062                break;
14063            }
14064            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14065            if let Some(current_row) = &end_row {
14066                if end.row == current_row.row {
14067                    continue;
14068                }
14069            }
14070            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14071            if start_row.is_none() {
14072                assert_eq!(end_row, None);
14073                start_row = Some(start);
14074                end_row = Some(end);
14075                continue;
14076            }
14077            if let Some(current_end) = end_row.as_mut() {
14078                if start.row > current_end.row + 1 {
14079                    push_region(start_row, end_row);
14080                    start_row = Some(start);
14081                    end_row = Some(end);
14082                } else {
14083                    // Merge two hunks.
14084                    *current_end = end;
14085                }
14086            } else {
14087                unreachable!();
14088            }
14089        }
14090        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14091        push_region(start_row, end_row);
14092        results
14093    }
14094
14095    pub fn gutter_highlights_in_range(
14096        &self,
14097        search_range: Range<Anchor>,
14098        display_snapshot: &DisplaySnapshot,
14099        cx: &App,
14100    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14101        let mut results = Vec::new();
14102        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14103            let color = color_fetcher(cx);
14104            let start_ix = match ranges.binary_search_by(|probe| {
14105                let cmp = probe
14106                    .end
14107                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14108                if cmp.is_gt() {
14109                    Ordering::Greater
14110                } else {
14111                    Ordering::Less
14112                }
14113            }) {
14114                Ok(i) | Err(i) => i,
14115            };
14116            for range in &ranges[start_ix..] {
14117                if range
14118                    .start
14119                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14120                    .is_ge()
14121                {
14122                    break;
14123                }
14124
14125                let start = range.start.to_display_point(display_snapshot);
14126                let end = range.end.to_display_point(display_snapshot);
14127                results.push((start..end, color))
14128            }
14129        }
14130        results
14131    }
14132
14133    /// Get the text ranges corresponding to the redaction query
14134    pub fn redacted_ranges(
14135        &self,
14136        search_range: Range<Anchor>,
14137        display_snapshot: &DisplaySnapshot,
14138        cx: &App,
14139    ) -> Vec<Range<DisplayPoint>> {
14140        display_snapshot
14141            .buffer_snapshot
14142            .redacted_ranges(search_range, |file| {
14143                if let Some(file) = file {
14144                    file.is_private()
14145                        && EditorSettings::get(
14146                            Some(SettingsLocation {
14147                                worktree_id: file.worktree_id(cx),
14148                                path: file.path().as_ref(),
14149                            }),
14150                            cx,
14151                        )
14152                        .redact_private_values
14153                } else {
14154                    false
14155                }
14156            })
14157            .map(|range| {
14158                range.start.to_display_point(display_snapshot)
14159                    ..range.end.to_display_point(display_snapshot)
14160            })
14161            .collect()
14162    }
14163
14164    pub fn highlight_text<T: 'static>(
14165        &mut self,
14166        ranges: Vec<Range<Anchor>>,
14167        style: HighlightStyle,
14168        cx: &mut Context<Self>,
14169    ) {
14170        self.display_map.update(cx, |map, _| {
14171            map.highlight_text(TypeId::of::<T>(), ranges, style)
14172        });
14173        cx.notify();
14174    }
14175
14176    pub(crate) fn highlight_inlays<T: 'static>(
14177        &mut self,
14178        highlights: Vec<InlayHighlight>,
14179        style: HighlightStyle,
14180        cx: &mut Context<Self>,
14181    ) {
14182        self.display_map.update(cx, |map, _| {
14183            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14184        });
14185        cx.notify();
14186    }
14187
14188    pub fn text_highlights<'a, T: 'static>(
14189        &'a self,
14190        cx: &'a App,
14191    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14192        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14193    }
14194
14195    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14196        let cleared = self
14197            .display_map
14198            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14199        if cleared {
14200            cx.notify();
14201        }
14202    }
14203
14204    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14205        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14206            && self.focus_handle.is_focused(window)
14207    }
14208
14209    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14210        self.show_cursor_when_unfocused = is_enabled;
14211        cx.notify();
14212    }
14213
14214    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14215        cx.notify();
14216    }
14217
14218    fn on_buffer_event(
14219        &mut self,
14220        multibuffer: &Entity<MultiBuffer>,
14221        event: &multi_buffer::Event,
14222        window: &mut Window,
14223        cx: &mut Context<Self>,
14224    ) {
14225        match event {
14226            multi_buffer::Event::Edited {
14227                singleton_buffer_edited,
14228                edited_buffer: buffer_edited,
14229            } => {
14230                self.scrollbar_marker_state.dirty = true;
14231                self.active_indent_guides_state.dirty = true;
14232                self.refresh_active_diagnostics(cx);
14233                self.refresh_code_actions(window, cx);
14234                if self.has_active_inline_completion() {
14235                    self.update_visible_inline_completion(window, cx);
14236                }
14237                if let Some(buffer) = buffer_edited {
14238                    let buffer_id = buffer.read(cx).remote_id();
14239                    if !self.registered_buffers.contains_key(&buffer_id) {
14240                        if let Some(project) = self.project.as_ref() {
14241                            project.update(cx, |project, cx| {
14242                                self.registered_buffers.insert(
14243                                    buffer_id,
14244                                    project.register_buffer_with_language_servers(&buffer, cx),
14245                                );
14246                            })
14247                        }
14248                    }
14249                }
14250                cx.emit(EditorEvent::BufferEdited);
14251                cx.emit(SearchEvent::MatchesInvalidated);
14252                if *singleton_buffer_edited {
14253                    if let Some(project) = &self.project {
14254                        #[allow(clippy::mutable_key_type)]
14255                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14256                            multibuffer
14257                                .all_buffers()
14258                                .into_iter()
14259                                .filter_map(|buffer| {
14260                                    buffer.update(cx, |buffer, cx| {
14261                                        let language = buffer.language()?;
14262                                        let should_discard = project.update(cx, |project, cx| {
14263                                            project.is_local()
14264                                                && !project.has_language_servers_for(buffer, cx)
14265                                        });
14266                                        should_discard.not().then_some(language.clone())
14267                                    })
14268                                })
14269                                .collect::<HashSet<_>>()
14270                        });
14271                        if !languages_affected.is_empty() {
14272                            self.refresh_inlay_hints(
14273                                InlayHintRefreshReason::BufferEdited(languages_affected),
14274                                cx,
14275                            );
14276                        }
14277                    }
14278                }
14279
14280                let Some(project) = &self.project else { return };
14281                let (telemetry, is_via_ssh) = {
14282                    let project = project.read(cx);
14283                    let telemetry = project.client().telemetry().clone();
14284                    let is_via_ssh = project.is_via_ssh();
14285                    (telemetry, is_via_ssh)
14286                };
14287                refresh_linked_ranges(self, window, cx);
14288                telemetry.log_edit_event("editor", is_via_ssh);
14289            }
14290            multi_buffer::Event::ExcerptsAdded {
14291                buffer,
14292                predecessor,
14293                excerpts,
14294            } => {
14295                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14296                let buffer_id = buffer.read(cx).remote_id();
14297                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14298                    if let Some(project) = &self.project {
14299                        get_uncommitted_diff_for_buffer(
14300                            project,
14301                            [buffer.clone()],
14302                            self.buffer.clone(),
14303                            cx,
14304                        )
14305                        .detach();
14306                    }
14307                }
14308                cx.emit(EditorEvent::ExcerptsAdded {
14309                    buffer: buffer.clone(),
14310                    predecessor: *predecessor,
14311                    excerpts: excerpts.clone(),
14312                });
14313                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14314            }
14315            multi_buffer::Event::ExcerptsRemoved { ids } => {
14316                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14317                let buffer = self.buffer.read(cx);
14318                self.registered_buffers
14319                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14320                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14321            }
14322            multi_buffer::Event::ExcerptsEdited { ids } => {
14323                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14324            }
14325            multi_buffer::Event::ExcerptsExpanded { ids } => {
14326                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14327                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14328            }
14329            multi_buffer::Event::Reparsed(buffer_id) => {
14330                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14331
14332                cx.emit(EditorEvent::Reparsed(*buffer_id));
14333            }
14334            multi_buffer::Event::DiffHunksToggled => {
14335                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14336            }
14337            multi_buffer::Event::LanguageChanged(buffer_id) => {
14338                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14339                cx.emit(EditorEvent::Reparsed(*buffer_id));
14340                cx.notify();
14341            }
14342            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14343            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14344            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14345                cx.emit(EditorEvent::TitleChanged)
14346            }
14347            // multi_buffer::Event::DiffBaseChanged => {
14348            //     self.scrollbar_marker_state.dirty = true;
14349            //     cx.emit(EditorEvent::DiffBaseChanged);
14350            //     cx.notify();
14351            // }
14352            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14353            multi_buffer::Event::DiagnosticsUpdated => {
14354                self.refresh_active_diagnostics(cx);
14355                self.scrollbar_marker_state.dirty = true;
14356                cx.notify();
14357            }
14358            _ => {}
14359        };
14360    }
14361
14362    fn on_display_map_changed(
14363        &mut self,
14364        _: Entity<DisplayMap>,
14365        _: &mut Window,
14366        cx: &mut Context<Self>,
14367    ) {
14368        cx.notify();
14369    }
14370
14371    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14372        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14373        self.refresh_inline_completion(true, false, window, cx);
14374        self.refresh_inlay_hints(
14375            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14376                self.selections.newest_anchor().head(),
14377                &self.buffer.read(cx).snapshot(cx),
14378                cx,
14379            )),
14380            cx,
14381        );
14382
14383        let old_cursor_shape = self.cursor_shape;
14384
14385        {
14386            let editor_settings = EditorSettings::get_global(cx);
14387            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14388            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14389            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14390        }
14391
14392        if old_cursor_shape != self.cursor_shape {
14393            cx.emit(EditorEvent::CursorShapeChanged);
14394        }
14395
14396        let project_settings = ProjectSettings::get_global(cx);
14397        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14398
14399        if self.mode == EditorMode::Full {
14400            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14401            if self.git_blame_inline_enabled != inline_blame_enabled {
14402                self.toggle_git_blame_inline_internal(false, window, cx);
14403            }
14404        }
14405
14406        cx.notify();
14407    }
14408
14409    pub fn set_searchable(&mut self, searchable: bool) {
14410        self.searchable = searchable;
14411    }
14412
14413    pub fn searchable(&self) -> bool {
14414        self.searchable
14415    }
14416
14417    fn open_proposed_changes_editor(
14418        &mut self,
14419        _: &OpenProposedChangesEditor,
14420        window: &mut Window,
14421        cx: &mut Context<Self>,
14422    ) {
14423        let Some(workspace) = self.workspace() else {
14424            cx.propagate();
14425            return;
14426        };
14427
14428        let selections = self.selections.all::<usize>(cx);
14429        let multi_buffer = self.buffer.read(cx);
14430        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14431        let mut new_selections_by_buffer = HashMap::default();
14432        for selection in selections {
14433            for (buffer, range, _) in
14434                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14435            {
14436                let mut range = range.to_point(buffer);
14437                range.start.column = 0;
14438                range.end.column = buffer.line_len(range.end.row);
14439                new_selections_by_buffer
14440                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14441                    .or_insert(Vec::new())
14442                    .push(range)
14443            }
14444        }
14445
14446        let proposed_changes_buffers = new_selections_by_buffer
14447            .into_iter()
14448            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14449            .collect::<Vec<_>>();
14450        let proposed_changes_editor = cx.new(|cx| {
14451            ProposedChangesEditor::new(
14452                "Proposed changes",
14453                proposed_changes_buffers,
14454                self.project.clone(),
14455                window,
14456                cx,
14457            )
14458        });
14459
14460        window.defer(cx, move |window, cx| {
14461            workspace.update(cx, |workspace, cx| {
14462                workspace.active_pane().update(cx, |pane, cx| {
14463                    pane.add_item(
14464                        Box::new(proposed_changes_editor),
14465                        true,
14466                        true,
14467                        None,
14468                        window,
14469                        cx,
14470                    );
14471                });
14472            });
14473        });
14474    }
14475
14476    pub fn open_excerpts_in_split(
14477        &mut self,
14478        _: &OpenExcerptsSplit,
14479        window: &mut Window,
14480        cx: &mut Context<Self>,
14481    ) {
14482        self.open_excerpts_common(None, true, window, cx)
14483    }
14484
14485    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14486        self.open_excerpts_common(None, false, window, cx)
14487    }
14488
14489    fn open_excerpts_common(
14490        &mut self,
14491        jump_data: Option<JumpData>,
14492        split: bool,
14493        window: &mut Window,
14494        cx: &mut Context<Self>,
14495    ) {
14496        let Some(workspace) = self.workspace() else {
14497            cx.propagate();
14498            return;
14499        };
14500
14501        if self.buffer.read(cx).is_singleton() {
14502            cx.propagate();
14503            return;
14504        }
14505
14506        let mut new_selections_by_buffer = HashMap::default();
14507        match &jump_data {
14508            Some(JumpData::MultiBufferPoint {
14509                excerpt_id,
14510                position,
14511                anchor,
14512                line_offset_from_top,
14513            }) => {
14514                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14515                if let Some(buffer) = multi_buffer_snapshot
14516                    .buffer_id_for_excerpt(*excerpt_id)
14517                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14518                {
14519                    let buffer_snapshot = buffer.read(cx).snapshot();
14520                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14521                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14522                    } else {
14523                        buffer_snapshot.clip_point(*position, Bias::Left)
14524                    };
14525                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14526                    new_selections_by_buffer.insert(
14527                        buffer,
14528                        (
14529                            vec![jump_to_offset..jump_to_offset],
14530                            Some(*line_offset_from_top),
14531                        ),
14532                    );
14533                }
14534            }
14535            Some(JumpData::MultiBufferRow {
14536                row,
14537                line_offset_from_top,
14538            }) => {
14539                let point = MultiBufferPoint::new(row.0, 0);
14540                if let Some((buffer, buffer_point, _)) =
14541                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14542                {
14543                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14544                    new_selections_by_buffer
14545                        .entry(buffer)
14546                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14547                        .0
14548                        .push(buffer_offset..buffer_offset)
14549                }
14550            }
14551            None => {
14552                let selections = self.selections.all::<usize>(cx);
14553                let multi_buffer = self.buffer.read(cx);
14554                for selection in selections {
14555                    for (buffer, mut range, _) in multi_buffer
14556                        .snapshot(cx)
14557                        .range_to_buffer_ranges(selection.range())
14558                    {
14559                        // When editing branch buffers, jump to the corresponding location
14560                        // in their base buffer.
14561                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14562                        let buffer = buffer_handle.read(cx);
14563                        if let Some(base_buffer) = buffer.base_buffer() {
14564                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14565                            buffer_handle = base_buffer;
14566                        }
14567
14568                        if selection.reversed {
14569                            mem::swap(&mut range.start, &mut range.end);
14570                        }
14571                        new_selections_by_buffer
14572                            .entry(buffer_handle)
14573                            .or_insert((Vec::new(), None))
14574                            .0
14575                            .push(range)
14576                    }
14577                }
14578            }
14579        }
14580
14581        if new_selections_by_buffer.is_empty() {
14582            return;
14583        }
14584
14585        // We defer the pane interaction because we ourselves are a workspace item
14586        // and activating a new item causes the pane to call a method on us reentrantly,
14587        // which panics if we're on the stack.
14588        window.defer(cx, move |window, cx| {
14589            workspace.update(cx, |workspace, cx| {
14590                let pane = if split {
14591                    workspace.adjacent_pane(window, cx)
14592                } else {
14593                    workspace.active_pane().clone()
14594                };
14595
14596                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14597                    let editor = buffer
14598                        .read(cx)
14599                        .file()
14600                        .is_none()
14601                        .then(|| {
14602                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14603                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14604                            // Instead, we try to activate the existing editor in the pane first.
14605                            let (editor, pane_item_index) =
14606                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14607                                    let editor = item.downcast::<Editor>()?;
14608                                    let singleton_buffer =
14609                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14610                                    if singleton_buffer == buffer {
14611                                        Some((editor, i))
14612                                    } else {
14613                                        None
14614                                    }
14615                                })?;
14616                            pane.update(cx, |pane, cx| {
14617                                pane.activate_item(pane_item_index, true, true, window, cx)
14618                            });
14619                            Some(editor)
14620                        })
14621                        .flatten()
14622                        .unwrap_or_else(|| {
14623                            workspace.open_project_item::<Self>(
14624                                pane.clone(),
14625                                buffer,
14626                                true,
14627                                true,
14628                                window,
14629                                cx,
14630                            )
14631                        });
14632
14633                    editor.update(cx, |editor, cx| {
14634                        let autoscroll = match scroll_offset {
14635                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14636                            None => Autoscroll::newest(),
14637                        };
14638                        let nav_history = editor.nav_history.take();
14639                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14640                            s.select_ranges(ranges);
14641                        });
14642                        editor.nav_history = nav_history;
14643                    });
14644                }
14645            })
14646        });
14647    }
14648
14649    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14650        let snapshot = self.buffer.read(cx).read(cx);
14651        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14652        Some(
14653            ranges
14654                .iter()
14655                .map(move |range| {
14656                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14657                })
14658                .collect(),
14659        )
14660    }
14661
14662    fn selection_replacement_ranges(
14663        &self,
14664        range: Range<OffsetUtf16>,
14665        cx: &mut App,
14666    ) -> Vec<Range<OffsetUtf16>> {
14667        let selections = self.selections.all::<OffsetUtf16>(cx);
14668        let newest_selection = selections
14669            .iter()
14670            .max_by_key(|selection| selection.id)
14671            .unwrap();
14672        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14673        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14674        let snapshot = self.buffer.read(cx).read(cx);
14675        selections
14676            .into_iter()
14677            .map(|mut selection| {
14678                selection.start.0 =
14679                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14680                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14681                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14682                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14683            })
14684            .collect()
14685    }
14686
14687    fn report_editor_event(
14688        &self,
14689        event_type: &'static str,
14690        file_extension: Option<String>,
14691        cx: &App,
14692    ) {
14693        if cfg!(any(test, feature = "test-support")) {
14694            return;
14695        }
14696
14697        let Some(project) = &self.project else { return };
14698
14699        // If None, we are in a file without an extension
14700        let file = self
14701            .buffer
14702            .read(cx)
14703            .as_singleton()
14704            .and_then(|b| b.read(cx).file());
14705        let file_extension = file_extension.or(file
14706            .as_ref()
14707            .and_then(|file| Path::new(file.file_name(cx)).extension())
14708            .and_then(|e| e.to_str())
14709            .map(|a| a.to_string()));
14710
14711        let vim_mode = cx
14712            .global::<SettingsStore>()
14713            .raw_user_settings()
14714            .get("vim_mode")
14715            == Some(&serde_json::Value::Bool(true));
14716
14717        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14718        let copilot_enabled = edit_predictions_provider
14719            == language::language_settings::EditPredictionProvider::Copilot;
14720        let copilot_enabled_for_language = self
14721            .buffer
14722            .read(cx)
14723            .settings_at(0, cx)
14724            .show_edit_predictions;
14725
14726        let project = project.read(cx);
14727        telemetry::event!(
14728            event_type,
14729            file_extension,
14730            vim_mode,
14731            copilot_enabled,
14732            copilot_enabled_for_language,
14733            edit_predictions_provider,
14734            is_via_ssh = project.is_via_ssh(),
14735        );
14736    }
14737
14738    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14739    /// with each line being an array of {text, highlight} objects.
14740    fn copy_highlight_json(
14741        &mut self,
14742        _: &CopyHighlightJson,
14743        window: &mut Window,
14744        cx: &mut Context<Self>,
14745    ) {
14746        #[derive(Serialize)]
14747        struct Chunk<'a> {
14748            text: String,
14749            highlight: Option<&'a str>,
14750        }
14751
14752        let snapshot = self.buffer.read(cx).snapshot(cx);
14753        let range = self
14754            .selected_text_range(false, window, cx)
14755            .and_then(|selection| {
14756                if selection.range.is_empty() {
14757                    None
14758                } else {
14759                    Some(selection.range)
14760                }
14761            })
14762            .unwrap_or_else(|| 0..snapshot.len());
14763
14764        let chunks = snapshot.chunks(range, true);
14765        let mut lines = Vec::new();
14766        let mut line: VecDeque<Chunk> = VecDeque::new();
14767
14768        let Some(style) = self.style.as_ref() else {
14769            return;
14770        };
14771
14772        for chunk in chunks {
14773            let highlight = chunk
14774                .syntax_highlight_id
14775                .and_then(|id| id.name(&style.syntax));
14776            let mut chunk_lines = chunk.text.split('\n').peekable();
14777            while let Some(text) = chunk_lines.next() {
14778                let mut merged_with_last_token = false;
14779                if let Some(last_token) = line.back_mut() {
14780                    if last_token.highlight == highlight {
14781                        last_token.text.push_str(text);
14782                        merged_with_last_token = true;
14783                    }
14784                }
14785
14786                if !merged_with_last_token {
14787                    line.push_back(Chunk {
14788                        text: text.into(),
14789                        highlight,
14790                    });
14791                }
14792
14793                if chunk_lines.peek().is_some() {
14794                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14795                        line.pop_front();
14796                    }
14797                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14798                        line.pop_back();
14799                    }
14800
14801                    lines.push(mem::take(&mut line));
14802                }
14803            }
14804        }
14805
14806        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14807            return;
14808        };
14809        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14810    }
14811
14812    pub fn open_context_menu(
14813        &mut self,
14814        _: &OpenContextMenu,
14815        window: &mut Window,
14816        cx: &mut Context<Self>,
14817    ) {
14818        self.request_autoscroll(Autoscroll::newest(), cx);
14819        let position = self.selections.newest_display(cx).start;
14820        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14821    }
14822
14823    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14824        &self.inlay_hint_cache
14825    }
14826
14827    pub fn replay_insert_event(
14828        &mut self,
14829        text: &str,
14830        relative_utf16_range: Option<Range<isize>>,
14831        window: &mut Window,
14832        cx: &mut Context<Self>,
14833    ) {
14834        if !self.input_enabled {
14835            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14836            return;
14837        }
14838        if let Some(relative_utf16_range) = relative_utf16_range {
14839            let selections = self.selections.all::<OffsetUtf16>(cx);
14840            self.change_selections(None, window, cx, |s| {
14841                let new_ranges = selections.into_iter().map(|range| {
14842                    let start = OffsetUtf16(
14843                        range
14844                            .head()
14845                            .0
14846                            .saturating_add_signed(relative_utf16_range.start),
14847                    );
14848                    let end = OffsetUtf16(
14849                        range
14850                            .head()
14851                            .0
14852                            .saturating_add_signed(relative_utf16_range.end),
14853                    );
14854                    start..end
14855                });
14856                s.select_ranges(new_ranges);
14857            });
14858        }
14859
14860        self.handle_input(text, window, cx);
14861    }
14862
14863    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14864        let Some(provider) = self.semantics_provider.as_ref() else {
14865            return false;
14866        };
14867
14868        let mut supports = false;
14869        self.buffer().update(cx, |this, cx| {
14870            this.for_each_buffer(|buffer| {
14871                supports |= provider.supports_inlay_hints(buffer, cx);
14872            });
14873        });
14874
14875        supports
14876    }
14877
14878    pub fn is_focused(&self, window: &Window) -> bool {
14879        self.focus_handle.is_focused(window)
14880    }
14881
14882    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14883        cx.emit(EditorEvent::Focused);
14884
14885        if let Some(descendant) = self
14886            .last_focused_descendant
14887            .take()
14888            .and_then(|descendant| descendant.upgrade())
14889        {
14890            window.focus(&descendant);
14891        } else {
14892            if let Some(blame) = self.blame.as_ref() {
14893                blame.update(cx, GitBlame::focus)
14894            }
14895
14896            self.blink_manager.update(cx, BlinkManager::enable);
14897            self.show_cursor_names(window, cx);
14898            self.buffer.update(cx, |buffer, cx| {
14899                buffer.finalize_last_transaction(cx);
14900                if self.leader_peer_id.is_none() {
14901                    buffer.set_active_selections(
14902                        &self.selections.disjoint_anchors(),
14903                        self.selections.line_mode,
14904                        self.cursor_shape,
14905                        cx,
14906                    );
14907                }
14908            });
14909        }
14910    }
14911
14912    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14913        cx.emit(EditorEvent::FocusedIn)
14914    }
14915
14916    fn handle_focus_out(
14917        &mut self,
14918        event: FocusOutEvent,
14919        _window: &mut Window,
14920        _cx: &mut Context<Self>,
14921    ) {
14922        if event.blurred != self.focus_handle {
14923            self.last_focused_descendant = Some(event.blurred);
14924        }
14925    }
14926
14927    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14928        self.blink_manager.update(cx, BlinkManager::disable);
14929        self.buffer
14930            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14931
14932        if let Some(blame) = self.blame.as_ref() {
14933            blame.update(cx, GitBlame::blur)
14934        }
14935        if !self.hover_state.focused(window, cx) {
14936            hide_hover(self, cx);
14937        }
14938        if !self
14939            .context_menu
14940            .borrow()
14941            .as_ref()
14942            .is_some_and(|context_menu| context_menu.focused(window, cx))
14943        {
14944            self.hide_context_menu(window, cx);
14945        }
14946        self.discard_inline_completion(false, cx);
14947        cx.emit(EditorEvent::Blurred);
14948        cx.notify();
14949    }
14950
14951    pub fn register_action<A: Action>(
14952        &mut self,
14953        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14954    ) -> Subscription {
14955        let id = self.next_editor_action_id.post_inc();
14956        let listener = Arc::new(listener);
14957        self.editor_actions.borrow_mut().insert(
14958            id,
14959            Box::new(move |window, _| {
14960                let listener = listener.clone();
14961                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14962                    let action = action.downcast_ref().unwrap();
14963                    if phase == DispatchPhase::Bubble {
14964                        listener(action, window, cx)
14965                    }
14966                })
14967            }),
14968        );
14969
14970        let editor_actions = self.editor_actions.clone();
14971        Subscription::new(move || {
14972            editor_actions.borrow_mut().remove(&id);
14973        })
14974    }
14975
14976    pub fn file_header_size(&self) -> u32 {
14977        FILE_HEADER_HEIGHT
14978    }
14979
14980    pub fn revert(
14981        &mut self,
14982        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14983        window: &mut Window,
14984        cx: &mut Context<Self>,
14985    ) {
14986        self.buffer().update(cx, |multi_buffer, cx| {
14987            for (buffer_id, changes) in revert_changes {
14988                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14989                    buffer.update(cx, |buffer, cx| {
14990                        buffer.edit(
14991                            changes.into_iter().map(|(range, text)| {
14992                                (range, text.to_string().map(Arc::<str>::from))
14993                            }),
14994                            None,
14995                            cx,
14996                        );
14997                    });
14998                }
14999            }
15000        });
15001        self.change_selections(None, window, cx, |selections| selections.refresh());
15002    }
15003
15004    pub fn to_pixel_point(
15005        &self,
15006        source: multi_buffer::Anchor,
15007        editor_snapshot: &EditorSnapshot,
15008        window: &mut Window,
15009    ) -> Option<gpui::Point<Pixels>> {
15010        let source_point = source.to_display_point(editor_snapshot);
15011        self.display_to_pixel_point(source_point, editor_snapshot, window)
15012    }
15013
15014    pub fn display_to_pixel_point(
15015        &self,
15016        source: DisplayPoint,
15017        editor_snapshot: &EditorSnapshot,
15018        window: &mut Window,
15019    ) -> Option<gpui::Point<Pixels>> {
15020        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15021        let text_layout_details = self.text_layout_details(window);
15022        let scroll_top = text_layout_details
15023            .scroll_anchor
15024            .scroll_position(editor_snapshot)
15025            .y;
15026
15027        if source.row().as_f32() < scroll_top.floor() {
15028            return None;
15029        }
15030        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15031        let source_y = line_height * (source.row().as_f32() - scroll_top);
15032        Some(gpui::Point::new(source_x, source_y))
15033    }
15034
15035    pub fn has_visible_completions_menu(&self) -> bool {
15036        !self.edit_prediction_preview_is_active()
15037            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15038                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15039            })
15040    }
15041
15042    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15043        self.addons
15044            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15045    }
15046
15047    pub fn unregister_addon<T: Addon>(&mut self) {
15048        self.addons.remove(&std::any::TypeId::of::<T>());
15049    }
15050
15051    pub fn addon<T: Addon>(&self) -> Option<&T> {
15052        let type_id = std::any::TypeId::of::<T>();
15053        self.addons
15054            .get(&type_id)
15055            .and_then(|item| item.to_any().downcast_ref::<T>())
15056    }
15057
15058    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15059        let text_layout_details = self.text_layout_details(window);
15060        let style = &text_layout_details.editor_style;
15061        let font_id = window.text_system().resolve_font(&style.text.font());
15062        let font_size = style.text.font_size.to_pixels(window.rem_size());
15063        let line_height = style.text.line_height_in_pixels(window.rem_size());
15064        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15065
15066        gpui::Size::new(em_width, line_height)
15067    }
15068
15069    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15070        self.load_diff_task.clone()
15071    }
15072
15073    fn read_selections_from_db(
15074        &mut self,
15075        item_id: u64,
15076        workspace_id: WorkspaceId,
15077        window: &mut Window,
15078        cx: &mut Context<Editor>,
15079    ) {
15080        if !self.is_singleton(cx)
15081            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15082        {
15083            return;
15084        }
15085        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15086            return;
15087        };
15088        if selections.is_empty() {
15089            return;
15090        }
15091
15092        let snapshot = self.buffer.read(cx).snapshot(cx);
15093        self.change_selections(None, window, cx, |s| {
15094            s.select_ranges(selections.into_iter().map(|(start, end)| {
15095                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15096            }));
15097        });
15098    }
15099}
15100
15101fn get_uncommitted_diff_for_buffer(
15102    project: &Entity<Project>,
15103    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15104    buffer: Entity<MultiBuffer>,
15105    cx: &mut App,
15106) -> Task<()> {
15107    let mut tasks = Vec::new();
15108    project.update(cx, |project, cx| {
15109        for buffer in buffers {
15110            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15111        }
15112    });
15113    cx.spawn(|mut cx| async move {
15114        let diffs = futures::future::join_all(tasks).await;
15115        buffer
15116            .update(&mut cx, |buffer, cx| {
15117                for diff in diffs.into_iter().flatten() {
15118                    buffer.add_diff(diff, cx);
15119                }
15120            })
15121            .ok();
15122    })
15123}
15124
15125fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15126    let tab_size = tab_size.get() as usize;
15127    let mut width = offset;
15128
15129    for ch in text.chars() {
15130        width += if ch == '\t' {
15131            tab_size - (width % tab_size)
15132        } else {
15133            1
15134        };
15135    }
15136
15137    width - offset
15138}
15139
15140#[cfg(test)]
15141mod tests {
15142    use super::*;
15143
15144    #[test]
15145    fn test_string_size_with_expanded_tabs() {
15146        let nz = |val| NonZeroU32::new(val).unwrap();
15147        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15148        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15149        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15150        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15151        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15152        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15153        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15154        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15155    }
15156}
15157
15158/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15159struct WordBreakingTokenizer<'a> {
15160    input: &'a str,
15161}
15162
15163impl<'a> WordBreakingTokenizer<'a> {
15164    fn new(input: &'a str) -> Self {
15165        Self { input }
15166    }
15167}
15168
15169fn is_char_ideographic(ch: char) -> bool {
15170    use unicode_script::Script::*;
15171    use unicode_script::UnicodeScript;
15172    matches!(ch.script(), Han | Tangut | Yi)
15173}
15174
15175fn is_grapheme_ideographic(text: &str) -> bool {
15176    text.chars().any(is_char_ideographic)
15177}
15178
15179fn is_grapheme_whitespace(text: &str) -> bool {
15180    text.chars().any(|x| x.is_whitespace())
15181}
15182
15183fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15184    text.chars().next().map_or(false, |ch| {
15185        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15186    })
15187}
15188
15189#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15190struct WordBreakToken<'a> {
15191    token: &'a str,
15192    grapheme_len: usize,
15193    is_whitespace: bool,
15194}
15195
15196impl<'a> Iterator for WordBreakingTokenizer<'a> {
15197    /// Yields a span, the count of graphemes in the token, and whether it was
15198    /// whitespace. Note that it also breaks at word boundaries.
15199    type Item = WordBreakToken<'a>;
15200
15201    fn next(&mut self) -> Option<Self::Item> {
15202        use unicode_segmentation::UnicodeSegmentation;
15203        if self.input.is_empty() {
15204            return None;
15205        }
15206
15207        let mut iter = self.input.graphemes(true).peekable();
15208        let mut offset = 0;
15209        let mut graphemes = 0;
15210        if let Some(first_grapheme) = iter.next() {
15211            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15212            offset += first_grapheme.len();
15213            graphemes += 1;
15214            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15215                if let Some(grapheme) = iter.peek().copied() {
15216                    if should_stay_with_preceding_ideograph(grapheme) {
15217                        offset += grapheme.len();
15218                        graphemes += 1;
15219                    }
15220                }
15221            } else {
15222                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15223                let mut next_word_bound = words.peek().copied();
15224                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15225                    next_word_bound = words.next();
15226                }
15227                while let Some(grapheme) = iter.peek().copied() {
15228                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15229                        break;
15230                    };
15231                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15232                        break;
15233                    };
15234                    offset += grapheme.len();
15235                    graphemes += 1;
15236                    iter.next();
15237                }
15238            }
15239            let token = &self.input[..offset];
15240            self.input = &self.input[offset..];
15241            if is_whitespace {
15242                Some(WordBreakToken {
15243                    token: " ",
15244                    grapheme_len: 1,
15245                    is_whitespace: true,
15246                })
15247            } else {
15248                Some(WordBreakToken {
15249                    token,
15250                    grapheme_len: graphemes,
15251                    is_whitespace: false,
15252                })
15253            }
15254        } else {
15255            None
15256        }
15257    }
15258}
15259
15260#[test]
15261fn test_word_breaking_tokenizer() {
15262    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15263        ("", &[]),
15264        ("  ", &[(" ", 1, true)]),
15265        ("Ʒ", &[("Ʒ", 1, false)]),
15266        ("Ǽ", &[("Ǽ", 1, false)]),
15267        ("", &[("", 1, false)]),
15268        ("⋑⋑", &[("⋑⋑", 2, false)]),
15269        (
15270            "原理,进而",
15271            &[
15272                ("", 1, false),
15273                ("理,", 2, false),
15274                ("", 1, false),
15275                ("", 1, false),
15276            ],
15277        ),
15278        (
15279            "hello world",
15280            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15281        ),
15282        (
15283            "hello, world",
15284            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15285        ),
15286        (
15287            "  hello world",
15288            &[
15289                (" ", 1, true),
15290                ("hello", 5, false),
15291                (" ", 1, true),
15292                ("world", 5, false),
15293            ],
15294        ),
15295        (
15296            "这是什么 \n 钢笔",
15297            &[
15298                ("", 1, false),
15299                ("", 1, false),
15300                ("", 1, false),
15301                ("", 1, false),
15302                (" ", 1, true),
15303                ("", 1, false),
15304                ("", 1, false),
15305            ],
15306        ),
15307        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15308    ];
15309
15310    for (input, result) in tests {
15311        assert_eq!(
15312            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15313            result
15314                .iter()
15315                .copied()
15316                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15317                    token,
15318                    grapheme_len,
15319                    is_whitespace,
15320                })
15321                .collect::<Vec<_>>()
15322        );
15323    }
15324}
15325
15326fn wrap_with_prefix(
15327    line_prefix: String,
15328    unwrapped_text: String,
15329    wrap_column: usize,
15330    tab_size: NonZeroU32,
15331) -> String {
15332    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15333    let mut wrapped_text = String::new();
15334    let mut current_line = line_prefix.clone();
15335
15336    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15337    let mut current_line_len = line_prefix_len;
15338    for WordBreakToken {
15339        token,
15340        grapheme_len,
15341        is_whitespace,
15342    } in tokenizer
15343    {
15344        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15345            wrapped_text.push_str(current_line.trim_end());
15346            wrapped_text.push('\n');
15347            current_line.truncate(line_prefix.len());
15348            current_line_len = line_prefix_len;
15349            if !is_whitespace {
15350                current_line.push_str(token);
15351                current_line_len += grapheme_len;
15352            }
15353        } else if !is_whitespace {
15354            current_line.push_str(token);
15355            current_line_len += grapheme_len;
15356        } else if current_line_len != line_prefix_len {
15357            current_line.push(' ');
15358            current_line_len += 1;
15359        }
15360    }
15361
15362    if !current_line.is_empty() {
15363        wrapped_text.push_str(&current_line);
15364    }
15365    wrapped_text
15366}
15367
15368#[test]
15369fn test_wrap_with_prefix() {
15370    assert_eq!(
15371        wrap_with_prefix(
15372            "# ".to_string(),
15373            "abcdefg".to_string(),
15374            4,
15375            NonZeroU32::new(4).unwrap()
15376        ),
15377        "# abcdefg"
15378    );
15379    assert_eq!(
15380        wrap_with_prefix(
15381            "".to_string(),
15382            "\thello world".to_string(),
15383            8,
15384            NonZeroU32::new(4).unwrap()
15385        ),
15386        "hello\nworld"
15387    );
15388    assert_eq!(
15389        wrap_with_prefix(
15390            "// ".to_string(),
15391            "xx \nyy zz aa bb cc".to_string(),
15392            12,
15393            NonZeroU32::new(4).unwrap()
15394        ),
15395        "// xx yy zz\n// aa bb cc"
15396    );
15397    assert_eq!(
15398        wrap_with_prefix(
15399            String::new(),
15400            "这是什么 \n 钢笔".to_string(),
15401            3,
15402            NonZeroU32::new(4).unwrap()
15403        ),
15404        "这是什\n么 钢\n"
15405    );
15406}
15407
15408pub trait CollaborationHub {
15409    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15410    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15411    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15412}
15413
15414impl CollaborationHub for Entity<Project> {
15415    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15416        self.read(cx).collaborators()
15417    }
15418
15419    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15420        self.read(cx).user_store().read(cx).participant_indices()
15421    }
15422
15423    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15424        let this = self.read(cx);
15425        let user_ids = this.collaborators().values().map(|c| c.user_id);
15426        this.user_store().read_with(cx, |user_store, cx| {
15427            user_store.participant_names(user_ids, cx)
15428        })
15429    }
15430}
15431
15432pub trait SemanticsProvider {
15433    fn hover(
15434        &self,
15435        buffer: &Entity<Buffer>,
15436        position: text::Anchor,
15437        cx: &mut App,
15438    ) -> Option<Task<Vec<project::Hover>>>;
15439
15440    fn inlay_hints(
15441        &self,
15442        buffer_handle: Entity<Buffer>,
15443        range: Range<text::Anchor>,
15444        cx: &mut App,
15445    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15446
15447    fn resolve_inlay_hint(
15448        &self,
15449        hint: InlayHint,
15450        buffer_handle: Entity<Buffer>,
15451        server_id: LanguageServerId,
15452        cx: &mut App,
15453    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15454
15455    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15456
15457    fn document_highlights(
15458        &self,
15459        buffer: &Entity<Buffer>,
15460        position: text::Anchor,
15461        cx: &mut App,
15462    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15463
15464    fn definitions(
15465        &self,
15466        buffer: &Entity<Buffer>,
15467        position: text::Anchor,
15468        kind: GotoDefinitionKind,
15469        cx: &mut App,
15470    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15471
15472    fn range_for_rename(
15473        &self,
15474        buffer: &Entity<Buffer>,
15475        position: text::Anchor,
15476        cx: &mut App,
15477    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15478
15479    fn perform_rename(
15480        &self,
15481        buffer: &Entity<Buffer>,
15482        position: text::Anchor,
15483        new_name: String,
15484        cx: &mut App,
15485    ) -> Option<Task<Result<ProjectTransaction>>>;
15486}
15487
15488pub trait CompletionProvider {
15489    fn completions(
15490        &self,
15491        buffer: &Entity<Buffer>,
15492        buffer_position: text::Anchor,
15493        trigger: CompletionContext,
15494        window: &mut Window,
15495        cx: &mut Context<Editor>,
15496    ) -> Task<Result<Vec<Completion>>>;
15497
15498    fn resolve_completions(
15499        &self,
15500        buffer: Entity<Buffer>,
15501        completion_indices: Vec<usize>,
15502        completions: Rc<RefCell<Box<[Completion]>>>,
15503        cx: &mut Context<Editor>,
15504    ) -> Task<Result<bool>>;
15505
15506    fn apply_additional_edits_for_completion(
15507        &self,
15508        _buffer: Entity<Buffer>,
15509        _completions: Rc<RefCell<Box<[Completion]>>>,
15510        _completion_index: usize,
15511        _push_to_history: bool,
15512        _cx: &mut Context<Editor>,
15513    ) -> Task<Result<Option<language::Transaction>>> {
15514        Task::ready(Ok(None))
15515    }
15516
15517    fn is_completion_trigger(
15518        &self,
15519        buffer: &Entity<Buffer>,
15520        position: language::Anchor,
15521        text: &str,
15522        trigger_in_words: bool,
15523        cx: &mut Context<Editor>,
15524    ) -> bool;
15525
15526    fn sort_completions(&self) -> bool {
15527        true
15528    }
15529}
15530
15531pub trait CodeActionProvider {
15532    fn id(&self) -> Arc<str>;
15533
15534    fn code_actions(
15535        &self,
15536        buffer: &Entity<Buffer>,
15537        range: Range<text::Anchor>,
15538        window: &mut Window,
15539        cx: &mut App,
15540    ) -> Task<Result<Vec<CodeAction>>>;
15541
15542    fn apply_code_action(
15543        &self,
15544        buffer_handle: Entity<Buffer>,
15545        action: CodeAction,
15546        excerpt_id: ExcerptId,
15547        push_to_history: bool,
15548        window: &mut Window,
15549        cx: &mut App,
15550    ) -> Task<Result<ProjectTransaction>>;
15551}
15552
15553impl CodeActionProvider for Entity<Project> {
15554    fn id(&self) -> Arc<str> {
15555        "project".into()
15556    }
15557
15558    fn code_actions(
15559        &self,
15560        buffer: &Entity<Buffer>,
15561        range: Range<text::Anchor>,
15562        _window: &mut Window,
15563        cx: &mut App,
15564    ) -> Task<Result<Vec<CodeAction>>> {
15565        self.update(cx, |project, cx| {
15566            project.code_actions(buffer, range, None, cx)
15567        })
15568    }
15569
15570    fn apply_code_action(
15571        &self,
15572        buffer_handle: Entity<Buffer>,
15573        action: CodeAction,
15574        _excerpt_id: ExcerptId,
15575        push_to_history: bool,
15576        _window: &mut Window,
15577        cx: &mut App,
15578    ) -> Task<Result<ProjectTransaction>> {
15579        self.update(cx, |project, cx| {
15580            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15581        })
15582    }
15583}
15584
15585fn snippet_completions(
15586    project: &Project,
15587    buffer: &Entity<Buffer>,
15588    buffer_position: text::Anchor,
15589    cx: &mut App,
15590) -> Task<Result<Vec<Completion>>> {
15591    let language = buffer.read(cx).language_at(buffer_position);
15592    let language_name = language.as_ref().map(|language| language.lsp_id());
15593    let snippet_store = project.snippets().read(cx);
15594    let snippets = snippet_store.snippets_for(language_name, cx);
15595
15596    if snippets.is_empty() {
15597        return Task::ready(Ok(vec![]));
15598    }
15599    let snapshot = buffer.read(cx).text_snapshot();
15600    let chars: String = snapshot
15601        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15602        .collect();
15603
15604    let scope = language.map(|language| language.default_scope());
15605    let executor = cx.background_executor().clone();
15606
15607    cx.background_spawn(async move {
15608        let classifier = CharClassifier::new(scope).for_completion(true);
15609        let mut last_word = chars
15610            .chars()
15611            .take_while(|c| classifier.is_word(*c))
15612            .collect::<String>();
15613        last_word = last_word.chars().rev().collect();
15614
15615        if last_word.is_empty() {
15616            return Ok(vec![]);
15617        }
15618
15619        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15620        let to_lsp = |point: &text::Anchor| {
15621            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15622            point_to_lsp(end)
15623        };
15624        let lsp_end = to_lsp(&buffer_position);
15625
15626        let candidates = snippets
15627            .iter()
15628            .enumerate()
15629            .flat_map(|(ix, snippet)| {
15630                snippet
15631                    .prefix
15632                    .iter()
15633                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15634            })
15635            .collect::<Vec<StringMatchCandidate>>();
15636
15637        let mut matches = fuzzy::match_strings(
15638            &candidates,
15639            &last_word,
15640            last_word.chars().any(|c| c.is_uppercase()),
15641            100,
15642            &Default::default(),
15643            executor,
15644        )
15645        .await;
15646
15647        // Remove all candidates where the query's start does not match the start of any word in the candidate
15648        if let Some(query_start) = last_word.chars().next() {
15649            matches.retain(|string_match| {
15650                split_words(&string_match.string).any(|word| {
15651                    // Check that the first codepoint of the word as lowercase matches the first
15652                    // codepoint of the query as lowercase
15653                    word.chars()
15654                        .flat_map(|codepoint| codepoint.to_lowercase())
15655                        .zip(query_start.to_lowercase())
15656                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15657                })
15658            });
15659        }
15660
15661        let matched_strings = matches
15662            .into_iter()
15663            .map(|m| m.string)
15664            .collect::<HashSet<_>>();
15665
15666        let result: Vec<Completion> = snippets
15667            .into_iter()
15668            .filter_map(|snippet| {
15669                let matching_prefix = snippet
15670                    .prefix
15671                    .iter()
15672                    .find(|prefix| matched_strings.contains(*prefix))?;
15673                let start = as_offset - last_word.len();
15674                let start = snapshot.anchor_before(start);
15675                let range = start..buffer_position;
15676                let lsp_start = to_lsp(&start);
15677                let lsp_range = lsp::Range {
15678                    start: lsp_start,
15679                    end: lsp_end,
15680                };
15681                Some(Completion {
15682                    old_range: range,
15683                    new_text: snippet.body.clone(),
15684                    resolved: false,
15685                    label: CodeLabel {
15686                        text: matching_prefix.clone(),
15687                        runs: vec![],
15688                        filter_range: 0..matching_prefix.len(),
15689                    },
15690                    server_id: LanguageServerId(usize::MAX),
15691                    documentation: snippet
15692                        .description
15693                        .clone()
15694                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
15695                    lsp_completion: lsp::CompletionItem {
15696                        label: snippet.prefix.first().unwrap().clone(),
15697                        kind: Some(CompletionItemKind::SNIPPET),
15698                        label_details: snippet.description.as_ref().map(|description| {
15699                            lsp::CompletionItemLabelDetails {
15700                                detail: Some(description.clone()),
15701                                description: None,
15702                            }
15703                        }),
15704                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15705                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15706                            lsp::InsertReplaceEdit {
15707                                new_text: snippet.body.clone(),
15708                                insert: lsp_range,
15709                                replace: lsp_range,
15710                            },
15711                        )),
15712                        filter_text: Some(snippet.body.clone()),
15713                        sort_text: Some(char::MAX.to_string()),
15714                        ..Default::default()
15715                    },
15716                    confirm: None,
15717                })
15718            })
15719            .collect();
15720
15721        Ok(result)
15722    })
15723}
15724
15725impl CompletionProvider for Entity<Project> {
15726    fn completions(
15727        &self,
15728        buffer: &Entity<Buffer>,
15729        buffer_position: text::Anchor,
15730        options: CompletionContext,
15731        _window: &mut Window,
15732        cx: &mut Context<Editor>,
15733    ) -> Task<Result<Vec<Completion>>> {
15734        self.update(cx, |project, cx| {
15735            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15736            let project_completions = project.completions(buffer, buffer_position, options, cx);
15737            cx.background_spawn(async move {
15738                let mut completions = project_completions.await?;
15739                let snippets_completions = snippets.await?;
15740                completions.extend(snippets_completions);
15741                Ok(completions)
15742            })
15743        })
15744    }
15745
15746    fn resolve_completions(
15747        &self,
15748        buffer: Entity<Buffer>,
15749        completion_indices: Vec<usize>,
15750        completions: Rc<RefCell<Box<[Completion]>>>,
15751        cx: &mut Context<Editor>,
15752    ) -> Task<Result<bool>> {
15753        self.update(cx, |project, cx| {
15754            project.lsp_store().update(cx, |lsp_store, cx| {
15755                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15756            })
15757        })
15758    }
15759
15760    fn apply_additional_edits_for_completion(
15761        &self,
15762        buffer: Entity<Buffer>,
15763        completions: Rc<RefCell<Box<[Completion]>>>,
15764        completion_index: usize,
15765        push_to_history: bool,
15766        cx: &mut Context<Editor>,
15767    ) -> Task<Result<Option<language::Transaction>>> {
15768        self.update(cx, |project, cx| {
15769            project.lsp_store().update(cx, |lsp_store, cx| {
15770                lsp_store.apply_additional_edits_for_completion(
15771                    buffer,
15772                    completions,
15773                    completion_index,
15774                    push_to_history,
15775                    cx,
15776                )
15777            })
15778        })
15779    }
15780
15781    fn is_completion_trigger(
15782        &self,
15783        buffer: &Entity<Buffer>,
15784        position: language::Anchor,
15785        text: &str,
15786        trigger_in_words: bool,
15787        cx: &mut Context<Editor>,
15788    ) -> bool {
15789        let mut chars = text.chars();
15790        let char = if let Some(char) = chars.next() {
15791            char
15792        } else {
15793            return false;
15794        };
15795        if chars.next().is_some() {
15796            return false;
15797        }
15798
15799        let buffer = buffer.read(cx);
15800        let snapshot = buffer.snapshot();
15801        if !snapshot.settings_at(position, cx).show_completions_on_input {
15802            return false;
15803        }
15804        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15805        if trigger_in_words && classifier.is_word(char) {
15806            return true;
15807        }
15808
15809        buffer.completion_triggers().contains(text)
15810    }
15811}
15812
15813impl SemanticsProvider for Entity<Project> {
15814    fn hover(
15815        &self,
15816        buffer: &Entity<Buffer>,
15817        position: text::Anchor,
15818        cx: &mut App,
15819    ) -> Option<Task<Vec<project::Hover>>> {
15820        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15821    }
15822
15823    fn document_highlights(
15824        &self,
15825        buffer: &Entity<Buffer>,
15826        position: text::Anchor,
15827        cx: &mut App,
15828    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15829        Some(self.update(cx, |project, cx| {
15830            project.document_highlights(buffer, position, cx)
15831        }))
15832    }
15833
15834    fn definitions(
15835        &self,
15836        buffer: &Entity<Buffer>,
15837        position: text::Anchor,
15838        kind: GotoDefinitionKind,
15839        cx: &mut App,
15840    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15841        Some(self.update(cx, |project, cx| match kind {
15842            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15843            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15844            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15845            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15846        }))
15847    }
15848
15849    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15850        // TODO: make this work for remote projects
15851        self.update(cx, |this, cx| {
15852            buffer.update(cx, |buffer, cx| {
15853                this.any_language_server_supports_inlay_hints(buffer, cx)
15854            })
15855        })
15856    }
15857
15858    fn inlay_hints(
15859        &self,
15860        buffer_handle: Entity<Buffer>,
15861        range: Range<text::Anchor>,
15862        cx: &mut App,
15863    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15864        Some(self.update(cx, |project, cx| {
15865            project.inlay_hints(buffer_handle, range, cx)
15866        }))
15867    }
15868
15869    fn resolve_inlay_hint(
15870        &self,
15871        hint: InlayHint,
15872        buffer_handle: Entity<Buffer>,
15873        server_id: LanguageServerId,
15874        cx: &mut App,
15875    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15876        Some(self.update(cx, |project, cx| {
15877            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15878        }))
15879    }
15880
15881    fn range_for_rename(
15882        &self,
15883        buffer: &Entity<Buffer>,
15884        position: text::Anchor,
15885        cx: &mut App,
15886    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15887        Some(self.update(cx, |project, cx| {
15888            let buffer = buffer.clone();
15889            let task = project.prepare_rename(buffer.clone(), position, cx);
15890            cx.spawn(|_, mut cx| async move {
15891                Ok(match task.await? {
15892                    PrepareRenameResponse::Success(range) => Some(range),
15893                    PrepareRenameResponse::InvalidPosition => None,
15894                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15895                        // Fallback on using TreeSitter info to determine identifier range
15896                        buffer.update(&mut cx, |buffer, _| {
15897                            let snapshot = buffer.snapshot();
15898                            let (range, kind) = snapshot.surrounding_word(position);
15899                            if kind != Some(CharKind::Word) {
15900                                return None;
15901                            }
15902                            Some(
15903                                snapshot.anchor_before(range.start)
15904                                    ..snapshot.anchor_after(range.end),
15905                            )
15906                        })?
15907                    }
15908                })
15909            })
15910        }))
15911    }
15912
15913    fn perform_rename(
15914        &self,
15915        buffer: &Entity<Buffer>,
15916        position: text::Anchor,
15917        new_name: String,
15918        cx: &mut App,
15919    ) -> Option<Task<Result<ProjectTransaction>>> {
15920        Some(self.update(cx, |project, cx| {
15921            project.perform_rename(buffer.clone(), position, new_name, cx)
15922        }))
15923    }
15924}
15925
15926fn inlay_hint_settings(
15927    location: Anchor,
15928    snapshot: &MultiBufferSnapshot,
15929    cx: &mut Context<Editor>,
15930) -> InlayHintSettings {
15931    let file = snapshot.file_at(location);
15932    let language = snapshot.language_at(location).map(|l| l.name());
15933    language_settings(language, file, cx).inlay_hints
15934}
15935
15936fn consume_contiguous_rows(
15937    contiguous_row_selections: &mut Vec<Selection<Point>>,
15938    selection: &Selection<Point>,
15939    display_map: &DisplaySnapshot,
15940    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15941) -> (MultiBufferRow, MultiBufferRow) {
15942    contiguous_row_selections.push(selection.clone());
15943    let start_row = MultiBufferRow(selection.start.row);
15944    let mut end_row = ending_row(selection, display_map);
15945
15946    while let Some(next_selection) = selections.peek() {
15947        if next_selection.start.row <= end_row.0 {
15948            end_row = ending_row(next_selection, display_map);
15949            contiguous_row_selections.push(selections.next().unwrap().clone());
15950        } else {
15951            break;
15952        }
15953    }
15954    (start_row, end_row)
15955}
15956
15957fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15958    if next_selection.end.column > 0 || next_selection.is_empty() {
15959        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15960    } else {
15961        MultiBufferRow(next_selection.end.row)
15962    }
15963}
15964
15965impl EditorSnapshot {
15966    pub fn remote_selections_in_range<'a>(
15967        &'a self,
15968        range: &'a Range<Anchor>,
15969        collaboration_hub: &dyn CollaborationHub,
15970        cx: &'a App,
15971    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15972        let participant_names = collaboration_hub.user_names(cx);
15973        let participant_indices = collaboration_hub.user_participant_indices(cx);
15974        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15975        let collaborators_by_replica_id = collaborators_by_peer_id
15976            .iter()
15977            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15978            .collect::<HashMap<_, _>>();
15979        self.buffer_snapshot
15980            .selections_in_range(range, false)
15981            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15982                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15983                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15984                let user_name = participant_names.get(&collaborator.user_id).cloned();
15985                Some(RemoteSelection {
15986                    replica_id,
15987                    selection,
15988                    cursor_shape,
15989                    line_mode,
15990                    participant_index,
15991                    peer_id: collaborator.peer_id,
15992                    user_name,
15993                })
15994            })
15995    }
15996
15997    pub fn hunks_for_ranges(
15998        &self,
15999        ranges: impl Iterator<Item = Range<Point>>,
16000    ) -> Vec<MultiBufferDiffHunk> {
16001        let mut hunks = Vec::new();
16002        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16003            HashMap::default();
16004        for query_range in ranges {
16005            let query_rows =
16006                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16007            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16008                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16009            ) {
16010                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16011                // when the caret is just above or just below the deleted hunk.
16012                let allow_adjacent = hunk.status().is_removed();
16013                let related_to_selection = if allow_adjacent {
16014                    hunk.row_range.overlaps(&query_rows)
16015                        || hunk.row_range.start == query_rows.end
16016                        || hunk.row_range.end == query_rows.start
16017                } else {
16018                    hunk.row_range.overlaps(&query_rows)
16019                };
16020                if related_to_selection {
16021                    if !processed_buffer_rows
16022                        .entry(hunk.buffer_id)
16023                        .or_default()
16024                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16025                    {
16026                        continue;
16027                    }
16028                    hunks.push(hunk);
16029                }
16030            }
16031        }
16032
16033        hunks
16034    }
16035
16036    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16037        self.display_snapshot.buffer_snapshot.language_at(position)
16038    }
16039
16040    pub fn is_focused(&self) -> bool {
16041        self.is_focused
16042    }
16043
16044    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16045        self.placeholder_text.as_ref()
16046    }
16047
16048    pub fn scroll_position(&self) -> gpui::Point<f32> {
16049        self.scroll_anchor.scroll_position(&self.display_snapshot)
16050    }
16051
16052    fn gutter_dimensions(
16053        &self,
16054        font_id: FontId,
16055        font_size: Pixels,
16056        max_line_number_width: Pixels,
16057        cx: &App,
16058    ) -> Option<GutterDimensions> {
16059        if !self.show_gutter {
16060            return None;
16061        }
16062
16063        let descent = cx.text_system().descent(font_id, font_size);
16064        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16065        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16066
16067        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16068            matches!(
16069                ProjectSettings::get_global(cx).git.git_gutter,
16070                Some(GitGutterSetting::TrackedFiles)
16071            )
16072        });
16073        let gutter_settings = EditorSettings::get_global(cx).gutter;
16074        let show_line_numbers = self
16075            .show_line_numbers
16076            .unwrap_or(gutter_settings.line_numbers);
16077        let line_gutter_width = if show_line_numbers {
16078            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16079            let min_width_for_number_on_gutter = em_advance * 4.0;
16080            max_line_number_width.max(min_width_for_number_on_gutter)
16081        } else {
16082            0.0.into()
16083        };
16084
16085        let show_code_actions = self
16086            .show_code_actions
16087            .unwrap_or(gutter_settings.code_actions);
16088
16089        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16090
16091        let git_blame_entries_width =
16092            self.git_blame_gutter_max_author_length
16093                .map(|max_author_length| {
16094                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16095
16096                    /// The number of characters to dedicate to gaps and margins.
16097                    const SPACING_WIDTH: usize = 4;
16098
16099                    let max_char_count = max_author_length
16100                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16101                        + ::git::SHORT_SHA_LENGTH
16102                        + MAX_RELATIVE_TIMESTAMP.len()
16103                        + SPACING_WIDTH;
16104
16105                    em_advance * max_char_count
16106                });
16107
16108        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16109        left_padding += if show_code_actions || show_runnables {
16110            em_width * 3.0
16111        } else if show_git_gutter && show_line_numbers {
16112            em_width * 2.0
16113        } else if show_git_gutter || show_line_numbers {
16114            em_width
16115        } else {
16116            px(0.)
16117        };
16118
16119        let right_padding = if gutter_settings.folds && show_line_numbers {
16120            em_width * 4.0
16121        } else if gutter_settings.folds {
16122            em_width * 3.0
16123        } else if show_line_numbers {
16124            em_width
16125        } else {
16126            px(0.)
16127        };
16128
16129        Some(GutterDimensions {
16130            left_padding,
16131            right_padding,
16132            width: line_gutter_width + left_padding + right_padding,
16133            margin: -descent,
16134            git_blame_entries_width,
16135        })
16136    }
16137
16138    pub fn render_crease_toggle(
16139        &self,
16140        buffer_row: MultiBufferRow,
16141        row_contains_cursor: bool,
16142        editor: Entity<Editor>,
16143        window: &mut Window,
16144        cx: &mut App,
16145    ) -> Option<AnyElement> {
16146        let folded = self.is_line_folded(buffer_row);
16147        let mut is_foldable = false;
16148
16149        if let Some(crease) = self
16150            .crease_snapshot
16151            .query_row(buffer_row, &self.buffer_snapshot)
16152        {
16153            is_foldable = true;
16154            match crease {
16155                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16156                    if let Some(render_toggle) = render_toggle {
16157                        let toggle_callback =
16158                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16159                                if folded {
16160                                    editor.update(cx, |editor, cx| {
16161                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16162                                    });
16163                                } else {
16164                                    editor.update(cx, |editor, cx| {
16165                                        editor.unfold_at(
16166                                            &crate::UnfoldAt { buffer_row },
16167                                            window,
16168                                            cx,
16169                                        )
16170                                    });
16171                                }
16172                            });
16173                        return Some((render_toggle)(
16174                            buffer_row,
16175                            folded,
16176                            toggle_callback,
16177                            window,
16178                            cx,
16179                        ));
16180                    }
16181                }
16182            }
16183        }
16184
16185        is_foldable |= self.starts_indent(buffer_row);
16186
16187        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16188            Some(
16189                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16190                    .toggle_state(folded)
16191                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16192                        if folded {
16193                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16194                        } else {
16195                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16196                        }
16197                    }))
16198                    .into_any_element(),
16199            )
16200        } else {
16201            None
16202        }
16203    }
16204
16205    pub fn render_crease_trailer(
16206        &self,
16207        buffer_row: MultiBufferRow,
16208        window: &mut Window,
16209        cx: &mut App,
16210    ) -> Option<AnyElement> {
16211        let folded = self.is_line_folded(buffer_row);
16212        if let Crease::Inline { render_trailer, .. } = self
16213            .crease_snapshot
16214            .query_row(buffer_row, &self.buffer_snapshot)?
16215        {
16216            let render_trailer = render_trailer.as_ref()?;
16217            Some(render_trailer(buffer_row, folded, window, cx))
16218        } else {
16219            None
16220        }
16221    }
16222}
16223
16224impl Deref for EditorSnapshot {
16225    type Target = DisplaySnapshot;
16226
16227    fn deref(&self) -> &Self::Target {
16228        &self.display_snapshot
16229    }
16230}
16231
16232#[derive(Clone, Debug, PartialEq, Eq)]
16233pub enum EditorEvent {
16234    InputIgnored {
16235        text: Arc<str>,
16236    },
16237    InputHandled {
16238        utf16_range_to_replace: Option<Range<isize>>,
16239        text: Arc<str>,
16240    },
16241    ExcerptsAdded {
16242        buffer: Entity<Buffer>,
16243        predecessor: ExcerptId,
16244        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16245    },
16246    ExcerptsRemoved {
16247        ids: Vec<ExcerptId>,
16248    },
16249    BufferFoldToggled {
16250        ids: Vec<ExcerptId>,
16251        folded: bool,
16252    },
16253    ExcerptsEdited {
16254        ids: Vec<ExcerptId>,
16255    },
16256    ExcerptsExpanded {
16257        ids: Vec<ExcerptId>,
16258    },
16259    BufferEdited,
16260    Edited {
16261        transaction_id: clock::Lamport,
16262    },
16263    Reparsed(BufferId),
16264    Focused,
16265    FocusedIn,
16266    Blurred,
16267    DirtyChanged,
16268    Saved,
16269    TitleChanged,
16270    DiffBaseChanged,
16271    SelectionsChanged {
16272        local: bool,
16273    },
16274    ScrollPositionChanged {
16275        local: bool,
16276        autoscroll: bool,
16277    },
16278    Closed,
16279    TransactionUndone {
16280        transaction_id: clock::Lamport,
16281    },
16282    TransactionBegun {
16283        transaction_id: clock::Lamport,
16284    },
16285    Reloaded,
16286    CursorShapeChanged,
16287}
16288
16289impl EventEmitter<EditorEvent> for Editor {}
16290
16291impl Focusable for Editor {
16292    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16293        self.focus_handle.clone()
16294    }
16295}
16296
16297impl Render for Editor {
16298    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16299        let settings = ThemeSettings::get_global(cx);
16300
16301        let mut text_style = match self.mode {
16302            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16303                color: cx.theme().colors().editor_foreground,
16304                font_family: settings.ui_font.family.clone(),
16305                font_features: settings.ui_font.features.clone(),
16306                font_fallbacks: settings.ui_font.fallbacks.clone(),
16307                font_size: rems(0.875).into(),
16308                font_weight: settings.ui_font.weight,
16309                line_height: relative(settings.buffer_line_height.value()),
16310                ..Default::default()
16311            },
16312            EditorMode::Full => TextStyle {
16313                color: cx.theme().colors().editor_foreground,
16314                font_family: settings.buffer_font.family.clone(),
16315                font_features: settings.buffer_font.features.clone(),
16316                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16317                font_size: settings.buffer_font_size(cx).into(),
16318                font_weight: settings.buffer_font.weight,
16319                line_height: relative(settings.buffer_line_height.value()),
16320                ..Default::default()
16321            },
16322        };
16323        if let Some(text_style_refinement) = &self.text_style_refinement {
16324            text_style.refine(text_style_refinement)
16325        }
16326
16327        let background = match self.mode {
16328            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16329            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16330            EditorMode::Full => cx.theme().colors().editor_background,
16331        };
16332
16333        EditorElement::new(
16334            &cx.entity(),
16335            EditorStyle {
16336                background,
16337                local_player: cx.theme().players().local(),
16338                text: text_style,
16339                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16340                syntax: cx.theme().syntax().clone(),
16341                status: cx.theme().status().clone(),
16342                inlay_hints_style: make_inlay_hints_style(cx),
16343                inline_completion_styles: make_suggestion_styles(cx),
16344                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16345            },
16346        )
16347    }
16348}
16349
16350impl EntityInputHandler for Editor {
16351    fn text_for_range(
16352        &mut self,
16353        range_utf16: Range<usize>,
16354        adjusted_range: &mut Option<Range<usize>>,
16355        _: &mut Window,
16356        cx: &mut Context<Self>,
16357    ) -> Option<String> {
16358        let snapshot = self.buffer.read(cx).read(cx);
16359        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16360        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16361        if (start.0..end.0) != range_utf16 {
16362            adjusted_range.replace(start.0..end.0);
16363        }
16364        Some(snapshot.text_for_range(start..end).collect())
16365    }
16366
16367    fn selected_text_range(
16368        &mut self,
16369        ignore_disabled_input: bool,
16370        _: &mut Window,
16371        cx: &mut Context<Self>,
16372    ) -> Option<UTF16Selection> {
16373        // Prevent the IME menu from appearing when holding down an alphabetic key
16374        // while input is disabled.
16375        if !ignore_disabled_input && !self.input_enabled {
16376            return None;
16377        }
16378
16379        let selection = self.selections.newest::<OffsetUtf16>(cx);
16380        let range = selection.range();
16381
16382        Some(UTF16Selection {
16383            range: range.start.0..range.end.0,
16384            reversed: selection.reversed,
16385        })
16386    }
16387
16388    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16389        let snapshot = self.buffer.read(cx).read(cx);
16390        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16391        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16392    }
16393
16394    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16395        self.clear_highlights::<InputComposition>(cx);
16396        self.ime_transaction.take();
16397    }
16398
16399    fn replace_text_in_range(
16400        &mut self,
16401        range_utf16: Option<Range<usize>>,
16402        text: &str,
16403        window: &mut Window,
16404        cx: &mut Context<Self>,
16405    ) {
16406        if !self.input_enabled {
16407            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16408            return;
16409        }
16410
16411        self.transact(window, cx, |this, window, cx| {
16412            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16413                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16414                Some(this.selection_replacement_ranges(range_utf16, cx))
16415            } else {
16416                this.marked_text_ranges(cx)
16417            };
16418
16419            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16420                let newest_selection_id = this.selections.newest_anchor().id;
16421                this.selections
16422                    .all::<OffsetUtf16>(cx)
16423                    .iter()
16424                    .zip(ranges_to_replace.iter())
16425                    .find_map(|(selection, range)| {
16426                        if selection.id == newest_selection_id {
16427                            Some(
16428                                (range.start.0 as isize - selection.head().0 as isize)
16429                                    ..(range.end.0 as isize - selection.head().0 as isize),
16430                            )
16431                        } else {
16432                            None
16433                        }
16434                    })
16435            });
16436
16437            cx.emit(EditorEvent::InputHandled {
16438                utf16_range_to_replace: range_to_replace,
16439                text: text.into(),
16440            });
16441
16442            if let Some(new_selected_ranges) = new_selected_ranges {
16443                this.change_selections(None, window, cx, |selections| {
16444                    selections.select_ranges(new_selected_ranges)
16445                });
16446                this.backspace(&Default::default(), window, cx);
16447            }
16448
16449            this.handle_input(text, window, cx);
16450        });
16451
16452        if let Some(transaction) = self.ime_transaction {
16453            self.buffer.update(cx, |buffer, cx| {
16454                buffer.group_until_transaction(transaction, cx);
16455            });
16456        }
16457
16458        self.unmark_text(window, cx);
16459    }
16460
16461    fn replace_and_mark_text_in_range(
16462        &mut self,
16463        range_utf16: Option<Range<usize>>,
16464        text: &str,
16465        new_selected_range_utf16: Option<Range<usize>>,
16466        window: &mut Window,
16467        cx: &mut Context<Self>,
16468    ) {
16469        if !self.input_enabled {
16470            return;
16471        }
16472
16473        let transaction = self.transact(window, cx, |this, window, cx| {
16474            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16475                let snapshot = this.buffer.read(cx).read(cx);
16476                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16477                    for marked_range in &mut marked_ranges {
16478                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16479                        marked_range.start.0 += relative_range_utf16.start;
16480                        marked_range.start =
16481                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16482                        marked_range.end =
16483                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16484                    }
16485                }
16486                Some(marked_ranges)
16487            } else if let Some(range_utf16) = range_utf16 {
16488                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16489                Some(this.selection_replacement_ranges(range_utf16, cx))
16490            } else {
16491                None
16492            };
16493
16494            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16495                let newest_selection_id = this.selections.newest_anchor().id;
16496                this.selections
16497                    .all::<OffsetUtf16>(cx)
16498                    .iter()
16499                    .zip(ranges_to_replace.iter())
16500                    .find_map(|(selection, range)| {
16501                        if selection.id == newest_selection_id {
16502                            Some(
16503                                (range.start.0 as isize - selection.head().0 as isize)
16504                                    ..(range.end.0 as isize - selection.head().0 as isize),
16505                            )
16506                        } else {
16507                            None
16508                        }
16509                    })
16510            });
16511
16512            cx.emit(EditorEvent::InputHandled {
16513                utf16_range_to_replace: range_to_replace,
16514                text: text.into(),
16515            });
16516
16517            if let Some(ranges) = ranges_to_replace {
16518                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16519            }
16520
16521            let marked_ranges = {
16522                let snapshot = this.buffer.read(cx).read(cx);
16523                this.selections
16524                    .disjoint_anchors()
16525                    .iter()
16526                    .map(|selection| {
16527                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16528                    })
16529                    .collect::<Vec<_>>()
16530            };
16531
16532            if text.is_empty() {
16533                this.unmark_text(window, cx);
16534            } else {
16535                this.highlight_text::<InputComposition>(
16536                    marked_ranges.clone(),
16537                    HighlightStyle {
16538                        underline: Some(UnderlineStyle {
16539                            thickness: px(1.),
16540                            color: None,
16541                            wavy: false,
16542                        }),
16543                        ..Default::default()
16544                    },
16545                    cx,
16546                );
16547            }
16548
16549            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16550            let use_autoclose = this.use_autoclose;
16551            let use_auto_surround = this.use_auto_surround;
16552            this.set_use_autoclose(false);
16553            this.set_use_auto_surround(false);
16554            this.handle_input(text, window, cx);
16555            this.set_use_autoclose(use_autoclose);
16556            this.set_use_auto_surround(use_auto_surround);
16557
16558            if let Some(new_selected_range) = new_selected_range_utf16 {
16559                let snapshot = this.buffer.read(cx).read(cx);
16560                let new_selected_ranges = marked_ranges
16561                    .into_iter()
16562                    .map(|marked_range| {
16563                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16564                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16565                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16566                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16567                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16568                    })
16569                    .collect::<Vec<_>>();
16570
16571                drop(snapshot);
16572                this.change_selections(None, window, cx, |selections| {
16573                    selections.select_ranges(new_selected_ranges)
16574                });
16575            }
16576        });
16577
16578        self.ime_transaction = self.ime_transaction.or(transaction);
16579        if let Some(transaction) = self.ime_transaction {
16580            self.buffer.update(cx, |buffer, cx| {
16581                buffer.group_until_transaction(transaction, cx);
16582            });
16583        }
16584
16585        if self.text_highlights::<InputComposition>(cx).is_none() {
16586            self.ime_transaction.take();
16587        }
16588    }
16589
16590    fn bounds_for_range(
16591        &mut self,
16592        range_utf16: Range<usize>,
16593        element_bounds: gpui::Bounds<Pixels>,
16594        window: &mut Window,
16595        cx: &mut Context<Self>,
16596    ) -> Option<gpui::Bounds<Pixels>> {
16597        let text_layout_details = self.text_layout_details(window);
16598        let gpui::Size {
16599            width: em_width,
16600            height: line_height,
16601        } = self.character_size(window);
16602
16603        let snapshot = self.snapshot(window, cx);
16604        let scroll_position = snapshot.scroll_position();
16605        let scroll_left = scroll_position.x * em_width;
16606
16607        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16608        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16609            + self.gutter_dimensions.width
16610            + self.gutter_dimensions.margin;
16611        let y = line_height * (start.row().as_f32() - scroll_position.y);
16612
16613        Some(Bounds {
16614            origin: element_bounds.origin + point(x, y),
16615            size: size(em_width, line_height),
16616        })
16617    }
16618
16619    fn character_index_for_point(
16620        &mut self,
16621        point: gpui::Point<Pixels>,
16622        _window: &mut Window,
16623        _cx: &mut Context<Self>,
16624    ) -> Option<usize> {
16625        let position_map = self.last_position_map.as_ref()?;
16626        if !position_map.text_hitbox.contains(&point) {
16627            return None;
16628        }
16629        let display_point = position_map.point_for_position(point).previous_valid;
16630        let anchor = position_map
16631            .snapshot
16632            .display_point_to_anchor(display_point, Bias::Left);
16633        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16634        Some(utf16_offset.0)
16635    }
16636}
16637
16638trait SelectionExt {
16639    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16640    fn spanned_rows(
16641        &self,
16642        include_end_if_at_line_start: bool,
16643        map: &DisplaySnapshot,
16644    ) -> Range<MultiBufferRow>;
16645}
16646
16647impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16648    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16649        let start = self
16650            .start
16651            .to_point(&map.buffer_snapshot)
16652            .to_display_point(map);
16653        let end = self
16654            .end
16655            .to_point(&map.buffer_snapshot)
16656            .to_display_point(map);
16657        if self.reversed {
16658            end..start
16659        } else {
16660            start..end
16661        }
16662    }
16663
16664    fn spanned_rows(
16665        &self,
16666        include_end_if_at_line_start: bool,
16667        map: &DisplaySnapshot,
16668    ) -> Range<MultiBufferRow> {
16669        let start = self.start.to_point(&map.buffer_snapshot);
16670        let mut end = self.end.to_point(&map.buffer_snapshot);
16671        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16672            end.row -= 1;
16673        }
16674
16675        let buffer_start = map.prev_line_boundary(start).0;
16676        let buffer_end = map.next_line_boundary(end).0;
16677        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16678    }
16679}
16680
16681impl<T: InvalidationRegion> InvalidationStack<T> {
16682    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16683    where
16684        S: Clone + ToOffset,
16685    {
16686        while let Some(region) = self.last() {
16687            let all_selections_inside_invalidation_ranges =
16688                if selections.len() == region.ranges().len() {
16689                    selections
16690                        .iter()
16691                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16692                        .all(|(selection, invalidation_range)| {
16693                            let head = selection.head().to_offset(buffer);
16694                            invalidation_range.start <= head && invalidation_range.end >= head
16695                        })
16696                } else {
16697                    false
16698                };
16699
16700            if all_selections_inside_invalidation_ranges {
16701                break;
16702            } else {
16703                self.pop();
16704            }
16705        }
16706    }
16707}
16708
16709impl<T> Default for InvalidationStack<T> {
16710    fn default() -> Self {
16711        Self(Default::default())
16712    }
16713}
16714
16715impl<T> Deref for InvalidationStack<T> {
16716    type Target = Vec<T>;
16717
16718    fn deref(&self) -> &Self::Target {
16719        &self.0
16720    }
16721}
16722
16723impl<T> DerefMut for InvalidationStack<T> {
16724    fn deref_mut(&mut self) -> &mut Self::Target {
16725        &mut self.0
16726    }
16727}
16728
16729impl InvalidationRegion for SnippetState {
16730    fn ranges(&self) -> &[Range<Anchor>] {
16731        &self.ranges[self.active_index]
16732    }
16733}
16734
16735pub fn diagnostic_block_renderer(
16736    diagnostic: Diagnostic,
16737    max_message_rows: Option<u8>,
16738    allow_closing: bool,
16739    _is_valid: bool,
16740) -> RenderBlock {
16741    let (text_without_backticks, code_ranges) =
16742        highlight_diagnostic_message(&diagnostic, max_message_rows);
16743
16744    Arc::new(move |cx: &mut BlockContext| {
16745        let group_id: SharedString = cx.block_id.to_string().into();
16746
16747        let mut text_style = cx.window.text_style().clone();
16748        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16749        let theme_settings = ThemeSettings::get_global(cx);
16750        text_style.font_family = theme_settings.buffer_font.family.clone();
16751        text_style.font_style = theme_settings.buffer_font.style;
16752        text_style.font_features = theme_settings.buffer_font.features.clone();
16753        text_style.font_weight = theme_settings.buffer_font.weight;
16754
16755        let multi_line_diagnostic = diagnostic.message.contains('\n');
16756
16757        let buttons = |diagnostic: &Diagnostic| {
16758            if multi_line_diagnostic {
16759                v_flex()
16760            } else {
16761                h_flex()
16762            }
16763            .when(allow_closing, |div| {
16764                div.children(diagnostic.is_primary.then(|| {
16765                    IconButton::new("close-block", IconName::XCircle)
16766                        .icon_color(Color::Muted)
16767                        .size(ButtonSize::Compact)
16768                        .style(ButtonStyle::Transparent)
16769                        .visible_on_hover(group_id.clone())
16770                        .on_click(move |_click, window, cx| {
16771                            window.dispatch_action(Box::new(Cancel), cx)
16772                        })
16773                        .tooltip(|window, cx| {
16774                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16775                        })
16776                }))
16777            })
16778            .child(
16779                IconButton::new("copy-block", IconName::Copy)
16780                    .icon_color(Color::Muted)
16781                    .size(ButtonSize::Compact)
16782                    .style(ButtonStyle::Transparent)
16783                    .visible_on_hover(group_id.clone())
16784                    .on_click({
16785                        let message = diagnostic.message.clone();
16786                        move |_click, _, cx| {
16787                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16788                        }
16789                    })
16790                    .tooltip(Tooltip::text("Copy diagnostic message")),
16791            )
16792        };
16793
16794        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16795            AvailableSpace::min_size(),
16796            cx.window,
16797            cx.app,
16798        );
16799
16800        h_flex()
16801            .id(cx.block_id)
16802            .group(group_id.clone())
16803            .relative()
16804            .size_full()
16805            .block_mouse_down()
16806            .pl(cx.gutter_dimensions.width)
16807            .w(cx.max_width - cx.gutter_dimensions.full_width())
16808            .child(
16809                div()
16810                    .flex()
16811                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16812                    .flex_shrink(),
16813            )
16814            .child(buttons(&diagnostic))
16815            .child(div().flex().flex_shrink_0().child(
16816                StyledText::new(text_without_backticks.clone()).with_highlights(
16817                    &text_style,
16818                    code_ranges.iter().map(|range| {
16819                        (
16820                            range.clone(),
16821                            HighlightStyle {
16822                                font_weight: Some(FontWeight::BOLD),
16823                                ..Default::default()
16824                            },
16825                        )
16826                    }),
16827                ),
16828            ))
16829            .into_any_element()
16830    })
16831}
16832
16833fn inline_completion_edit_text(
16834    current_snapshot: &BufferSnapshot,
16835    edits: &[(Range<Anchor>, String)],
16836    edit_preview: &EditPreview,
16837    include_deletions: bool,
16838    cx: &App,
16839) -> HighlightedText {
16840    let edits = edits
16841        .iter()
16842        .map(|(anchor, text)| {
16843            (
16844                anchor.start.text_anchor..anchor.end.text_anchor,
16845                text.clone(),
16846            )
16847        })
16848        .collect::<Vec<_>>();
16849
16850    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16851}
16852
16853pub fn highlight_diagnostic_message(
16854    diagnostic: &Diagnostic,
16855    mut max_message_rows: Option<u8>,
16856) -> (SharedString, Vec<Range<usize>>) {
16857    let mut text_without_backticks = String::new();
16858    let mut code_ranges = Vec::new();
16859
16860    if let Some(source) = &diagnostic.source {
16861        text_without_backticks.push_str(source);
16862        code_ranges.push(0..source.len());
16863        text_without_backticks.push_str(": ");
16864    }
16865
16866    let mut prev_offset = 0;
16867    let mut in_code_block = false;
16868    let has_row_limit = max_message_rows.is_some();
16869    let mut newline_indices = diagnostic
16870        .message
16871        .match_indices('\n')
16872        .filter(|_| has_row_limit)
16873        .map(|(ix, _)| ix)
16874        .fuse()
16875        .peekable();
16876
16877    for (quote_ix, _) in diagnostic
16878        .message
16879        .match_indices('`')
16880        .chain([(diagnostic.message.len(), "")])
16881    {
16882        let mut first_newline_ix = None;
16883        let mut last_newline_ix = None;
16884        while let Some(newline_ix) = newline_indices.peek() {
16885            if *newline_ix < quote_ix {
16886                if first_newline_ix.is_none() {
16887                    first_newline_ix = Some(*newline_ix);
16888                }
16889                last_newline_ix = Some(*newline_ix);
16890
16891                if let Some(rows_left) = &mut max_message_rows {
16892                    if *rows_left == 0 {
16893                        break;
16894                    } else {
16895                        *rows_left -= 1;
16896                    }
16897                }
16898                let _ = newline_indices.next();
16899            } else {
16900                break;
16901            }
16902        }
16903        let prev_len = text_without_backticks.len();
16904        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16905        text_without_backticks.push_str(new_text);
16906        if in_code_block {
16907            code_ranges.push(prev_len..text_without_backticks.len());
16908        }
16909        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16910        in_code_block = !in_code_block;
16911        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16912            text_without_backticks.push_str("...");
16913            break;
16914        }
16915    }
16916
16917    (text_without_backticks.into(), code_ranges)
16918}
16919
16920fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16921    match severity {
16922        DiagnosticSeverity::ERROR => colors.error,
16923        DiagnosticSeverity::WARNING => colors.warning,
16924        DiagnosticSeverity::INFORMATION => colors.info,
16925        DiagnosticSeverity::HINT => colors.info,
16926        _ => colors.ignored,
16927    }
16928}
16929
16930pub fn styled_runs_for_code_label<'a>(
16931    label: &'a CodeLabel,
16932    syntax_theme: &'a theme::SyntaxTheme,
16933) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16934    let fade_out = HighlightStyle {
16935        fade_out: Some(0.35),
16936        ..Default::default()
16937    };
16938
16939    let mut prev_end = label.filter_range.end;
16940    label
16941        .runs
16942        .iter()
16943        .enumerate()
16944        .flat_map(move |(ix, (range, highlight_id))| {
16945            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16946                style
16947            } else {
16948                return Default::default();
16949            };
16950            let mut muted_style = style;
16951            muted_style.highlight(fade_out);
16952
16953            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16954            if range.start >= label.filter_range.end {
16955                if range.start > prev_end {
16956                    runs.push((prev_end..range.start, fade_out));
16957                }
16958                runs.push((range.clone(), muted_style));
16959            } else if range.end <= label.filter_range.end {
16960                runs.push((range.clone(), style));
16961            } else {
16962                runs.push((range.start..label.filter_range.end, style));
16963                runs.push((label.filter_range.end..range.end, muted_style));
16964            }
16965            prev_end = cmp::max(prev_end, range.end);
16966
16967            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16968                runs.push((prev_end..label.text.len(), fade_out));
16969            }
16970
16971            runs
16972        })
16973}
16974
16975pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16976    let mut prev_index = 0;
16977    let mut prev_codepoint: Option<char> = None;
16978    text.char_indices()
16979        .chain([(text.len(), '\0')])
16980        .filter_map(move |(index, codepoint)| {
16981            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16982            let is_boundary = index == text.len()
16983                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16984                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16985            if is_boundary {
16986                let chunk = &text[prev_index..index];
16987                prev_index = index;
16988                Some(chunk)
16989            } else {
16990                None
16991            }
16992        })
16993}
16994
16995pub trait RangeToAnchorExt: Sized {
16996    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16997
16998    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16999        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17000        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17001    }
17002}
17003
17004impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17005    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17006        let start_offset = self.start.to_offset(snapshot);
17007        let end_offset = self.end.to_offset(snapshot);
17008        if start_offset == end_offset {
17009            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17010        } else {
17011            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17012        }
17013    }
17014}
17015
17016pub trait RowExt {
17017    fn as_f32(&self) -> f32;
17018
17019    fn next_row(&self) -> Self;
17020
17021    fn previous_row(&self) -> Self;
17022
17023    fn minus(&self, other: Self) -> u32;
17024}
17025
17026impl RowExt for DisplayRow {
17027    fn as_f32(&self) -> f32 {
17028        self.0 as f32
17029    }
17030
17031    fn next_row(&self) -> Self {
17032        Self(self.0 + 1)
17033    }
17034
17035    fn previous_row(&self) -> Self {
17036        Self(self.0.saturating_sub(1))
17037    }
17038
17039    fn minus(&self, other: Self) -> u32 {
17040        self.0 - other.0
17041    }
17042}
17043
17044impl RowExt for MultiBufferRow {
17045    fn as_f32(&self) -> f32 {
17046        self.0 as f32
17047    }
17048
17049    fn next_row(&self) -> Self {
17050        Self(self.0 + 1)
17051    }
17052
17053    fn previous_row(&self) -> Self {
17054        Self(self.0.saturating_sub(1))
17055    }
17056
17057    fn minus(&self, other: Self) -> u32 {
17058        self.0 - other.0
17059    }
17060}
17061
17062trait RowRangeExt {
17063    type Row;
17064
17065    fn len(&self) -> usize;
17066
17067    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17068}
17069
17070impl RowRangeExt for Range<MultiBufferRow> {
17071    type Row = MultiBufferRow;
17072
17073    fn len(&self) -> usize {
17074        (self.end.0 - self.start.0) as usize
17075    }
17076
17077    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17078        (self.start.0..self.end.0).map(MultiBufferRow)
17079    }
17080}
17081
17082impl RowRangeExt for Range<DisplayRow> {
17083    type Row = DisplayRow;
17084
17085    fn len(&self) -> usize {
17086        (self.end.0 - self.start.0) as usize
17087    }
17088
17089    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17090        (self.start.0..self.end.0).map(DisplayRow)
17091    }
17092}
17093
17094/// If select range has more than one line, we
17095/// just point the cursor to range.start.
17096fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17097    if range.start.row == range.end.row {
17098        range
17099    } else {
17100        range.start..range.start
17101    }
17102}
17103pub struct KillRing(ClipboardItem);
17104impl Global for KillRing {}
17105
17106const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17107
17108fn all_edits_insertions_or_deletions(
17109    edits: &Vec<(Range<Anchor>, String)>,
17110    snapshot: &MultiBufferSnapshot,
17111) -> bool {
17112    let mut all_insertions = true;
17113    let mut all_deletions = true;
17114
17115    for (range, new_text) in edits.iter() {
17116        let range_is_empty = range.to_offset(&snapshot).is_empty();
17117        let text_is_empty = new_text.is_empty();
17118
17119        if range_is_empty != text_is_empty {
17120            if range_is_empty {
17121                all_deletions = false;
17122            } else {
17123                all_insertions = false;
17124            }
17125        } else {
17126            return false;
17127        }
17128
17129        if !all_insertions && !all_deletions {
17130            return false;
17131        }
17132    }
17133    all_insertions || all_deletions
17134}