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    #[allow(clippy::too_many_arguments)]
 5938    fn render_edit_prediction_cursor_popover(
 5939        &self,
 5940        min_width: Pixels,
 5941        max_width: Pixels,
 5942        cursor_point: Point,
 5943        style: &EditorStyle,
 5944        accept_keystroke: Option<&gpui::Keystroke>,
 5945        _window: &Window,
 5946        cx: &mut Context<Editor>,
 5947    ) -> Option<AnyElement> {
 5948        let provider = self.edit_prediction_provider.as_ref()?;
 5949
 5950        if provider.provider.needs_terms_acceptance(cx) {
 5951            return Some(
 5952                h_flex()
 5953                    .min_w(min_width)
 5954                    .flex_1()
 5955                    .px_2()
 5956                    .py_1()
 5957                    .gap_3()
 5958                    .elevation_2(cx)
 5959                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5960                    .id("accept-terms")
 5961                    .cursor_pointer()
 5962                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5963                    .on_click(cx.listener(|this, _event, window, cx| {
 5964                        cx.stop_propagation();
 5965                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5966                        window.dispatch_action(
 5967                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5968                            cx,
 5969                        );
 5970                    }))
 5971                    .child(
 5972                        h_flex()
 5973                            .flex_1()
 5974                            .gap_2()
 5975                            .child(Icon::new(IconName::ZedPredict))
 5976                            .child(Label::new("Accept Terms of Service"))
 5977                            .child(div().w_full())
 5978                            .child(
 5979                                Icon::new(IconName::ArrowUpRight)
 5980                                    .color(Color::Muted)
 5981                                    .size(IconSize::Small),
 5982                            )
 5983                            .into_any_element(),
 5984                    )
 5985                    .into_any(),
 5986            );
 5987        }
 5988
 5989        let is_refreshing = provider.provider.is_refreshing(cx);
 5990
 5991        fn pending_completion_container() -> Div {
 5992            h_flex()
 5993                .h_full()
 5994                .flex_1()
 5995                .gap_2()
 5996                .child(Icon::new(IconName::ZedPredict))
 5997        }
 5998
 5999        let completion = match &self.active_inline_completion {
 6000            Some(completion) => match &completion.completion {
 6001                InlineCompletion::Move {
 6002                    target, snapshot, ..
 6003                } if !self.has_visible_completions_menu() => {
 6004                    use text::ToPoint as _;
 6005
 6006                    return Some(
 6007                        h_flex()
 6008                            .px_2()
 6009                            .py_1()
 6010                            .elevation_2(cx)
 6011                            .border_color(cx.theme().colors().border)
 6012                            .rounded_tl(px(0.))
 6013                            .gap_2()
 6014                            .child(
 6015                                if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6016                                    Icon::new(IconName::ZedPredictDown)
 6017                                } else {
 6018                                    Icon::new(IconName::ZedPredictUp)
 6019                                },
 6020                            )
 6021                            .child(Label::new("Hold").size(LabelSize::Small))
 6022                            .child(h_flex().children(ui::render_modifiers(
 6023                                &accept_keystroke?.modifiers,
 6024                                PlatformStyle::platform(),
 6025                                Some(Color::Default),
 6026                                Some(IconSize::Small.rems().into()),
 6027                                false,
 6028                            )))
 6029                            .into_any(),
 6030                    );
 6031                }
 6032                _ => self.render_edit_prediction_cursor_popover_preview(
 6033                    completion,
 6034                    cursor_point,
 6035                    style,
 6036                    cx,
 6037                )?,
 6038            },
 6039
 6040            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 6041                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 6042                    stale_completion,
 6043                    cursor_point,
 6044                    style,
 6045                    cx,
 6046                )?,
 6047
 6048                None => {
 6049                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 6050                }
 6051            },
 6052
 6053            None => pending_completion_container().child(Label::new("No Prediction")),
 6054        };
 6055
 6056        let completion = if is_refreshing {
 6057            completion
 6058                .with_animation(
 6059                    "loading-completion",
 6060                    Animation::new(Duration::from_secs(2))
 6061                        .repeat()
 6062                        .with_easing(pulsating_between(0.4, 0.8)),
 6063                    |label, delta| label.opacity(delta),
 6064                )
 6065                .into_any_element()
 6066        } else {
 6067            completion.into_any_element()
 6068        };
 6069
 6070        let has_completion = self.active_inline_completion.is_some();
 6071
 6072        let is_platform_style_mac = PlatformStyle::platform() == PlatformStyle::Mac;
 6073        Some(
 6074            h_flex()
 6075                .min_w(min_width)
 6076                .max_w(max_width)
 6077                .flex_1()
 6078                .elevation_2(cx)
 6079                .border_color(cx.theme().colors().border)
 6080                .child(
 6081                    div()
 6082                        .flex_1()
 6083                        .py_1()
 6084                        .px_2()
 6085                        .overflow_hidden()
 6086                        .child(completion),
 6087                )
 6088                .when_some(accept_keystroke, |el, accept_keystroke| {
 6089                    if !accept_keystroke.modifiers.modified() {
 6090                        return el;
 6091                    }
 6092
 6093                    el.child(
 6094                        h_flex()
 6095                            .h_full()
 6096                            .border_l_1()
 6097                            .rounded_r_lg()
 6098                            .border_color(cx.theme().colors().border)
 6099                            .bg(Self::edit_prediction_line_popover_bg_color(cx))
 6100                            .gap_1()
 6101                            .py_1()
 6102                            .px_2()
 6103                            .child(
 6104                                h_flex()
 6105                                    .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6106                                    .when(is_platform_style_mac, |parent| parent.gap_1())
 6107                                    .child(h_flex().children(ui::render_modifiers(
 6108                                        &accept_keystroke.modifiers,
 6109                                        PlatformStyle::platform(),
 6110                                        Some(if !has_completion {
 6111                                            Color::Muted
 6112                                        } else {
 6113                                            Color::Default
 6114                                        }),
 6115                                        None,
 6116                                        false,
 6117                                    ))),
 6118                            )
 6119                            .child(Label::new("Preview").into_any_element())
 6120                            .opacity(if has_completion { 1.0 } else { 0.4 }),
 6121                    )
 6122                })
 6123                .into_any(),
 6124        )
 6125    }
 6126
 6127    fn render_edit_prediction_cursor_popover_preview(
 6128        &self,
 6129        completion: &InlineCompletionState,
 6130        cursor_point: Point,
 6131        style: &EditorStyle,
 6132        cx: &mut Context<Editor>,
 6133    ) -> Option<Div> {
 6134        use text::ToPoint as _;
 6135
 6136        fn render_relative_row_jump(
 6137            prefix: impl Into<String>,
 6138            current_row: u32,
 6139            target_row: u32,
 6140        ) -> Div {
 6141            let (row_diff, arrow) = if target_row < current_row {
 6142                (current_row - target_row, IconName::ArrowUp)
 6143            } else {
 6144                (target_row - current_row, IconName::ArrowDown)
 6145            };
 6146
 6147            h_flex()
 6148                .child(
 6149                    Label::new(format!("{}{}", prefix.into(), row_diff))
 6150                        .color(Color::Muted)
 6151                        .size(LabelSize::Small),
 6152                )
 6153                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 6154        }
 6155
 6156        match &completion.completion {
 6157            InlineCompletion::Move {
 6158                target, snapshot, ..
 6159            } => Some(
 6160                h_flex()
 6161                    .px_2()
 6162                    .gap_2()
 6163                    .flex_1()
 6164                    .child(
 6165                        if target.text_anchor.to_point(&snapshot).row > cursor_point.row {
 6166                            Icon::new(IconName::ZedPredictDown)
 6167                        } else {
 6168                            Icon::new(IconName::ZedPredictUp)
 6169                        },
 6170                    )
 6171                    .child(Label::new("Jump to Edit")),
 6172            ),
 6173
 6174            InlineCompletion::Edit {
 6175                edits,
 6176                edit_preview,
 6177                snapshot,
 6178                display_mode: _,
 6179            } => {
 6180                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 6181
 6182                let (highlighted_edits, has_more_lines) = crate::inline_completion_edit_text(
 6183                    &snapshot,
 6184                    &edits,
 6185                    edit_preview.as_ref()?,
 6186                    true,
 6187                    cx,
 6188                )
 6189                .first_line_preview();
 6190
 6191                let styled_text = gpui::StyledText::new(highlighted_edits.text)
 6192                    .with_highlights(&style.text, highlighted_edits.highlights);
 6193
 6194                let preview = h_flex()
 6195                    .gap_1()
 6196                    .min_w_16()
 6197                    .child(styled_text)
 6198                    .when(has_more_lines, |parent| parent.child(""));
 6199
 6200                let left = if first_edit_row != cursor_point.row {
 6201                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 6202                        .into_any_element()
 6203                } else {
 6204                    Icon::new(IconName::ZedPredict).into_any_element()
 6205                };
 6206
 6207                Some(
 6208                    h_flex()
 6209                        .h_full()
 6210                        .flex_1()
 6211                        .gap_2()
 6212                        .pr_1()
 6213                        .overflow_x_hidden()
 6214                        .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
 6215                        .child(left)
 6216                        .child(preview),
 6217                )
 6218            }
 6219        }
 6220    }
 6221
 6222    fn render_context_menu(
 6223        &self,
 6224        style: &EditorStyle,
 6225        max_height_in_lines: u32,
 6226        y_flipped: bool,
 6227        window: &mut Window,
 6228        cx: &mut Context<Editor>,
 6229    ) -> Option<AnyElement> {
 6230        let menu = self.context_menu.borrow();
 6231        let menu = menu.as_ref()?;
 6232        if !menu.visible() {
 6233            return None;
 6234        };
 6235        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 6236    }
 6237
 6238    fn render_context_menu_aside(
 6239        &mut self,
 6240        max_size: Size<Pixels>,
 6241        window: &mut Window,
 6242        cx: &mut Context<Editor>,
 6243    ) -> Option<AnyElement> {
 6244        self.context_menu.borrow_mut().as_mut().and_then(|menu| {
 6245            if menu.visible() {
 6246                menu.render_aside(self, max_size, window, cx)
 6247            } else {
 6248                None
 6249            }
 6250        })
 6251    }
 6252
 6253    fn hide_context_menu(
 6254        &mut self,
 6255        window: &mut Window,
 6256        cx: &mut Context<Self>,
 6257    ) -> Option<CodeContextMenu> {
 6258        cx.notify();
 6259        self.completion_tasks.clear();
 6260        let context_menu = self.context_menu.borrow_mut().take();
 6261        self.stale_inline_completion_in_menu.take();
 6262        self.update_visible_inline_completion(window, cx);
 6263        context_menu
 6264    }
 6265
 6266    fn show_snippet_choices(
 6267        &mut self,
 6268        choices: &Vec<String>,
 6269        selection: Range<Anchor>,
 6270        cx: &mut Context<Self>,
 6271    ) {
 6272        if selection.start.buffer_id.is_none() {
 6273            return;
 6274        }
 6275        let buffer_id = selection.start.buffer_id.unwrap();
 6276        let buffer = self.buffer().read(cx).buffer(buffer_id);
 6277        let id = post_inc(&mut self.next_completion_id);
 6278
 6279        if let Some(buffer) = buffer {
 6280            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 6281                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 6282            ));
 6283        }
 6284    }
 6285
 6286    pub fn insert_snippet(
 6287        &mut self,
 6288        insertion_ranges: &[Range<usize>],
 6289        snippet: Snippet,
 6290        window: &mut Window,
 6291        cx: &mut Context<Self>,
 6292    ) -> Result<()> {
 6293        struct Tabstop<T> {
 6294            is_end_tabstop: bool,
 6295            ranges: Vec<Range<T>>,
 6296            choices: Option<Vec<String>>,
 6297        }
 6298
 6299        let tabstops = self.buffer.update(cx, |buffer, cx| {
 6300            let snippet_text: Arc<str> = snippet.text.clone().into();
 6301            buffer.edit(
 6302                insertion_ranges
 6303                    .iter()
 6304                    .cloned()
 6305                    .map(|range| (range, snippet_text.clone())),
 6306                Some(AutoindentMode::EachLine),
 6307                cx,
 6308            );
 6309
 6310            let snapshot = &*buffer.read(cx);
 6311            let snippet = &snippet;
 6312            snippet
 6313                .tabstops
 6314                .iter()
 6315                .map(|tabstop| {
 6316                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 6317                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 6318                    });
 6319                    let mut tabstop_ranges = tabstop
 6320                        .ranges
 6321                        .iter()
 6322                        .flat_map(|tabstop_range| {
 6323                            let mut delta = 0_isize;
 6324                            insertion_ranges.iter().map(move |insertion_range| {
 6325                                let insertion_start = insertion_range.start as isize + delta;
 6326                                delta +=
 6327                                    snippet.text.len() as isize - insertion_range.len() as isize;
 6328
 6329                                let start = ((insertion_start + tabstop_range.start) as usize)
 6330                                    .min(snapshot.len());
 6331                                let end = ((insertion_start + tabstop_range.end) as usize)
 6332                                    .min(snapshot.len());
 6333                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 6334                            })
 6335                        })
 6336                        .collect::<Vec<_>>();
 6337                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 6338
 6339                    Tabstop {
 6340                        is_end_tabstop,
 6341                        ranges: tabstop_ranges,
 6342                        choices: tabstop.choices.clone(),
 6343                    }
 6344                })
 6345                .collect::<Vec<_>>()
 6346        });
 6347        if let Some(tabstop) = tabstops.first() {
 6348            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6349                s.select_ranges(tabstop.ranges.iter().cloned());
 6350            });
 6351
 6352            if let Some(choices) = &tabstop.choices {
 6353                if let Some(selection) = tabstop.ranges.first() {
 6354                    self.show_snippet_choices(choices, selection.clone(), cx)
 6355                }
 6356            }
 6357
 6358            // If we're already at the last tabstop and it's at the end of the snippet,
 6359            // we're done, we don't need to keep the state around.
 6360            if !tabstop.is_end_tabstop {
 6361                let choices = tabstops
 6362                    .iter()
 6363                    .map(|tabstop| tabstop.choices.clone())
 6364                    .collect();
 6365
 6366                let ranges = tabstops
 6367                    .into_iter()
 6368                    .map(|tabstop| tabstop.ranges)
 6369                    .collect::<Vec<_>>();
 6370
 6371                self.snippet_stack.push(SnippetState {
 6372                    active_index: 0,
 6373                    ranges,
 6374                    choices,
 6375                });
 6376            }
 6377
 6378            // Check whether the just-entered snippet ends with an auto-closable bracket.
 6379            if self.autoclose_regions.is_empty() {
 6380                let snapshot = self.buffer.read(cx).snapshot(cx);
 6381                for selection in &mut self.selections.all::<Point>(cx) {
 6382                    let selection_head = selection.head();
 6383                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 6384                        continue;
 6385                    };
 6386
 6387                    let mut bracket_pair = None;
 6388                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 6389                    let prev_chars = snapshot
 6390                        .reversed_chars_at(selection_head)
 6391                        .collect::<String>();
 6392                    for (pair, enabled) in scope.brackets() {
 6393                        if enabled
 6394                            && pair.close
 6395                            && prev_chars.starts_with(pair.start.as_str())
 6396                            && next_chars.starts_with(pair.end.as_str())
 6397                        {
 6398                            bracket_pair = Some(pair.clone());
 6399                            break;
 6400                        }
 6401                    }
 6402                    if let Some(pair) = bracket_pair {
 6403                        let start = snapshot.anchor_after(selection_head);
 6404                        let end = snapshot.anchor_after(selection_head);
 6405                        self.autoclose_regions.push(AutocloseRegion {
 6406                            selection_id: selection.id,
 6407                            range: start..end,
 6408                            pair,
 6409                        });
 6410                    }
 6411                }
 6412            }
 6413        }
 6414        Ok(())
 6415    }
 6416
 6417    pub fn move_to_next_snippet_tabstop(
 6418        &mut self,
 6419        window: &mut Window,
 6420        cx: &mut Context<Self>,
 6421    ) -> bool {
 6422        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6423    }
 6424
 6425    pub fn move_to_prev_snippet_tabstop(
 6426        &mut self,
 6427        window: &mut Window,
 6428        cx: &mut Context<Self>,
 6429    ) -> bool {
 6430        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6431    }
 6432
 6433    pub fn move_to_snippet_tabstop(
 6434        &mut self,
 6435        bias: Bias,
 6436        window: &mut Window,
 6437        cx: &mut Context<Self>,
 6438    ) -> bool {
 6439        if let Some(mut snippet) = self.snippet_stack.pop() {
 6440            match bias {
 6441                Bias::Left => {
 6442                    if snippet.active_index > 0 {
 6443                        snippet.active_index -= 1;
 6444                    } else {
 6445                        self.snippet_stack.push(snippet);
 6446                        return false;
 6447                    }
 6448                }
 6449                Bias::Right => {
 6450                    if snippet.active_index + 1 < snippet.ranges.len() {
 6451                        snippet.active_index += 1;
 6452                    } else {
 6453                        self.snippet_stack.push(snippet);
 6454                        return false;
 6455                    }
 6456                }
 6457            }
 6458            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6459                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6460                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6461                });
 6462
 6463                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6464                    if let Some(selection) = current_ranges.first() {
 6465                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6466                    }
 6467                }
 6468
 6469                // If snippet state is not at the last tabstop, push it back on the stack
 6470                if snippet.active_index + 1 < snippet.ranges.len() {
 6471                    self.snippet_stack.push(snippet);
 6472                }
 6473                return true;
 6474            }
 6475        }
 6476
 6477        false
 6478    }
 6479
 6480    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6481        self.transact(window, cx, |this, window, cx| {
 6482            this.select_all(&SelectAll, window, cx);
 6483            this.insert("", window, cx);
 6484        });
 6485    }
 6486
 6487    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6488        self.transact(window, cx, |this, window, cx| {
 6489            this.select_autoclose_pair(window, cx);
 6490            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6491            if !this.linked_edit_ranges.is_empty() {
 6492                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6493                let snapshot = this.buffer.read(cx).snapshot(cx);
 6494
 6495                for selection in selections.iter() {
 6496                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6497                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6498                    if selection_start.buffer_id != selection_end.buffer_id {
 6499                        continue;
 6500                    }
 6501                    if let Some(ranges) =
 6502                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6503                    {
 6504                        for (buffer, entries) in ranges {
 6505                            linked_ranges.entry(buffer).or_default().extend(entries);
 6506                        }
 6507                    }
 6508                }
 6509            }
 6510
 6511            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6512            if !this.selections.line_mode {
 6513                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6514                for selection in &mut selections {
 6515                    if selection.is_empty() {
 6516                        let old_head = selection.head();
 6517                        let mut new_head =
 6518                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6519                                .to_point(&display_map);
 6520                        if let Some((buffer, line_buffer_range)) = display_map
 6521                            .buffer_snapshot
 6522                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6523                        {
 6524                            let indent_size =
 6525                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6526                            let indent_len = match indent_size.kind {
 6527                                IndentKind::Space => {
 6528                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6529                                }
 6530                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6531                            };
 6532                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6533                                let indent_len = indent_len.get();
 6534                                new_head = cmp::min(
 6535                                    new_head,
 6536                                    MultiBufferPoint::new(
 6537                                        old_head.row,
 6538                                        ((old_head.column - 1) / indent_len) * indent_len,
 6539                                    ),
 6540                                );
 6541                            }
 6542                        }
 6543
 6544                        selection.set_head(new_head, SelectionGoal::None);
 6545                    }
 6546                }
 6547            }
 6548
 6549            this.signature_help_state.set_backspace_pressed(true);
 6550            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6551                s.select(selections)
 6552            });
 6553            this.insert("", window, cx);
 6554            let empty_str: Arc<str> = Arc::from("");
 6555            for (buffer, edits) in linked_ranges {
 6556                let snapshot = buffer.read(cx).snapshot();
 6557                use text::ToPoint as TP;
 6558
 6559                let edits = edits
 6560                    .into_iter()
 6561                    .map(|range| {
 6562                        let end_point = TP::to_point(&range.end, &snapshot);
 6563                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6564
 6565                        if end_point == start_point {
 6566                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6567                                .saturating_sub(1);
 6568                            start_point =
 6569                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6570                        };
 6571
 6572                        (start_point..end_point, empty_str.clone())
 6573                    })
 6574                    .sorted_by_key(|(range, _)| range.start)
 6575                    .collect::<Vec<_>>();
 6576                buffer.update(cx, |this, cx| {
 6577                    this.edit(edits, None, cx);
 6578                })
 6579            }
 6580            this.refresh_inline_completion(true, false, window, cx);
 6581            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6582        });
 6583    }
 6584
 6585    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6586        self.transact(window, cx, |this, window, cx| {
 6587            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6588                let line_mode = s.line_mode;
 6589                s.move_with(|map, selection| {
 6590                    if selection.is_empty() && !line_mode {
 6591                        let cursor = movement::right(map, selection.head());
 6592                        selection.end = cursor;
 6593                        selection.reversed = true;
 6594                        selection.goal = SelectionGoal::None;
 6595                    }
 6596                })
 6597            });
 6598            this.insert("", window, cx);
 6599            this.refresh_inline_completion(true, false, window, cx);
 6600        });
 6601    }
 6602
 6603    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6604        if self.move_to_prev_snippet_tabstop(window, cx) {
 6605            return;
 6606        }
 6607
 6608        self.outdent(&Outdent, window, cx);
 6609    }
 6610
 6611    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6612        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6613            return;
 6614        }
 6615
 6616        let mut selections = self.selections.all_adjusted(cx);
 6617        let buffer = self.buffer.read(cx);
 6618        let snapshot = buffer.snapshot(cx);
 6619        let rows_iter = selections.iter().map(|s| s.head().row);
 6620        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6621
 6622        let mut edits = Vec::new();
 6623        let mut prev_edited_row = 0;
 6624        let mut row_delta = 0;
 6625        for selection in &mut selections {
 6626            if selection.start.row != prev_edited_row {
 6627                row_delta = 0;
 6628            }
 6629            prev_edited_row = selection.end.row;
 6630
 6631            // If the selection is non-empty, then increase the indentation of the selected lines.
 6632            if !selection.is_empty() {
 6633                row_delta =
 6634                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6635                continue;
 6636            }
 6637
 6638            // If the selection is empty and the cursor is in the leading whitespace before the
 6639            // suggested indentation, then auto-indent the line.
 6640            let cursor = selection.head();
 6641            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6642            if let Some(suggested_indent) =
 6643                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6644            {
 6645                if cursor.column < suggested_indent.len
 6646                    && cursor.column <= current_indent.len
 6647                    && current_indent.len <= suggested_indent.len
 6648                {
 6649                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6650                    selection.end = selection.start;
 6651                    if row_delta == 0 {
 6652                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6653                            cursor.row,
 6654                            current_indent,
 6655                            suggested_indent,
 6656                        ));
 6657                        row_delta = suggested_indent.len - current_indent.len;
 6658                    }
 6659                    continue;
 6660                }
 6661            }
 6662
 6663            // Otherwise, insert a hard or soft tab.
 6664            let settings = buffer.settings_at(cursor, cx);
 6665            let tab_size = if settings.hard_tabs {
 6666                IndentSize::tab()
 6667            } else {
 6668                let tab_size = settings.tab_size.get();
 6669                let char_column = snapshot
 6670                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6671                    .flat_map(str::chars)
 6672                    .count()
 6673                    + row_delta as usize;
 6674                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6675                IndentSize::spaces(chars_to_next_tab_stop)
 6676            };
 6677            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6678            selection.end = selection.start;
 6679            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6680            row_delta += tab_size.len;
 6681        }
 6682
 6683        self.transact(window, cx, |this, window, cx| {
 6684            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6685            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6686                s.select(selections)
 6687            });
 6688            this.refresh_inline_completion(true, false, window, cx);
 6689        });
 6690    }
 6691
 6692    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6693        if self.read_only(cx) {
 6694            return;
 6695        }
 6696        let mut selections = self.selections.all::<Point>(cx);
 6697        let mut prev_edited_row = 0;
 6698        let mut row_delta = 0;
 6699        let mut edits = Vec::new();
 6700        let buffer = self.buffer.read(cx);
 6701        let snapshot = buffer.snapshot(cx);
 6702        for selection in &mut selections {
 6703            if selection.start.row != prev_edited_row {
 6704                row_delta = 0;
 6705            }
 6706            prev_edited_row = selection.end.row;
 6707
 6708            row_delta =
 6709                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6710        }
 6711
 6712        self.transact(window, cx, |this, window, cx| {
 6713            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6714            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6715                s.select(selections)
 6716            });
 6717        });
 6718    }
 6719
 6720    fn indent_selection(
 6721        buffer: &MultiBuffer,
 6722        snapshot: &MultiBufferSnapshot,
 6723        selection: &mut Selection<Point>,
 6724        edits: &mut Vec<(Range<Point>, String)>,
 6725        delta_for_start_row: u32,
 6726        cx: &App,
 6727    ) -> u32 {
 6728        let settings = buffer.settings_at(selection.start, cx);
 6729        let tab_size = settings.tab_size.get();
 6730        let indent_kind = if settings.hard_tabs {
 6731            IndentKind::Tab
 6732        } else {
 6733            IndentKind::Space
 6734        };
 6735        let mut start_row = selection.start.row;
 6736        let mut end_row = selection.end.row + 1;
 6737
 6738        // If a selection ends at the beginning of a line, don't indent
 6739        // that last line.
 6740        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6741            end_row -= 1;
 6742        }
 6743
 6744        // Avoid re-indenting a row that has already been indented by a
 6745        // previous selection, but still update this selection's column
 6746        // to reflect that indentation.
 6747        if delta_for_start_row > 0 {
 6748            start_row += 1;
 6749            selection.start.column += delta_for_start_row;
 6750            if selection.end.row == selection.start.row {
 6751                selection.end.column += delta_for_start_row;
 6752            }
 6753        }
 6754
 6755        let mut delta_for_end_row = 0;
 6756        let has_multiple_rows = start_row + 1 != end_row;
 6757        for row in start_row..end_row {
 6758            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6759            let indent_delta = match (current_indent.kind, indent_kind) {
 6760                (IndentKind::Space, IndentKind::Space) => {
 6761                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6762                    IndentSize::spaces(columns_to_next_tab_stop)
 6763                }
 6764                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6765                (_, IndentKind::Tab) => IndentSize::tab(),
 6766            };
 6767
 6768            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6769                0
 6770            } else {
 6771                selection.start.column
 6772            };
 6773            let row_start = Point::new(row, start);
 6774            edits.push((
 6775                row_start..row_start,
 6776                indent_delta.chars().collect::<String>(),
 6777            ));
 6778
 6779            // Update this selection's endpoints to reflect the indentation.
 6780            if row == selection.start.row {
 6781                selection.start.column += indent_delta.len;
 6782            }
 6783            if row == selection.end.row {
 6784                selection.end.column += indent_delta.len;
 6785                delta_for_end_row = indent_delta.len;
 6786            }
 6787        }
 6788
 6789        if selection.start.row == selection.end.row {
 6790            delta_for_start_row + delta_for_end_row
 6791        } else {
 6792            delta_for_end_row
 6793        }
 6794    }
 6795
 6796    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6797        if self.read_only(cx) {
 6798            return;
 6799        }
 6800        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6801        let selections = self.selections.all::<Point>(cx);
 6802        let mut deletion_ranges = Vec::new();
 6803        let mut last_outdent = None;
 6804        {
 6805            let buffer = self.buffer.read(cx);
 6806            let snapshot = buffer.snapshot(cx);
 6807            for selection in &selections {
 6808                let settings = buffer.settings_at(selection.start, cx);
 6809                let tab_size = settings.tab_size.get();
 6810                let mut rows = selection.spanned_rows(false, &display_map);
 6811
 6812                // Avoid re-outdenting a row that has already been outdented by a
 6813                // previous selection.
 6814                if let Some(last_row) = last_outdent {
 6815                    if last_row == rows.start {
 6816                        rows.start = rows.start.next_row();
 6817                    }
 6818                }
 6819                let has_multiple_rows = rows.len() > 1;
 6820                for row in rows.iter_rows() {
 6821                    let indent_size = snapshot.indent_size_for_line(row);
 6822                    if indent_size.len > 0 {
 6823                        let deletion_len = match indent_size.kind {
 6824                            IndentKind::Space => {
 6825                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6826                                if columns_to_prev_tab_stop == 0 {
 6827                                    tab_size
 6828                                } else {
 6829                                    columns_to_prev_tab_stop
 6830                                }
 6831                            }
 6832                            IndentKind::Tab => 1,
 6833                        };
 6834                        let start = if has_multiple_rows
 6835                            || deletion_len > selection.start.column
 6836                            || indent_size.len < selection.start.column
 6837                        {
 6838                            0
 6839                        } else {
 6840                            selection.start.column - deletion_len
 6841                        };
 6842                        deletion_ranges.push(
 6843                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6844                        );
 6845                        last_outdent = Some(row);
 6846                    }
 6847                }
 6848            }
 6849        }
 6850
 6851        self.transact(window, cx, |this, window, cx| {
 6852            this.buffer.update(cx, |buffer, cx| {
 6853                let empty_str: Arc<str> = Arc::default();
 6854                buffer.edit(
 6855                    deletion_ranges
 6856                        .into_iter()
 6857                        .map(|range| (range, empty_str.clone())),
 6858                    None,
 6859                    cx,
 6860                );
 6861            });
 6862            let selections = this.selections.all::<usize>(cx);
 6863            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6864                s.select(selections)
 6865            });
 6866        });
 6867    }
 6868
 6869    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6870        if self.read_only(cx) {
 6871            return;
 6872        }
 6873        let selections = self
 6874            .selections
 6875            .all::<usize>(cx)
 6876            .into_iter()
 6877            .map(|s| s.range());
 6878
 6879        self.transact(window, cx, |this, window, cx| {
 6880            this.buffer.update(cx, |buffer, cx| {
 6881                buffer.autoindent_ranges(selections, cx);
 6882            });
 6883            let selections = this.selections.all::<usize>(cx);
 6884            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6885                s.select(selections)
 6886            });
 6887        });
 6888    }
 6889
 6890    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6891        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6892        let selections = self.selections.all::<Point>(cx);
 6893
 6894        let mut new_cursors = Vec::new();
 6895        let mut edit_ranges = Vec::new();
 6896        let mut selections = selections.iter().peekable();
 6897        while let Some(selection) = selections.next() {
 6898            let mut rows = selection.spanned_rows(false, &display_map);
 6899            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6900
 6901            // Accumulate contiguous regions of rows that we want to delete.
 6902            while let Some(next_selection) = selections.peek() {
 6903                let next_rows = next_selection.spanned_rows(false, &display_map);
 6904                if next_rows.start <= rows.end {
 6905                    rows.end = next_rows.end;
 6906                    selections.next().unwrap();
 6907                } else {
 6908                    break;
 6909                }
 6910            }
 6911
 6912            let buffer = &display_map.buffer_snapshot;
 6913            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6914            let edit_end;
 6915            let cursor_buffer_row;
 6916            if buffer.max_point().row >= rows.end.0 {
 6917                // If there's a line after the range, delete the \n from the end of the row range
 6918                // and position the cursor on the next line.
 6919                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6920                cursor_buffer_row = rows.end;
 6921            } else {
 6922                // If there isn't a line after the range, delete the \n from the line before the
 6923                // start of the row range and position the cursor there.
 6924                edit_start = edit_start.saturating_sub(1);
 6925                edit_end = buffer.len();
 6926                cursor_buffer_row = rows.start.previous_row();
 6927            }
 6928
 6929            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6930            *cursor.column_mut() =
 6931                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6932
 6933            new_cursors.push((
 6934                selection.id,
 6935                buffer.anchor_after(cursor.to_point(&display_map)),
 6936            ));
 6937            edit_ranges.push(edit_start..edit_end);
 6938        }
 6939
 6940        self.transact(window, cx, |this, window, cx| {
 6941            let buffer = this.buffer.update(cx, |buffer, cx| {
 6942                let empty_str: Arc<str> = Arc::default();
 6943                buffer.edit(
 6944                    edit_ranges
 6945                        .into_iter()
 6946                        .map(|range| (range, empty_str.clone())),
 6947                    None,
 6948                    cx,
 6949                );
 6950                buffer.snapshot(cx)
 6951            });
 6952            let new_selections = new_cursors
 6953                .into_iter()
 6954                .map(|(id, cursor)| {
 6955                    let cursor = cursor.to_point(&buffer);
 6956                    Selection {
 6957                        id,
 6958                        start: cursor,
 6959                        end: cursor,
 6960                        reversed: false,
 6961                        goal: SelectionGoal::None,
 6962                    }
 6963                })
 6964                .collect();
 6965
 6966            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6967                s.select(new_selections);
 6968            });
 6969        });
 6970    }
 6971
 6972    pub fn join_lines_impl(
 6973        &mut self,
 6974        insert_whitespace: bool,
 6975        window: &mut Window,
 6976        cx: &mut Context<Self>,
 6977    ) {
 6978        if self.read_only(cx) {
 6979            return;
 6980        }
 6981        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6982        for selection in self.selections.all::<Point>(cx) {
 6983            let start = MultiBufferRow(selection.start.row);
 6984            // Treat single line selections as if they include the next line. Otherwise this action
 6985            // would do nothing for single line selections individual cursors.
 6986            let end = if selection.start.row == selection.end.row {
 6987                MultiBufferRow(selection.start.row + 1)
 6988            } else {
 6989                MultiBufferRow(selection.end.row)
 6990            };
 6991
 6992            if let Some(last_row_range) = row_ranges.last_mut() {
 6993                if start <= last_row_range.end {
 6994                    last_row_range.end = end;
 6995                    continue;
 6996                }
 6997            }
 6998            row_ranges.push(start..end);
 6999        }
 7000
 7001        let snapshot = self.buffer.read(cx).snapshot(cx);
 7002        let mut cursor_positions = Vec::new();
 7003        for row_range in &row_ranges {
 7004            let anchor = snapshot.anchor_before(Point::new(
 7005                row_range.end.previous_row().0,
 7006                snapshot.line_len(row_range.end.previous_row()),
 7007            ));
 7008            cursor_positions.push(anchor..anchor);
 7009        }
 7010
 7011        self.transact(window, cx, |this, window, cx| {
 7012            for row_range in row_ranges.into_iter().rev() {
 7013                for row in row_range.iter_rows().rev() {
 7014                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 7015                    let next_line_row = row.next_row();
 7016                    let indent = snapshot.indent_size_for_line(next_line_row);
 7017                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 7018
 7019                    let replace =
 7020                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 7021                            " "
 7022                        } else {
 7023                            ""
 7024                        };
 7025
 7026                    this.buffer.update(cx, |buffer, cx| {
 7027                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 7028                    });
 7029                }
 7030            }
 7031
 7032            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7033                s.select_anchor_ranges(cursor_positions)
 7034            });
 7035        });
 7036    }
 7037
 7038    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 7039        self.join_lines_impl(true, window, cx);
 7040    }
 7041
 7042    pub fn sort_lines_case_sensitive(
 7043        &mut self,
 7044        _: &SortLinesCaseSensitive,
 7045        window: &mut Window,
 7046        cx: &mut Context<Self>,
 7047    ) {
 7048        self.manipulate_lines(window, cx, |lines| lines.sort())
 7049    }
 7050
 7051    pub fn sort_lines_case_insensitive(
 7052        &mut self,
 7053        _: &SortLinesCaseInsensitive,
 7054        window: &mut Window,
 7055        cx: &mut Context<Self>,
 7056    ) {
 7057        self.manipulate_lines(window, cx, |lines| {
 7058            lines.sort_by_key(|line| line.to_lowercase())
 7059        })
 7060    }
 7061
 7062    pub fn unique_lines_case_insensitive(
 7063        &mut self,
 7064        _: &UniqueLinesCaseInsensitive,
 7065        window: &mut Window,
 7066        cx: &mut Context<Self>,
 7067    ) {
 7068        self.manipulate_lines(window, cx, |lines| {
 7069            let mut seen = HashSet::default();
 7070            lines.retain(|line| seen.insert(line.to_lowercase()));
 7071        })
 7072    }
 7073
 7074    pub fn unique_lines_case_sensitive(
 7075        &mut self,
 7076        _: &UniqueLinesCaseSensitive,
 7077        window: &mut Window,
 7078        cx: &mut Context<Self>,
 7079    ) {
 7080        self.manipulate_lines(window, cx, |lines| {
 7081            let mut seen = HashSet::default();
 7082            lines.retain(|line| seen.insert(*line));
 7083        })
 7084    }
 7085
 7086    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 7087        let mut revert_changes = HashMap::default();
 7088        let snapshot = self.snapshot(window, cx);
 7089        for hunk in snapshot
 7090            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 7091        {
 7092            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7093        }
 7094        if !revert_changes.is_empty() {
 7095            self.transact(window, cx, |editor, window, cx| {
 7096                editor.revert(revert_changes, window, cx);
 7097            });
 7098        }
 7099    }
 7100
 7101    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 7102        let Some(project) = self.project.clone() else {
 7103            return;
 7104        };
 7105        self.reload(project, window, cx)
 7106            .detach_and_notify_err(window, cx);
 7107    }
 7108
 7109    pub fn revert_selected_hunks(
 7110        &mut self,
 7111        _: &RevertSelectedHunks,
 7112        window: &mut Window,
 7113        cx: &mut Context<Self>,
 7114    ) {
 7115        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 7116        self.revert_hunks_in_ranges(selections, window, cx);
 7117    }
 7118
 7119    fn revert_hunks_in_ranges(
 7120        &mut self,
 7121        ranges: impl Iterator<Item = Range<Point>>,
 7122        window: &mut Window,
 7123        cx: &mut Context<Editor>,
 7124    ) {
 7125        let mut revert_changes = HashMap::default();
 7126        let snapshot = self.snapshot(window, cx);
 7127        for hunk in &snapshot.hunks_for_ranges(ranges) {
 7128            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 7129        }
 7130        if !revert_changes.is_empty() {
 7131            self.transact(window, cx, |editor, window, cx| {
 7132                editor.revert(revert_changes, window, cx);
 7133            });
 7134        }
 7135    }
 7136
 7137    pub fn open_active_item_in_terminal(
 7138        &mut self,
 7139        _: &OpenInTerminal,
 7140        window: &mut Window,
 7141        cx: &mut Context<Self>,
 7142    ) {
 7143        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 7144            let project_path = buffer.read(cx).project_path(cx)?;
 7145            let project = self.project.as_ref()?.read(cx);
 7146            let entry = project.entry_for_path(&project_path, cx)?;
 7147            let parent = match &entry.canonical_path {
 7148                Some(canonical_path) => canonical_path.to_path_buf(),
 7149                None => project.absolute_path(&project_path, cx)?,
 7150            }
 7151            .parent()?
 7152            .to_path_buf();
 7153            Some(parent)
 7154        }) {
 7155            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 7156        }
 7157    }
 7158
 7159    pub fn prepare_revert_change(
 7160        &self,
 7161        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 7162        hunk: &MultiBufferDiffHunk,
 7163        cx: &mut App,
 7164    ) -> Option<()> {
 7165        let buffer = self.buffer.read(cx);
 7166        let diff = buffer.diff_for(hunk.buffer_id)?;
 7167        let buffer = buffer.buffer(hunk.buffer_id)?;
 7168        let buffer = buffer.read(cx);
 7169        let original_text = diff
 7170            .read(cx)
 7171            .base_text()
 7172            .as_ref()?
 7173            .as_rope()
 7174            .slice(hunk.diff_base_byte_range.clone());
 7175        let buffer_snapshot = buffer.snapshot();
 7176        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 7177        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 7178            probe
 7179                .0
 7180                .start
 7181                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 7182                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 7183        }) {
 7184            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 7185            Some(())
 7186        } else {
 7187            None
 7188        }
 7189    }
 7190
 7191    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 7192        self.manipulate_lines(window, cx, |lines| lines.reverse())
 7193    }
 7194
 7195    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 7196        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 7197    }
 7198
 7199    fn manipulate_lines<Fn>(
 7200        &mut self,
 7201        window: &mut Window,
 7202        cx: &mut Context<Self>,
 7203        mut callback: Fn,
 7204    ) where
 7205        Fn: FnMut(&mut Vec<&str>),
 7206    {
 7207        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7208        let buffer = self.buffer.read(cx).snapshot(cx);
 7209
 7210        let mut edits = Vec::new();
 7211
 7212        let selections = self.selections.all::<Point>(cx);
 7213        let mut selections = selections.iter().peekable();
 7214        let mut contiguous_row_selections = Vec::new();
 7215        let mut new_selections = Vec::new();
 7216        let mut added_lines = 0;
 7217        let mut removed_lines = 0;
 7218
 7219        while let Some(selection) = selections.next() {
 7220            let (start_row, end_row) = consume_contiguous_rows(
 7221                &mut contiguous_row_selections,
 7222                selection,
 7223                &display_map,
 7224                &mut selections,
 7225            );
 7226
 7227            let start_point = Point::new(start_row.0, 0);
 7228            let end_point = Point::new(
 7229                end_row.previous_row().0,
 7230                buffer.line_len(end_row.previous_row()),
 7231            );
 7232            let text = buffer
 7233                .text_for_range(start_point..end_point)
 7234                .collect::<String>();
 7235
 7236            let mut lines = text.split('\n').collect_vec();
 7237
 7238            let lines_before = lines.len();
 7239            callback(&mut lines);
 7240            let lines_after = lines.len();
 7241
 7242            edits.push((start_point..end_point, lines.join("\n")));
 7243
 7244            // Selections must change based on added and removed line count
 7245            let start_row =
 7246                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 7247            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 7248            new_selections.push(Selection {
 7249                id: selection.id,
 7250                start: start_row,
 7251                end: end_row,
 7252                goal: SelectionGoal::None,
 7253                reversed: selection.reversed,
 7254            });
 7255
 7256            if lines_after > lines_before {
 7257                added_lines += lines_after - lines_before;
 7258            } else if lines_before > lines_after {
 7259                removed_lines += lines_before - lines_after;
 7260            }
 7261        }
 7262
 7263        self.transact(window, cx, |this, window, cx| {
 7264            let buffer = this.buffer.update(cx, |buffer, cx| {
 7265                buffer.edit(edits, None, cx);
 7266                buffer.snapshot(cx)
 7267            });
 7268
 7269            // Recalculate offsets on newly edited buffer
 7270            let new_selections = new_selections
 7271                .iter()
 7272                .map(|s| {
 7273                    let start_point = Point::new(s.start.0, 0);
 7274                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 7275                    Selection {
 7276                        id: s.id,
 7277                        start: buffer.point_to_offset(start_point),
 7278                        end: buffer.point_to_offset(end_point),
 7279                        goal: s.goal,
 7280                        reversed: s.reversed,
 7281                    }
 7282                })
 7283                .collect();
 7284
 7285            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7286                s.select(new_selections);
 7287            });
 7288
 7289            this.request_autoscroll(Autoscroll::fit(), cx);
 7290        });
 7291    }
 7292
 7293    pub fn convert_to_upper_case(
 7294        &mut self,
 7295        _: &ConvertToUpperCase,
 7296        window: &mut Window,
 7297        cx: &mut Context<Self>,
 7298    ) {
 7299        self.manipulate_text(window, cx, |text| text.to_uppercase())
 7300    }
 7301
 7302    pub fn convert_to_lower_case(
 7303        &mut self,
 7304        _: &ConvertToLowerCase,
 7305        window: &mut Window,
 7306        cx: &mut Context<Self>,
 7307    ) {
 7308        self.manipulate_text(window, cx, |text| text.to_lowercase())
 7309    }
 7310
 7311    pub fn convert_to_title_case(
 7312        &mut self,
 7313        _: &ConvertToTitleCase,
 7314        window: &mut Window,
 7315        cx: &mut Context<Self>,
 7316    ) {
 7317        self.manipulate_text(window, cx, |text| {
 7318            text.split('\n')
 7319                .map(|line| line.to_case(Case::Title))
 7320                .join("\n")
 7321        })
 7322    }
 7323
 7324    pub fn convert_to_snake_case(
 7325        &mut self,
 7326        _: &ConvertToSnakeCase,
 7327        window: &mut Window,
 7328        cx: &mut Context<Self>,
 7329    ) {
 7330        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 7331    }
 7332
 7333    pub fn convert_to_kebab_case(
 7334        &mut self,
 7335        _: &ConvertToKebabCase,
 7336        window: &mut Window,
 7337        cx: &mut Context<Self>,
 7338    ) {
 7339        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 7340    }
 7341
 7342    pub fn convert_to_upper_camel_case(
 7343        &mut self,
 7344        _: &ConvertToUpperCamelCase,
 7345        window: &mut Window,
 7346        cx: &mut Context<Self>,
 7347    ) {
 7348        self.manipulate_text(window, cx, |text| {
 7349            text.split('\n')
 7350                .map(|line| line.to_case(Case::UpperCamel))
 7351                .join("\n")
 7352        })
 7353    }
 7354
 7355    pub fn convert_to_lower_camel_case(
 7356        &mut self,
 7357        _: &ConvertToLowerCamelCase,
 7358        window: &mut Window,
 7359        cx: &mut Context<Self>,
 7360    ) {
 7361        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 7362    }
 7363
 7364    pub fn convert_to_opposite_case(
 7365        &mut self,
 7366        _: &ConvertToOppositeCase,
 7367        window: &mut Window,
 7368        cx: &mut Context<Self>,
 7369    ) {
 7370        self.manipulate_text(window, cx, |text| {
 7371            text.chars()
 7372                .fold(String::with_capacity(text.len()), |mut t, c| {
 7373                    if c.is_uppercase() {
 7374                        t.extend(c.to_lowercase());
 7375                    } else {
 7376                        t.extend(c.to_uppercase());
 7377                    }
 7378                    t
 7379                })
 7380        })
 7381    }
 7382
 7383    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 7384    where
 7385        Fn: FnMut(&str) -> String,
 7386    {
 7387        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7388        let buffer = self.buffer.read(cx).snapshot(cx);
 7389
 7390        let mut new_selections = Vec::new();
 7391        let mut edits = Vec::new();
 7392        let mut selection_adjustment = 0i32;
 7393
 7394        for selection in self.selections.all::<usize>(cx) {
 7395            let selection_is_empty = selection.is_empty();
 7396
 7397            let (start, end) = if selection_is_empty {
 7398                let word_range = movement::surrounding_word(
 7399                    &display_map,
 7400                    selection.start.to_display_point(&display_map),
 7401                );
 7402                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7403                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7404                (start, end)
 7405            } else {
 7406                (selection.start, selection.end)
 7407            };
 7408
 7409            let text = buffer.text_for_range(start..end).collect::<String>();
 7410            let old_length = text.len() as i32;
 7411            let text = callback(&text);
 7412
 7413            new_selections.push(Selection {
 7414                start: (start as i32 - selection_adjustment) as usize,
 7415                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7416                goal: SelectionGoal::None,
 7417                ..selection
 7418            });
 7419
 7420            selection_adjustment += old_length - text.len() as i32;
 7421
 7422            edits.push((start..end, text));
 7423        }
 7424
 7425        self.transact(window, cx, |this, window, cx| {
 7426            this.buffer.update(cx, |buffer, cx| {
 7427                buffer.edit(edits, None, cx);
 7428            });
 7429
 7430            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7431                s.select(new_selections);
 7432            });
 7433
 7434            this.request_autoscroll(Autoscroll::fit(), cx);
 7435        });
 7436    }
 7437
 7438    pub fn duplicate(
 7439        &mut self,
 7440        upwards: bool,
 7441        whole_lines: bool,
 7442        window: &mut Window,
 7443        cx: &mut Context<Self>,
 7444    ) {
 7445        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7446        let buffer = &display_map.buffer_snapshot;
 7447        let selections = self.selections.all::<Point>(cx);
 7448
 7449        let mut edits = Vec::new();
 7450        let mut selections_iter = selections.iter().peekable();
 7451        while let Some(selection) = selections_iter.next() {
 7452            let mut rows = selection.spanned_rows(false, &display_map);
 7453            // duplicate line-wise
 7454            if whole_lines || selection.start == selection.end {
 7455                // Avoid duplicating the same lines twice.
 7456                while let Some(next_selection) = selections_iter.peek() {
 7457                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7458                    if next_rows.start < rows.end {
 7459                        rows.end = next_rows.end;
 7460                        selections_iter.next().unwrap();
 7461                    } else {
 7462                        break;
 7463                    }
 7464                }
 7465
 7466                // Copy the text from the selected row region and splice it either at the start
 7467                // or end of the region.
 7468                let start = Point::new(rows.start.0, 0);
 7469                let end = Point::new(
 7470                    rows.end.previous_row().0,
 7471                    buffer.line_len(rows.end.previous_row()),
 7472                );
 7473                let text = buffer
 7474                    .text_for_range(start..end)
 7475                    .chain(Some("\n"))
 7476                    .collect::<String>();
 7477                let insert_location = if upwards {
 7478                    Point::new(rows.end.0, 0)
 7479                } else {
 7480                    start
 7481                };
 7482                edits.push((insert_location..insert_location, text));
 7483            } else {
 7484                // duplicate character-wise
 7485                let start = selection.start;
 7486                let end = selection.end;
 7487                let text = buffer.text_for_range(start..end).collect::<String>();
 7488                edits.push((selection.end..selection.end, text));
 7489            }
 7490        }
 7491
 7492        self.transact(window, cx, |this, _, cx| {
 7493            this.buffer.update(cx, |buffer, cx| {
 7494                buffer.edit(edits, None, cx);
 7495            });
 7496
 7497            this.request_autoscroll(Autoscroll::fit(), cx);
 7498        });
 7499    }
 7500
 7501    pub fn duplicate_line_up(
 7502        &mut self,
 7503        _: &DuplicateLineUp,
 7504        window: &mut Window,
 7505        cx: &mut Context<Self>,
 7506    ) {
 7507        self.duplicate(true, true, window, cx);
 7508    }
 7509
 7510    pub fn duplicate_line_down(
 7511        &mut self,
 7512        _: &DuplicateLineDown,
 7513        window: &mut Window,
 7514        cx: &mut Context<Self>,
 7515    ) {
 7516        self.duplicate(false, true, window, cx);
 7517    }
 7518
 7519    pub fn duplicate_selection(
 7520        &mut self,
 7521        _: &DuplicateSelection,
 7522        window: &mut Window,
 7523        cx: &mut Context<Self>,
 7524    ) {
 7525        self.duplicate(false, false, window, cx);
 7526    }
 7527
 7528    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7529        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7530        let buffer = self.buffer.read(cx).snapshot(cx);
 7531
 7532        let mut edits = Vec::new();
 7533        let mut unfold_ranges = Vec::new();
 7534        let mut refold_creases = Vec::new();
 7535
 7536        let selections = self.selections.all::<Point>(cx);
 7537        let mut selections = selections.iter().peekable();
 7538        let mut contiguous_row_selections = Vec::new();
 7539        let mut new_selections = Vec::new();
 7540
 7541        while let Some(selection) = selections.next() {
 7542            // Find all the selections that span a contiguous row range
 7543            let (start_row, end_row) = consume_contiguous_rows(
 7544                &mut contiguous_row_selections,
 7545                selection,
 7546                &display_map,
 7547                &mut selections,
 7548            );
 7549
 7550            // Move the text spanned by the row range to be before the line preceding the row range
 7551            if start_row.0 > 0 {
 7552                let range_to_move = Point::new(
 7553                    start_row.previous_row().0,
 7554                    buffer.line_len(start_row.previous_row()),
 7555                )
 7556                    ..Point::new(
 7557                        end_row.previous_row().0,
 7558                        buffer.line_len(end_row.previous_row()),
 7559                    );
 7560                let insertion_point = display_map
 7561                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7562                    .0;
 7563
 7564                // Don't move lines across excerpts
 7565                if buffer
 7566                    .excerpt_containing(insertion_point..range_to_move.end)
 7567                    .is_some()
 7568                {
 7569                    let text = buffer
 7570                        .text_for_range(range_to_move.clone())
 7571                        .flat_map(|s| s.chars())
 7572                        .skip(1)
 7573                        .chain(['\n'])
 7574                        .collect::<String>();
 7575
 7576                    edits.push((
 7577                        buffer.anchor_after(range_to_move.start)
 7578                            ..buffer.anchor_before(range_to_move.end),
 7579                        String::new(),
 7580                    ));
 7581                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7582                    edits.push((insertion_anchor..insertion_anchor, text));
 7583
 7584                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7585
 7586                    // Move selections up
 7587                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7588                        |mut selection| {
 7589                            selection.start.row -= row_delta;
 7590                            selection.end.row -= row_delta;
 7591                            selection
 7592                        },
 7593                    ));
 7594
 7595                    // Move folds up
 7596                    unfold_ranges.push(range_to_move.clone());
 7597                    for fold in display_map.folds_in_range(
 7598                        buffer.anchor_before(range_to_move.start)
 7599                            ..buffer.anchor_after(range_to_move.end),
 7600                    ) {
 7601                        let mut start = fold.range.start.to_point(&buffer);
 7602                        let mut end = fold.range.end.to_point(&buffer);
 7603                        start.row -= row_delta;
 7604                        end.row -= row_delta;
 7605                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7606                    }
 7607                }
 7608            }
 7609
 7610            // If we didn't move line(s), preserve the existing selections
 7611            new_selections.append(&mut contiguous_row_selections);
 7612        }
 7613
 7614        self.transact(window, cx, |this, window, cx| {
 7615            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7616            this.buffer.update(cx, |buffer, cx| {
 7617                for (range, text) in edits {
 7618                    buffer.edit([(range, text)], None, cx);
 7619                }
 7620            });
 7621            this.fold_creases(refold_creases, true, window, cx);
 7622            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7623                s.select(new_selections);
 7624            })
 7625        });
 7626    }
 7627
 7628    pub fn move_line_down(
 7629        &mut self,
 7630        _: &MoveLineDown,
 7631        window: &mut Window,
 7632        cx: &mut Context<Self>,
 7633    ) {
 7634        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7635        let buffer = self.buffer.read(cx).snapshot(cx);
 7636
 7637        let mut edits = Vec::new();
 7638        let mut unfold_ranges = Vec::new();
 7639        let mut refold_creases = Vec::new();
 7640
 7641        let selections = self.selections.all::<Point>(cx);
 7642        let mut selections = selections.iter().peekable();
 7643        let mut contiguous_row_selections = Vec::new();
 7644        let mut new_selections = Vec::new();
 7645
 7646        while let Some(selection) = selections.next() {
 7647            // Find all the selections that span a contiguous row range
 7648            let (start_row, end_row) = consume_contiguous_rows(
 7649                &mut contiguous_row_selections,
 7650                selection,
 7651                &display_map,
 7652                &mut selections,
 7653            );
 7654
 7655            // Move the text spanned by the row range to be after the last line of the row range
 7656            if end_row.0 <= buffer.max_point().row {
 7657                let range_to_move =
 7658                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7659                let insertion_point = display_map
 7660                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7661                    .0;
 7662
 7663                // Don't move lines across excerpt boundaries
 7664                if buffer
 7665                    .excerpt_containing(range_to_move.start..insertion_point)
 7666                    .is_some()
 7667                {
 7668                    let mut text = String::from("\n");
 7669                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7670                    text.pop(); // Drop trailing newline
 7671                    edits.push((
 7672                        buffer.anchor_after(range_to_move.start)
 7673                            ..buffer.anchor_before(range_to_move.end),
 7674                        String::new(),
 7675                    ));
 7676                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7677                    edits.push((insertion_anchor..insertion_anchor, text));
 7678
 7679                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7680
 7681                    // Move selections down
 7682                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7683                        |mut selection| {
 7684                            selection.start.row += row_delta;
 7685                            selection.end.row += row_delta;
 7686                            selection
 7687                        },
 7688                    ));
 7689
 7690                    // Move folds down
 7691                    unfold_ranges.push(range_to_move.clone());
 7692                    for fold in display_map.folds_in_range(
 7693                        buffer.anchor_before(range_to_move.start)
 7694                            ..buffer.anchor_after(range_to_move.end),
 7695                    ) {
 7696                        let mut start = fold.range.start.to_point(&buffer);
 7697                        let mut end = fold.range.end.to_point(&buffer);
 7698                        start.row += row_delta;
 7699                        end.row += row_delta;
 7700                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7701                    }
 7702                }
 7703            }
 7704
 7705            // If we didn't move line(s), preserve the existing selections
 7706            new_selections.append(&mut contiguous_row_selections);
 7707        }
 7708
 7709        self.transact(window, cx, |this, window, cx| {
 7710            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7711            this.buffer.update(cx, |buffer, cx| {
 7712                for (range, text) in edits {
 7713                    buffer.edit([(range, text)], None, cx);
 7714                }
 7715            });
 7716            this.fold_creases(refold_creases, true, window, cx);
 7717            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7718                s.select(new_selections)
 7719            });
 7720        });
 7721    }
 7722
 7723    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7724        let text_layout_details = &self.text_layout_details(window);
 7725        self.transact(window, cx, |this, window, cx| {
 7726            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7727                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7728                let line_mode = s.line_mode;
 7729                s.move_with(|display_map, selection| {
 7730                    if !selection.is_empty() || line_mode {
 7731                        return;
 7732                    }
 7733
 7734                    let mut head = selection.head();
 7735                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7736                    if head.column() == display_map.line_len(head.row()) {
 7737                        transpose_offset = display_map
 7738                            .buffer_snapshot
 7739                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7740                    }
 7741
 7742                    if transpose_offset == 0 {
 7743                        return;
 7744                    }
 7745
 7746                    *head.column_mut() += 1;
 7747                    head = display_map.clip_point(head, Bias::Right);
 7748                    let goal = SelectionGoal::HorizontalPosition(
 7749                        display_map
 7750                            .x_for_display_point(head, text_layout_details)
 7751                            .into(),
 7752                    );
 7753                    selection.collapse_to(head, goal);
 7754
 7755                    let transpose_start = display_map
 7756                        .buffer_snapshot
 7757                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7758                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7759                        let transpose_end = display_map
 7760                            .buffer_snapshot
 7761                            .clip_offset(transpose_offset + 1, Bias::Right);
 7762                        if let Some(ch) =
 7763                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7764                        {
 7765                            edits.push((transpose_start..transpose_offset, String::new()));
 7766                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7767                        }
 7768                    }
 7769                });
 7770                edits
 7771            });
 7772            this.buffer
 7773                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7774            let selections = this.selections.all::<usize>(cx);
 7775            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7776                s.select(selections);
 7777            });
 7778        });
 7779    }
 7780
 7781    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7782        self.rewrap_impl(IsVimMode::No, cx)
 7783    }
 7784
 7785    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7786        let buffer = self.buffer.read(cx).snapshot(cx);
 7787        let selections = self.selections.all::<Point>(cx);
 7788        let mut selections = selections.iter().peekable();
 7789
 7790        let mut edits = Vec::new();
 7791        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7792
 7793        while let Some(selection) = selections.next() {
 7794            let mut start_row = selection.start.row;
 7795            let mut end_row = selection.end.row;
 7796
 7797            // Skip selections that overlap with a range that has already been rewrapped.
 7798            let selection_range = start_row..end_row;
 7799            if rewrapped_row_ranges
 7800                .iter()
 7801                .any(|range| range.overlaps(&selection_range))
 7802            {
 7803                continue;
 7804            }
 7805
 7806            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7807
 7808            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7809                match language_scope.language_name().as_ref() {
 7810                    "Markdown" | "Plain Text" => {
 7811                        should_rewrap = true;
 7812                    }
 7813                    _ => {}
 7814                }
 7815            }
 7816
 7817            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7818
 7819            // Since not all lines in the selection may be at the same indent
 7820            // level, choose the indent size that is the most common between all
 7821            // of the lines.
 7822            //
 7823            // If there is a tie, we use the deepest indent.
 7824            let (indent_size, indent_end) = {
 7825                let mut indent_size_occurrences = HashMap::default();
 7826                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7827
 7828                for row in start_row..=end_row {
 7829                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7830                    rows_by_indent_size.entry(indent).or_default().push(row);
 7831                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7832                }
 7833
 7834                let indent_size = indent_size_occurrences
 7835                    .into_iter()
 7836                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7837                    .map(|(indent, _)| indent)
 7838                    .unwrap_or_default();
 7839                let row = rows_by_indent_size[&indent_size][0];
 7840                let indent_end = Point::new(row, indent_size.len);
 7841
 7842                (indent_size, indent_end)
 7843            };
 7844
 7845            let mut line_prefix = indent_size.chars().collect::<String>();
 7846
 7847            if let Some(comment_prefix) =
 7848                buffer
 7849                    .language_scope_at(selection.head())
 7850                    .and_then(|language| {
 7851                        language
 7852                            .line_comment_prefixes()
 7853                            .iter()
 7854                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7855                            .cloned()
 7856                    })
 7857            {
 7858                line_prefix.push_str(&comment_prefix);
 7859                should_rewrap = true;
 7860            }
 7861
 7862            if !should_rewrap {
 7863                continue;
 7864            }
 7865
 7866            if selection.is_empty() {
 7867                'expand_upwards: while start_row > 0 {
 7868                    let prev_row = start_row - 1;
 7869                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7870                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7871                    {
 7872                        start_row = prev_row;
 7873                    } else {
 7874                        break 'expand_upwards;
 7875                    }
 7876                }
 7877
 7878                'expand_downwards: while end_row < buffer.max_point().row {
 7879                    let next_row = end_row + 1;
 7880                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7881                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7882                    {
 7883                        end_row = next_row;
 7884                    } else {
 7885                        break 'expand_downwards;
 7886                    }
 7887                }
 7888            }
 7889
 7890            let start = Point::new(start_row, 0);
 7891            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7892            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7893            let Some(lines_without_prefixes) = selection_text
 7894                .lines()
 7895                .map(|line| {
 7896                    line.strip_prefix(&line_prefix)
 7897                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7898                        .ok_or_else(|| {
 7899                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7900                        })
 7901                })
 7902                .collect::<Result<Vec<_>, _>>()
 7903                .log_err()
 7904            else {
 7905                continue;
 7906            };
 7907
 7908            let wrap_column = buffer
 7909                .settings_at(Point::new(start_row, 0), cx)
 7910                .preferred_line_length as usize;
 7911            let wrapped_text = wrap_with_prefix(
 7912                line_prefix,
 7913                lines_without_prefixes.join(" "),
 7914                wrap_column,
 7915                tab_size,
 7916            );
 7917
 7918            // TODO: should always use char-based diff while still supporting cursor behavior that
 7919            // matches vim.
 7920            let diff = match is_vim_mode {
 7921                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7922                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7923            };
 7924            let mut offset = start.to_offset(&buffer);
 7925            let mut moved_since_edit = true;
 7926
 7927            for change in diff.iter_all_changes() {
 7928                let value = change.value();
 7929                match change.tag() {
 7930                    ChangeTag::Equal => {
 7931                        offset += value.len();
 7932                        moved_since_edit = true;
 7933                    }
 7934                    ChangeTag::Delete => {
 7935                        let start = buffer.anchor_after(offset);
 7936                        let end = buffer.anchor_before(offset + value.len());
 7937
 7938                        if moved_since_edit {
 7939                            edits.push((start..end, String::new()));
 7940                        } else {
 7941                            edits.last_mut().unwrap().0.end = end;
 7942                        }
 7943
 7944                        offset += value.len();
 7945                        moved_since_edit = false;
 7946                    }
 7947                    ChangeTag::Insert => {
 7948                        if moved_since_edit {
 7949                            let anchor = buffer.anchor_after(offset);
 7950                            edits.push((anchor..anchor, value.to_string()));
 7951                        } else {
 7952                            edits.last_mut().unwrap().1.push_str(value);
 7953                        }
 7954
 7955                        moved_since_edit = false;
 7956                    }
 7957                }
 7958            }
 7959
 7960            rewrapped_row_ranges.push(start_row..=end_row);
 7961        }
 7962
 7963        self.buffer
 7964            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7965    }
 7966
 7967    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7968        let mut text = String::new();
 7969        let buffer = self.buffer.read(cx).snapshot(cx);
 7970        let mut selections = self.selections.all::<Point>(cx);
 7971        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7972        {
 7973            let max_point = buffer.max_point();
 7974            let mut is_first = true;
 7975            for selection in &mut selections {
 7976                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7977                if is_entire_line {
 7978                    selection.start = Point::new(selection.start.row, 0);
 7979                    if !selection.is_empty() && selection.end.column == 0 {
 7980                        selection.end = cmp::min(max_point, selection.end);
 7981                    } else {
 7982                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7983                    }
 7984                    selection.goal = SelectionGoal::None;
 7985                }
 7986                if is_first {
 7987                    is_first = false;
 7988                } else {
 7989                    text += "\n";
 7990                }
 7991                let mut len = 0;
 7992                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7993                    text.push_str(chunk);
 7994                    len += chunk.len();
 7995                }
 7996                clipboard_selections.push(ClipboardSelection {
 7997                    len,
 7998                    is_entire_line,
 7999                    first_line_indent: buffer
 8000                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 8001                        .len,
 8002                });
 8003            }
 8004        }
 8005
 8006        self.transact(window, cx, |this, window, cx| {
 8007            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8008                s.select(selections);
 8009            });
 8010            this.insert("", window, cx);
 8011        });
 8012        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 8013    }
 8014
 8015    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 8016        let item = self.cut_common(window, cx);
 8017        cx.write_to_clipboard(item);
 8018    }
 8019
 8020    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 8021        self.change_selections(None, window, cx, |s| {
 8022            s.move_with(|snapshot, sel| {
 8023                if sel.is_empty() {
 8024                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 8025                }
 8026            });
 8027        });
 8028        let item = self.cut_common(window, cx);
 8029        cx.set_global(KillRing(item))
 8030    }
 8031
 8032    pub fn kill_ring_yank(
 8033        &mut self,
 8034        _: &KillRingYank,
 8035        window: &mut Window,
 8036        cx: &mut Context<Self>,
 8037    ) {
 8038        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 8039            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 8040                (kill_ring.text().to_string(), kill_ring.metadata_json())
 8041            } else {
 8042                return;
 8043            }
 8044        } else {
 8045            return;
 8046        };
 8047        self.do_paste(&text, metadata, false, window, cx);
 8048    }
 8049
 8050    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 8051        let selections = self.selections.all::<Point>(cx);
 8052        let buffer = self.buffer.read(cx).read(cx);
 8053        let mut text = String::new();
 8054
 8055        let mut clipboard_selections = Vec::with_capacity(selections.len());
 8056        {
 8057            let max_point = buffer.max_point();
 8058            let mut is_first = true;
 8059            for selection in selections.iter() {
 8060                let mut start = selection.start;
 8061                let mut end = selection.end;
 8062                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 8063                if is_entire_line {
 8064                    start = Point::new(start.row, 0);
 8065                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 8066                }
 8067                if is_first {
 8068                    is_first = false;
 8069                } else {
 8070                    text += "\n";
 8071                }
 8072                let mut len = 0;
 8073                for chunk in buffer.text_for_range(start..end) {
 8074                    text.push_str(chunk);
 8075                    len += chunk.len();
 8076                }
 8077                clipboard_selections.push(ClipboardSelection {
 8078                    len,
 8079                    is_entire_line,
 8080                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 8081                });
 8082            }
 8083        }
 8084
 8085        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 8086            text,
 8087            clipboard_selections,
 8088        ));
 8089    }
 8090
 8091    pub fn do_paste(
 8092        &mut self,
 8093        text: &String,
 8094        clipboard_selections: Option<Vec<ClipboardSelection>>,
 8095        handle_entire_lines: bool,
 8096        window: &mut Window,
 8097        cx: &mut Context<Self>,
 8098    ) {
 8099        if self.read_only(cx) {
 8100            return;
 8101        }
 8102
 8103        let clipboard_text = Cow::Borrowed(text);
 8104
 8105        self.transact(window, cx, |this, window, cx| {
 8106            if let Some(mut clipboard_selections) = clipboard_selections {
 8107                let old_selections = this.selections.all::<usize>(cx);
 8108                let all_selections_were_entire_line =
 8109                    clipboard_selections.iter().all(|s| s.is_entire_line);
 8110                let first_selection_indent_column =
 8111                    clipboard_selections.first().map(|s| s.first_line_indent);
 8112                if clipboard_selections.len() != old_selections.len() {
 8113                    clipboard_selections.drain(..);
 8114                }
 8115                let cursor_offset = this.selections.last::<usize>(cx).head();
 8116                let mut auto_indent_on_paste = true;
 8117
 8118                this.buffer.update(cx, |buffer, cx| {
 8119                    let snapshot = buffer.read(cx);
 8120                    auto_indent_on_paste =
 8121                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 8122
 8123                    let mut start_offset = 0;
 8124                    let mut edits = Vec::new();
 8125                    let mut original_indent_columns = Vec::new();
 8126                    for (ix, selection) in old_selections.iter().enumerate() {
 8127                        let to_insert;
 8128                        let entire_line;
 8129                        let original_indent_column;
 8130                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 8131                            let end_offset = start_offset + clipboard_selection.len;
 8132                            to_insert = &clipboard_text[start_offset..end_offset];
 8133                            entire_line = clipboard_selection.is_entire_line;
 8134                            start_offset = end_offset + 1;
 8135                            original_indent_column = Some(clipboard_selection.first_line_indent);
 8136                        } else {
 8137                            to_insert = clipboard_text.as_str();
 8138                            entire_line = all_selections_were_entire_line;
 8139                            original_indent_column = first_selection_indent_column
 8140                        }
 8141
 8142                        // If the corresponding selection was empty when this slice of the
 8143                        // clipboard text was written, then the entire line containing the
 8144                        // selection was copied. If this selection is also currently empty,
 8145                        // then paste the line before the current line of the buffer.
 8146                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 8147                            let column = selection.start.to_point(&snapshot).column as usize;
 8148                            let line_start = selection.start - column;
 8149                            line_start..line_start
 8150                        } else {
 8151                            selection.range()
 8152                        };
 8153
 8154                        edits.push((range, to_insert));
 8155                        original_indent_columns.extend(original_indent_column);
 8156                    }
 8157                    drop(snapshot);
 8158
 8159                    buffer.edit(
 8160                        edits,
 8161                        if auto_indent_on_paste {
 8162                            Some(AutoindentMode::Block {
 8163                                original_indent_columns,
 8164                            })
 8165                        } else {
 8166                            None
 8167                        },
 8168                        cx,
 8169                    );
 8170                });
 8171
 8172                let selections = this.selections.all::<usize>(cx);
 8173                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8174                    s.select(selections)
 8175                });
 8176            } else {
 8177                this.insert(&clipboard_text, window, cx);
 8178            }
 8179        });
 8180    }
 8181
 8182    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 8183        if let Some(item) = cx.read_from_clipboard() {
 8184            let entries = item.entries();
 8185
 8186            match entries.first() {
 8187                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 8188                // of all the pasted entries.
 8189                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 8190                    .do_paste(
 8191                        clipboard_string.text(),
 8192                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 8193                        true,
 8194                        window,
 8195                        cx,
 8196                    ),
 8197                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 8198            }
 8199        }
 8200    }
 8201
 8202    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 8203        if self.read_only(cx) {
 8204            return;
 8205        }
 8206
 8207        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 8208            if let Some((selections, _)) =
 8209                self.selection_history.transaction(transaction_id).cloned()
 8210            {
 8211                self.change_selections(None, window, cx, |s| {
 8212                    s.select_anchors(selections.to_vec());
 8213                });
 8214            }
 8215            self.request_autoscroll(Autoscroll::fit(), cx);
 8216            self.unmark_text(window, cx);
 8217            self.refresh_inline_completion(true, false, window, cx);
 8218            cx.emit(EditorEvent::Edited { transaction_id });
 8219            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 8220        }
 8221    }
 8222
 8223    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 8224        if self.read_only(cx) {
 8225            return;
 8226        }
 8227
 8228        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 8229            if let Some((_, Some(selections))) =
 8230                self.selection_history.transaction(transaction_id).cloned()
 8231            {
 8232                self.change_selections(None, window, cx, |s| {
 8233                    s.select_anchors(selections.to_vec());
 8234                });
 8235            }
 8236            self.request_autoscroll(Autoscroll::fit(), cx);
 8237            self.unmark_text(window, cx);
 8238            self.refresh_inline_completion(true, false, window, cx);
 8239            cx.emit(EditorEvent::Edited { transaction_id });
 8240        }
 8241    }
 8242
 8243    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 8244        self.buffer
 8245            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 8246    }
 8247
 8248    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 8249        self.buffer
 8250            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 8251    }
 8252
 8253    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 8254        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8255            let line_mode = s.line_mode;
 8256            s.move_with(|map, selection| {
 8257                let cursor = if selection.is_empty() && !line_mode {
 8258                    movement::left(map, selection.start)
 8259                } else {
 8260                    selection.start
 8261                };
 8262                selection.collapse_to(cursor, SelectionGoal::None);
 8263            });
 8264        })
 8265    }
 8266
 8267    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 8268        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8269            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 8270        })
 8271    }
 8272
 8273    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 8274        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8275            let line_mode = s.line_mode;
 8276            s.move_with(|map, selection| {
 8277                let cursor = if selection.is_empty() && !line_mode {
 8278                    movement::right(map, selection.end)
 8279                } else {
 8280                    selection.end
 8281                };
 8282                selection.collapse_to(cursor, SelectionGoal::None)
 8283            });
 8284        })
 8285    }
 8286
 8287    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 8288        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8289            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 8290        })
 8291    }
 8292
 8293    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 8294        if self.take_rename(true, window, cx).is_some() {
 8295            return;
 8296        }
 8297
 8298        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8299            cx.propagate();
 8300            return;
 8301        }
 8302
 8303        let text_layout_details = &self.text_layout_details(window);
 8304        let selection_count = self.selections.count();
 8305        let first_selection = self.selections.first_anchor();
 8306
 8307        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8308            let line_mode = s.line_mode;
 8309            s.move_with(|map, selection| {
 8310                if !selection.is_empty() && !line_mode {
 8311                    selection.goal = SelectionGoal::None;
 8312                }
 8313                let (cursor, goal) = movement::up(
 8314                    map,
 8315                    selection.start,
 8316                    selection.goal,
 8317                    false,
 8318                    text_layout_details,
 8319                );
 8320                selection.collapse_to(cursor, goal);
 8321            });
 8322        });
 8323
 8324        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8325        {
 8326            cx.propagate();
 8327        }
 8328    }
 8329
 8330    pub fn move_up_by_lines(
 8331        &mut self,
 8332        action: &MoveUpByLines,
 8333        window: &mut Window,
 8334        cx: &mut Context<Self>,
 8335    ) {
 8336        if self.take_rename(true, window, cx).is_some() {
 8337            return;
 8338        }
 8339
 8340        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8341            cx.propagate();
 8342            return;
 8343        }
 8344
 8345        let text_layout_details = &self.text_layout_details(window);
 8346
 8347        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8348            let line_mode = s.line_mode;
 8349            s.move_with(|map, selection| {
 8350                if !selection.is_empty() && !line_mode {
 8351                    selection.goal = SelectionGoal::None;
 8352                }
 8353                let (cursor, goal) = movement::up_by_rows(
 8354                    map,
 8355                    selection.start,
 8356                    action.lines,
 8357                    selection.goal,
 8358                    false,
 8359                    text_layout_details,
 8360                );
 8361                selection.collapse_to(cursor, goal);
 8362            });
 8363        })
 8364    }
 8365
 8366    pub fn move_down_by_lines(
 8367        &mut self,
 8368        action: &MoveDownByLines,
 8369        window: &mut Window,
 8370        cx: &mut Context<Self>,
 8371    ) {
 8372        if self.take_rename(true, window, cx).is_some() {
 8373            return;
 8374        }
 8375
 8376        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8377            cx.propagate();
 8378            return;
 8379        }
 8380
 8381        let text_layout_details = &self.text_layout_details(window);
 8382
 8383        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8384            let line_mode = s.line_mode;
 8385            s.move_with(|map, selection| {
 8386                if !selection.is_empty() && !line_mode {
 8387                    selection.goal = SelectionGoal::None;
 8388                }
 8389                let (cursor, goal) = movement::down_by_rows(
 8390                    map,
 8391                    selection.start,
 8392                    action.lines,
 8393                    selection.goal,
 8394                    false,
 8395                    text_layout_details,
 8396                );
 8397                selection.collapse_to(cursor, goal);
 8398            });
 8399        })
 8400    }
 8401
 8402    pub fn select_down_by_lines(
 8403        &mut self,
 8404        action: &SelectDownByLines,
 8405        window: &mut Window,
 8406        cx: &mut Context<Self>,
 8407    ) {
 8408        let text_layout_details = &self.text_layout_details(window);
 8409        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8410            s.move_heads_with(|map, head, goal| {
 8411                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8412            })
 8413        })
 8414    }
 8415
 8416    pub fn select_up_by_lines(
 8417        &mut self,
 8418        action: &SelectUpByLines,
 8419        window: &mut Window,
 8420        cx: &mut Context<Self>,
 8421    ) {
 8422        let text_layout_details = &self.text_layout_details(window);
 8423        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8424            s.move_heads_with(|map, head, goal| {
 8425                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8426            })
 8427        })
 8428    }
 8429
 8430    pub fn select_page_up(
 8431        &mut self,
 8432        _: &SelectPageUp,
 8433        window: &mut Window,
 8434        cx: &mut Context<Self>,
 8435    ) {
 8436        let Some(row_count) = self.visible_row_count() else {
 8437            return;
 8438        };
 8439
 8440        let text_layout_details = &self.text_layout_details(window);
 8441
 8442        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8443            s.move_heads_with(|map, head, goal| {
 8444                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8445            })
 8446        })
 8447    }
 8448
 8449    pub fn move_page_up(
 8450        &mut self,
 8451        action: &MovePageUp,
 8452        window: &mut Window,
 8453        cx: &mut Context<Self>,
 8454    ) {
 8455        if self.take_rename(true, window, cx).is_some() {
 8456            return;
 8457        }
 8458
 8459        if self
 8460            .context_menu
 8461            .borrow_mut()
 8462            .as_mut()
 8463            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8464            .unwrap_or(false)
 8465        {
 8466            return;
 8467        }
 8468
 8469        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8470            cx.propagate();
 8471            return;
 8472        }
 8473
 8474        let Some(row_count) = self.visible_row_count() else {
 8475            return;
 8476        };
 8477
 8478        let autoscroll = if action.center_cursor {
 8479            Autoscroll::center()
 8480        } else {
 8481            Autoscroll::fit()
 8482        };
 8483
 8484        let text_layout_details = &self.text_layout_details(window);
 8485
 8486        self.change_selections(Some(autoscroll), window, cx, |s| {
 8487            let line_mode = s.line_mode;
 8488            s.move_with(|map, selection| {
 8489                if !selection.is_empty() && !line_mode {
 8490                    selection.goal = SelectionGoal::None;
 8491                }
 8492                let (cursor, goal) = movement::up_by_rows(
 8493                    map,
 8494                    selection.end,
 8495                    row_count,
 8496                    selection.goal,
 8497                    false,
 8498                    text_layout_details,
 8499                );
 8500                selection.collapse_to(cursor, goal);
 8501            });
 8502        });
 8503    }
 8504
 8505    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8506        let text_layout_details = &self.text_layout_details(window);
 8507        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8508            s.move_heads_with(|map, head, goal| {
 8509                movement::up(map, head, goal, false, text_layout_details)
 8510            })
 8511        })
 8512    }
 8513
 8514    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8515        self.take_rename(true, window, cx);
 8516
 8517        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8518            cx.propagate();
 8519            return;
 8520        }
 8521
 8522        let text_layout_details = &self.text_layout_details(window);
 8523        let selection_count = self.selections.count();
 8524        let first_selection = self.selections.first_anchor();
 8525
 8526        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8527            let line_mode = s.line_mode;
 8528            s.move_with(|map, selection| {
 8529                if !selection.is_empty() && !line_mode {
 8530                    selection.goal = SelectionGoal::None;
 8531                }
 8532                let (cursor, goal) = movement::down(
 8533                    map,
 8534                    selection.end,
 8535                    selection.goal,
 8536                    false,
 8537                    text_layout_details,
 8538                );
 8539                selection.collapse_to(cursor, goal);
 8540            });
 8541        });
 8542
 8543        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8544        {
 8545            cx.propagate();
 8546        }
 8547    }
 8548
 8549    pub fn select_page_down(
 8550        &mut self,
 8551        _: &SelectPageDown,
 8552        window: &mut Window,
 8553        cx: &mut Context<Self>,
 8554    ) {
 8555        let Some(row_count) = self.visible_row_count() else {
 8556            return;
 8557        };
 8558
 8559        let text_layout_details = &self.text_layout_details(window);
 8560
 8561        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8562            s.move_heads_with(|map, head, goal| {
 8563                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8564            })
 8565        })
 8566    }
 8567
 8568    pub fn move_page_down(
 8569        &mut self,
 8570        action: &MovePageDown,
 8571        window: &mut Window,
 8572        cx: &mut Context<Self>,
 8573    ) {
 8574        if self.take_rename(true, window, cx).is_some() {
 8575            return;
 8576        }
 8577
 8578        if self
 8579            .context_menu
 8580            .borrow_mut()
 8581            .as_mut()
 8582            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8583            .unwrap_or(false)
 8584        {
 8585            return;
 8586        }
 8587
 8588        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8589            cx.propagate();
 8590            return;
 8591        }
 8592
 8593        let Some(row_count) = self.visible_row_count() else {
 8594            return;
 8595        };
 8596
 8597        let autoscroll = if action.center_cursor {
 8598            Autoscroll::center()
 8599        } else {
 8600            Autoscroll::fit()
 8601        };
 8602
 8603        let text_layout_details = &self.text_layout_details(window);
 8604        self.change_selections(Some(autoscroll), window, cx, |s| {
 8605            let line_mode = s.line_mode;
 8606            s.move_with(|map, selection| {
 8607                if !selection.is_empty() && !line_mode {
 8608                    selection.goal = SelectionGoal::None;
 8609                }
 8610                let (cursor, goal) = movement::down_by_rows(
 8611                    map,
 8612                    selection.end,
 8613                    row_count,
 8614                    selection.goal,
 8615                    false,
 8616                    text_layout_details,
 8617                );
 8618                selection.collapse_to(cursor, goal);
 8619            });
 8620        });
 8621    }
 8622
 8623    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8624        let text_layout_details = &self.text_layout_details(window);
 8625        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8626            s.move_heads_with(|map, head, goal| {
 8627                movement::down(map, head, goal, false, text_layout_details)
 8628            })
 8629        });
 8630    }
 8631
 8632    pub fn context_menu_first(
 8633        &mut self,
 8634        _: &ContextMenuFirst,
 8635        _window: &mut Window,
 8636        cx: &mut Context<Self>,
 8637    ) {
 8638        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8639            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8640        }
 8641    }
 8642
 8643    pub fn context_menu_prev(
 8644        &mut self,
 8645        _: &ContextMenuPrev,
 8646        _window: &mut Window,
 8647        cx: &mut Context<Self>,
 8648    ) {
 8649        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8650            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8651        }
 8652    }
 8653
 8654    pub fn context_menu_next(
 8655        &mut self,
 8656        _: &ContextMenuNext,
 8657        _window: &mut Window,
 8658        cx: &mut Context<Self>,
 8659    ) {
 8660        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8661            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8662        }
 8663    }
 8664
 8665    pub fn context_menu_last(
 8666        &mut self,
 8667        _: &ContextMenuLast,
 8668        _window: &mut Window,
 8669        cx: &mut Context<Self>,
 8670    ) {
 8671        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8672            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8673        }
 8674    }
 8675
 8676    pub fn move_to_previous_word_start(
 8677        &mut self,
 8678        _: &MoveToPreviousWordStart,
 8679        window: &mut Window,
 8680        cx: &mut Context<Self>,
 8681    ) {
 8682        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8683            s.move_cursors_with(|map, head, _| {
 8684                (
 8685                    movement::previous_word_start(map, head),
 8686                    SelectionGoal::None,
 8687                )
 8688            });
 8689        })
 8690    }
 8691
 8692    pub fn move_to_previous_subword_start(
 8693        &mut self,
 8694        _: &MoveToPreviousSubwordStart,
 8695        window: &mut Window,
 8696        cx: &mut Context<Self>,
 8697    ) {
 8698        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8699            s.move_cursors_with(|map, head, _| {
 8700                (
 8701                    movement::previous_subword_start(map, head),
 8702                    SelectionGoal::None,
 8703                )
 8704            });
 8705        })
 8706    }
 8707
 8708    pub fn select_to_previous_word_start(
 8709        &mut self,
 8710        _: &SelectToPreviousWordStart,
 8711        window: &mut Window,
 8712        cx: &mut Context<Self>,
 8713    ) {
 8714        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8715            s.move_heads_with(|map, head, _| {
 8716                (
 8717                    movement::previous_word_start(map, head),
 8718                    SelectionGoal::None,
 8719                )
 8720            });
 8721        })
 8722    }
 8723
 8724    pub fn select_to_previous_subword_start(
 8725        &mut self,
 8726        _: &SelectToPreviousSubwordStart,
 8727        window: &mut Window,
 8728        cx: &mut Context<Self>,
 8729    ) {
 8730        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8731            s.move_heads_with(|map, head, _| {
 8732                (
 8733                    movement::previous_subword_start(map, head),
 8734                    SelectionGoal::None,
 8735                )
 8736            });
 8737        })
 8738    }
 8739
 8740    pub fn delete_to_previous_word_start(
 8741        &mut self,
 8742        action: &DeleteToPreviousWordStart,
 8743        window: &mut Window,
 8744        cx: &mut Context<Self>,
 8745    ) {
 8746        self.transact(window, cx, |this, window, cx| {
 8747            this.select_autoclose_pair(window, cx);
 8748            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8749                let line_mode = s.line_mode;
 8750                s.move_with(|map, selection| {
 8751                    if selection.is_empty() && !line_mode {
 8752                        let cursor = if action.ignore_newlines {
 8753                            movement::previous_word_start(map, selection.head())
 8754                        } else {
 8755                            movement::previous_word_start_or_newline(map, selection.head())
 8756                        };
 8757                        selection.set_head(cursor, SelectionGoal::None);
 8758                    }
 8759                });
 8760            });
 8761            this.insert("", window, cx);
 8762        });
 8763    }
 8764
 8765    pub fn delete_to_previous_subword_start(
 8766        &mut self,
 8767        _: &DeleteToPreviousSubwordStart,
 8768        window: &mut Window,
 8769        cx: &mut Context<Self>,
 8770    ) {
 8771        self.transact(window, cx, |this, window, cx| {
 8772            this.select_autoclose_pair(window, cx);
 8773            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8774                let line_mode = s.line_mode;
 8775                s.move_with(|map, selection| {
 8776                    if selection.is_empty() && !line_mode {
 8777                        let cursor = movement::previous_subword_start(map, selection.head());
 8778                        selection.set_head(cursor, SelectionGoal::None);
 8779                    }
 8780                });
 8781            });
 8782            this.insert("", window, cx);
 8783        });
 8784    }
 8785
 8786    pub fn move_to_next_word_end(
 8787        &mut self,
 8788        _: &MoveToNextWordEnd,
 8789        window: &mut Window,
 8790        cx: &mut Context<Self>,
 8791    ) {
 8792        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8793            s.move_cursors_with(|map, head, _| {
 8794                (movement::next_word_end(map, head), SelectionGoal::None)
 8795            });
 8796        })
 8797    }
 8798
 8799    pub fn move_to_next_subword_end(
 8800        &mut self,
 8801        _: &MoveToNextSubwordEnd,
 8802        window: &mut Window,
 8803        cx: &mut Context<Self>,
 8804    ) {
 8805        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8806            s.move_cursors_with(|map, head, _| {
 8807                (movement::next_subword_end(map, head), SelectionGoal::None)
 8808            });
 8809        })
 8810    }
 8811
 8812    pub fn select_to_next_word_end(
 8813        &mut self,
 8814        _: &SelectToNextWordEnd,
 8815        window: &mut Window,
 8816        cx: &mut Context<Self>,
 8817    ) {
 8818        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8819            s.move_heads_with(|map, head, _| {
 8820                (movement::next_word_end(map, head), SelectionGoal::None)
 8821            });
 8822        })
 8823    }
 8824
 8825    pub fn select_to_next_subword_end(
 8826        &mut self,
 8827        _: &SelectToNextSubwordEnd,
 8828        window: &mut Window,
 8829        cx: &mut Context<Self>,
 8830    ) {
 8831        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8832            s.move_heads_with(|map, head, _| {
 8833                (movement::next_subword_end(map, head), SelectionGoal::None)
 8834            });
 8835        })
 8836    }
 8837
 8838    pub fn delete_to_next_word_end(
 8839        &mut self,
 8840        action: &DeleteToNextWordEnd,
 8841        window: &mut Window,
 8842        cx: &mut Context<Self>,
 8843    ) {
 8844        self.transact(window, cx, |this, window, cx| {
 8845            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8846                let line_mode = s.line_mode;
 8847                s.move_with(|map, selection| {
 8848                    if selection.is_empty() && !line_mode {
 8849                        let cursor = if action.ignore_newlines {
 8850                            movement::next_word_end(map, selection.head())
 8851                        } else {
 8852                            movement::next_word_end_or_newline(map, selection.head())
 8853                        };
 8854                        selection.set_head(cursor, SelectionGoal::None);
 8855                    }
 8856                });
 8857            });
 8858            this.insert("", window, cx);
 8859        });
 8860    }
 8861
 8862    pub fn delete_to_next_subword_end(
 8863        &mut self,
 8864        _: &DeleteToNextSubwordEnd,
 8865        window: &mut Window,
 8866        cx: &mut Context<Self>,
 8867    ) {
 8868        self.transact(window, cx, |this, window, cx| {
 8869            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8870                s.move_with(|map, selection| {
 8871                    if selection.is_empty() {
 8872                        let cursor = movement::next_subword_end(map, selection.head());
 8873                        selection.set_head(cursor, SelectionGoal::None);
 8874                    }
 8875                });
 8876            });
 8877            this.insert("", window, cx);
 8878        });
 8879    }
 8880
 8881    pub fn move_to_beginning_of_line(
 8882        &mut self,
 8883        action: &MoveToBeginningOfLine,
 8884        window: &mut Window,
 8885        cx: &mut Context<Self>,
 8886    ) {
 8887        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8888            s.move_cursors_with(|map, head, _| {
 8889                (
 8890                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8891                    SelectionGoal::None,
 8892                )
 8893            });
 8894        })
 8895    }
 8896
 8897    pub fn select_to_beginning_of_line(
 8898        &mut self,
 8899        action: &SelectToBeginningOfLine,
 8900        window: &mut Window,
 8901        cx: &mut Context<Self>,
 8902    ) {
 8903        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8904            s.move_heads_with(|map, head, _| {
 8905                (
 8906                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8907                    SelectionGoal::None,
 8908                )
 8909            });
 8910        });
 8911    }
 8912
 8913    pub fn delete_to_beginning_of_line(
 8914        &mut self,
 8915        _: &DeleteToBeginningOfLine,
 8916        window: &mut Window,
 8917        cx: &mut Context<Self>,
 8918    ) {
 8919        self.transact(window, cx, |this, window, cx| {
 8920            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8921                s.move_with(|_, selection| {
 8922                    selection.reversed = true;
 8923                });
 8924            });
 8925
 8926            this.select_to_beginning_of_line(
 8927                &SelectToBeginningOfLine {
 8928                    stop_at_soft_wraps: false,
 8929                },
 8930                window,
 8931                cx,
 8932            );
 8933            this.backspace(&Backspace, window, cx);
 8934        });
 8935    }
 8936
 8937    pub fn move_to_end_of_line(
 8938        &mut self,
 8939        action: &MoveToEndOfLine,
 8940        window: &mut Window,
 8941        cx: &mut Context<Self>,
 8942    ) {
 8943        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8944            s.move_cursors_with(|map, head, _| {
 8945                (
 8946                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8947                    SelectionGoal::None,
 8948                )
 8949            });
 8950        })
 8951    }
 8952
 8953    pub fn select_to_end_of_line(
 8954        &mut self,
 8955        action: &SelectToEndOfLine,
 8956        window: &mut Window,
 8957        cx: &mut Context<Self>,
 8958    ) {
 8959        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8960            s.move_heads_with(|map, head, _| {
 8961                (
 8962                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8963                    SelectionGoal::None,
 8964                )
 8965            });
 8966        })
 8967    }
 8968
 8969    pub fn delete_to_end_of_line(
 8970        &mut self,
 8971        _: &DeleteToEndOfLine,
 8972        window: &mut Window,
 8973        cx: &mut Context<Self>,
 8974    ) {
 8975        self.transact(window, cx, |this, window, cx| {
 8976            this.select_to_end_of_line(
 8977                &SelectToEndOfLine {
 8978                    stop_at_soft_wraps: false,
 8979                },
 8980                window,
 8981                cx,
 8982            );
 8983            this.delete(&Delete, window, cx);
 8984        });
 8985    }
 8986
 8987    pub fn cut_to_end_of_line(
 8988        &mut self,
 8989        _: &CutToEndOfLine,
 8990        window: &mut Window,
 8991        cx: &mut Context<Self>,
 8992    ) {
 8993        self.transact(window, cx, |this, window, cx| {
 8994            this.select_to_end_of_line(
 8995                &SelectToEndOfLine {
 8996                    stop_at_soft_wraps: false,
 8997                },
 8998                window,
 8999                cx,
 9000            );
 9001            this.cut(&Cut, window, cx);
 9002        });
 9003    }
 9004
 9005    pub fn move_to_start_of_paragraph(
 9006        &mut self,
 9007        _: &MoveToStartOfParagraph,
 9008        window: &mut Window,
 9009        cx: &mut Context<Self>,
 9010    ) {
 9011        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9012            cx.propagate();
 9013            return;
 9014        }
 9015
 9016        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9017            s.move_with(|map, selection| {
 9018                selection.collapse_to(
 9019                    movement::start_of_paragraph(map, selection.head(), 1),
 9020                    SelectionGoal::None,
 9021                )
 9022            });
 9023        })
 9024    }
 9025
 9026    pub fn move_to_end_of_paragraph(
 9027        &mut self,
 9028        _: &MoveToEndOfParagraph,
 9029        window: &mut Window,
 9030        cx: &mut Context<Self>,
 9031    ) {
 9032        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9033            cx.propagate();
 9034            return;
 9035        }
 9036
 9037        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9038            s.move_with(|map, selection| {
 9039                selection.collapse_to(
 9040                    movement::end_of_paragraph(map, selection.head(), 1),
 9041                    SelectionGoal::None,
 9042                )
 9043            });
 9044        })
 9045    }
 9046
 9047    pub fn select_to_start_of_paragraph(
 9048        &mut self,
 9049        _: &SelectToStartOfParagraph,
 9050        window: &mut Window,
 9051        cx: &mut Context<Self>,
 9052    ) {
 9053        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9054            cx.propagate();
 9055            return;
 9056        }
 9057
 9058        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9059            s.move_heads_with(|map, head, _| {
 9060                (
 9061                    movement::start_of_paragraph(map, head, 1),
 9062                    SelectionGoal::None,
 9063                )
 9064            });
 9065        })
 9066    }
 9067
 9068    pub fn select_to_end_of_paragraph(
 9069        &mut self,
 9070        _: &SelectToEndOfParagraph,
 9071        window: &mut Window,
 9072        cx: &mut Context<Self>,
 9073    ) {
 9074        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9075            cx.propagate();
 9076            return;
 9077        }
 9078
 9079        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9080            s.move_heads_with(|map, head, _| {
 9081                (
 9082                    movement::end_of_paragraph(map, head, 1),
 9083                    SelectionGoal::None,
 9084                )
 9085            });
 9086        })
 9087    }
 9088
 9089    pub fn move_to_beginning(
 9090        &mut self,
 9091        _: &MoveToBeginning,
 9092        window: &mut Window,
 9093        cx: &mut Context<Self>,
 9094    ) {
 9095        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9096            cx.propagate();
 9097            return;
 9098        }
 9099
 9100        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9101            s.select_ranges(vec![0..0]);
 9102        });
 9103    }
 9104
 9105    pub fn select_to_beginning(
 9106        &mut self,
 9107        _: &SelectToBeginning,
 9108        window: &mut Window,
 9109        cx: &mut Context<Self>,
 9110    ) {
 9111        let mut selection = self.selections.last::<Point>(cx);
 9112        selection.set_head(Point::zero(), SelectionGoal::None);
 9113
 9114        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9115            s.select(vec![selection]);
 9116        });
 9117    }
 9118
 9119    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9120        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 9121            cx.propagate();
 9122            return;
 9123        }
 9124
 9125        let cursor = self.buffer.read(cx).read(cx).len();
 9126        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9127            s.select_ranges(vec![cursor..cursor])
 9128        });
 9129    }
 9130
 9131    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 9132        self.nav_history = nav_history;
 9133    }
 9134
 9135    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 9136        self.nav_history.as_ref()
 9137    }
 9138
 9139    fn push_to_nav_history(
 9140        &mut self,
 9141        cursor_anchor: Anchor,
 9142        new_position: Option<Point>,
 9143        cx: &mut Context<Self>,
 9144    ) {
 9145        if let Some(nav_history) = self.nav_history.as_mut() {
 9146            let buffer = self.buffer.read(cx).read(cx);
 9147            let cursor_position = cursor_anchor.to_point(&buffer);
 9148            let scroll_state = self.scroll_manager.anchor();
 9149            let scroll_top_row = scroll_state.top_row(&buffer);
 9150            drop(buffer);
 9151
 9152            if let Some(new_position) = new_position {
 9153                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 9154                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 9155                    return;
 9156                }
 9157            }
 9158
 9159            nav_history.push(
 9160                Some(NavigationData {
 9161                    cursor_anchor,
 9162                    cursor_position,
 9163                    scroll_anchor: scroll_state,
 9164                    scroll_top_row,
 9165                }),
 9166                cx,
 9167            );
 9168        }
 9169    }
 9170
 9171    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 9172        let buffer = self.buffer.read(cx).snapshot(cx);
 9173        let mut selection = self.selections.first::<usize>(cx);
 9174        selection.set_head(buffer.len(), SelectionGoal::None);
 9175        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9176            s.select(vec![selection]);
 9177        });
 9178    }
 9179
 9180    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 9181        let end = self.buffer.read(cx).read(cx).len();
 9182        self.change_selections(None, window, cx, |s| {
 9183            s.select_ranges(vec![0..end]);
 9184        });
 9185    }
 9186
 9187    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 9188        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9189        let mut selections = self.selections.all::<Point>(cx);
 9190        let max_point = display_map.buffer_snapshot.max_point();
 9191        for selection in &mut selections {
 9192            let rows = selection.spanned_rows(true, &display_map);
 9193            selection.start = Point::new(rows.start.0, 0);
 9194            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 9195            selection.reversed = false;
 9196        }
 9197        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9198            s.select(selections);
 9199        });
 9200    }
 9201
 9202    pub fn split_selection_into_lines(
 9203        &mut self,
 9204        _: &SplitSelectionIntoLines,
 9205        window: &mut Window,
 9206        cx: &mut Context<Self>,
 9207    ) {
 9208        let selections = self
 9209            .selections
 9210            .all::<Point>(cx)
 9211            .into_iter()
 9212            .map(|selection| selection.start..selection.end)
 9213            .collect::<Vec<_>>();
 9214        self.unfold_ranges(&selections, true, true, cx);
 9215
 9216        let mut new_selection_ranges = Vec::new();
 9217        {
 9218            let buffer = self.buffer.read(cx).read(cx);
 9219            for selection in selections {
 9220                for row in selection.start.row..selection.end.row {
 9221                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 9222                    new_selection_ranges.push(cursor..cursor);
 9223                }
 9224
 9225                let is_multiline_selection = selection.start.row != selection.end.row;
 9226                // Don't insert last one if it's a multi-line selection ending at the start of a line,
 9227                // so this action feels more ergonomic when paired with other selection operations
 9228                let should_skip_last = is_multiline_selection && selection.end.column == 0;
 9229                if !should_skip_last {
 9230                    new_selection_ranges.push(selection.end..selection.end);
 9231                }
 9232            }
 9233        }
 9234        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9235            s.select_ranges(new_selection_ranges);
 9236        });
 9237    }
 9238
 9239    pub fn add_selection_above(
 9240        &mut self,
 9241        _: &AddSelectionAbove,
 9242        window: &mut Window,
 9243        cx: &mut Context<Self>,
 9244    ) {
 9245        self.add_selection(true, window, cx);
 9246    }
 9247
 9248    pub fn add_selection_below(
 9249        &mut self,
 9250        _: &AddSelectionBelow,
 9251        window: &mut Window,
 9252        cx: &mut Context<Self>,
 9253    ) {
 9254        self.add_selection(false, window, cx);
 9255    }
 9256
 9257    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 9258        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9259        let mut selections = self.selections.all::<Point>(cx);
 9260        let text_layout_details = self.text_layout_details(window);
 9261        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 9262            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 9263            let range = oldest_selection.display_range(&display_map).sorted();
 9264
 9265            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 9266            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 9267            let positions = start_x.min(end_x)..start_x.max(end_x);
 9268
 9269            selections.clear();
 9270            let mut stack = Vec::new();
 9271            for row in range.start.row().0..=range.end.row().0 {
 9272                if let Some(selection) = self.selections.build_columnar_selection(
 9273                    &display_map,
 9274                    DisplayRow(row),
 9275                    &positions,
 9276                    oldest_selection.reversed,
 9277                    &text_layout_details,
 9278                ) {
 9279                    stack.push(selection.id);
 9280                    selections.push(selection);
 9281                }
 9282            }
 9283
 9284            if above {
 9285                stack.reverse();
 9286            }
 9287
 9288            AddSelectionsState { above, stack }
 9289        });
 9290
 9291        let last_added_selection = *state.stack.last().unwrap();
 9292        let mut new_selections = Vec::new();
 9293        if above == state.above {
 9294            let end_row = if above {
 9295                DisplayRow(0)
 9296            } else {
 9297                display_map.max_point().row()
 9298            };
 9299
 9300            'outer: for selection in selections {
 9301                if selection.id == last_added_selection {
 9302                    let range = selection.display_range(&display_map).sorted();
 9303                    debug_assert_eq!(range.start.row(), range.end.row());
 9304                    let mut row = range.start.row();
 9305                    let positions =
 9306                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 9307                            px(start)..px(end)
 9308                        } else {
 9309                            let start_x =
 9310                                display_map.x_for_display_point(range.start, &text_layout_details);
 9311                            let end_x =
 9312                                display_map.x_for_display_point(range.end, &text_layout_details);
 9313                            start_x.min(end_x)..start_x.max(end_x)
 9314                        };
 9315
 9316                    while row != end_row {
 9317                        if above {
 9318                            row.0 -= 1;
 9319                        } else {
 9320                            row.0 += 1;
 9321                        }
 9322
 9323                        if let Some(new_selection) = self.selections.build_columnar_selection(
 9324                            &display_map,
 9325                            row,
 9326                            &positions,
 9327                            selection.reversed,
 9328                            &text_layout_details,
 9329                        ) {
 9330                            state.stack.push(new_selection.id);
 9331                            if above {
 9332                                new_selections.push(new_selection);
 9333                                new_selections.push(selection);
 9334                            } else {
 9335                                new_selections.push(selection);
 9336                                new_selections.push(new_selection);
 9337                            }
 9338
 9339                            continue 'outer;
 9340                        }
 9341                    }
 9342                }
 9343
 9344                new_selections.push(selection);
 9345            }
 9346        } else {
 9347            new_selections = selections;
 9348            new_selections.retain(|s| s.id != last_added_selection);
 9349            state.stack.pop();
 9350        }
 9351
 9352        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9353            s.select(new_selections);
 9354        });
 9355        if state.stack.len() > 1 {
 9356            self.add_selections_state = Some(state);
 9357        }
 9358    }
 9359
 9360    pub fn select_next_match_internal(
 9361        &mut self,
 9362        display_map: &DisplaySnapshot,
 9363        replace_newest: bool,
 9364        autoscroll: Option<Autoscroll>,
 9365        window: &mut Window,
 9366        cx: &mut Context<Self>,
 9367    ) -> Result<()> {
 9368        fn select_next_match_ranges(
 9369            this: &mut Editor,
 9370            range: Range<usize>,
 9371            replace_newest: bool,
 9372            auto_scroll: Option<Autoscroll>,
 9373            window: &mut Window,
 9374            cx: &mut Context<Editor>,
 9375        ) {
 9376            this.unfold_ranges(&[range.clone()], false, true, cx);
 9377            this.change_selections(auto_scroll, window, cx, |s| {
 9378                if replace_newest {
 9379                    s.delete(s.newest_anchor().id);
 9380                }
 9381                s.insert_range(range.clone());
 9382            });
 9383        }
 9384
 9385        let buffer = &display_map.buffer_snapshot;
 9386        let mut selections = self.selections.all::<usize>(cx);
 9387        if let Some(mut select_next_state) = self.select_next_state.take() {
 9388            let query = &select_next_state.query;
 9389            if !select_next_state.done {
 9390                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9391                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9392                let mut next_selected_range = None;
 9393
 9394                let bytes_after_last_selection =
 9395                    buffer.bytes_in_range(last_selection.end..buffer.len());
 9396                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 9397                let query_matches = query
 9398                    .stream_find_iter(bytes_after_last_selection)
 9399                    .map(|result| (last_selection.end, result))
 9400                    .chain(
 9401                        query
 9402                            .stream_find_iter(bytes_before_first_selection)
 9403                            .map(|result| (0, result)),
 9404                    );
 9405
 9406                for (start_offset, query_match) in query_matches {
 9407                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9408                    let offset_range =
 9409                        start_offset + query_match.start()..start_offset + query_match.end();
 9410                    let display_range = offset_range.start.to_display_point(display_map)
 9411                        ..offset_range.end.to_display_point(display_map);
 9412
 9413                    if !select_next_state.wordwise
 9414                        || (!movement::is_inside_word(display_map, display_range.start)
 9415                            && !movement::is_inside_word(display_map, display_range.end))
 9416                    {
 9417                        // TODO: This is n^2, because we might check all the selections
 9418                        if !selections
 9419                            .iter()
 9420                            .any(|selection| selection.range().overlaps(&offset_range))
 9421                        {
 9422                            next_selected_range = Some(offset_range);
 9423                            break;
 9424                        }
 9425                    }
 9426                }
 9427
 9428                if let Some(next_selected_range) = next_selected_range {
 9429                    select_next_match_ranges(
 9430                        self,
 9431                        next_selected_range,
 9432                        replace_newest,
 9433                        autoscroll,
 9434                        window,
 9435                        cx,
 9436                    );
 9437                } else {
 9438                    select_next_state.done = true;
 9439                }
 9440            }
 9441
 9442            self.select_next_state = Some(select_next_state);
 9443        } else {
 9444            let mut only_carets = true;
 9445            let mut same_text_selected = true;
 9446            let mut selected_text = None;
 9447
 9448            let mut selections_iter = selections.iter().peekable();
 9449            while let Some(selection) = selections_iter.next() {
 9450                if selection.start != selection.end {
 9451                    only_carets = false;
 9452                }
 9453
 9454                if same_text_selected {
 9455                    if selected_text.is_none() {
 9456                        selected_text =
 9457                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9458                    }
 9459
 9460                    if let Some(next_selection) = selections_iter.peek() {
 9461                        if next_selection.range().len() == selection.range().len() {
 9462                            let next_selected_text = buffer
 9463                                .text_for_range(next_selection.range())
 9464                                .collect::<String>();
 9465                            if Some(next_selected_text) != selected_text {
 9466                                same_text_selected = false;
 9467                                selected_text = None;
 9468                            }
 9469                        } else {
 9470                            same_text_selected = false;
 9471                            selected_text = None;
 9472                        }
 9473                    }
 9474                }
 9475            }
 9476
 9477            if only_carets {
 9478                for selection in &mut selections {
 9479                    let word_range = movement::surrounding_word(
 9480                        display_map,
 9481                        selection.start.to_display_point(display_map),
 9482                    );
 9483                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9484                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9485                    selection.goal = SelectionGoal::None;
 9486                    selection.reversed = false;
 9487                    select_next_match_ranges(
 9488                        self,
 9489                        selection.start..selection.end,
 9490                        replace_newest,
 9491                        autoscroll,
 9492                        window,
 9493                        cx,
 9494                    );
 9495                }
 9496
 9497                if selections.len() == 1 {
 9498                    let selection = selections
 9499                        .last()
 9500                        .expect("ensured that there's only one selection");
 9501                    let query = buffer
 9502                        .text_for_range(selection.start..selection.end)
 9503                        .collect::<String>();
 9504                    let is_empty = query.is_empty();
 9505                    let select_state = SelectNextState {
 9506                        query: AhoCorasick::new(&[query])?,
 9507                        wordwise: true,
 9508                        done: is_empty,
 9509                    };
 9510                    self.select_next_state = Some(select_state);
 9511                } else {
 9512                    self.select_next_state = None;
 9513                }
 9514            } else if let Some(selected_text) = selected_text {
 9515                self.select_next_state = Some(SelectNextState {
 9516                    query: AhoCorasick::new(&[selected_text])?,
 9517                    wordwise: false,
 9518                    done: false,
 9519                });
 9520                self.select_next_match_internal(
 9521                    display_map,
 9522                    replace_newest,
 9523                    autoscroll,
 9524                    window,
 9525                    cx,
 9526                )?;
 9527            }
 9528        }
 9529        Ok(())
 9530    }
 9531
 9532    pub fn select_all_matches(
 9533        &mut self,
 9534        _action: &SelectAllMatches,
 9535        window: &mut Window,
 9536        cx: &mut Context<Self>,
 9537    ) -> Result<()> {
 9538        self.push_to_selection_history();
 9539        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9540
 9541        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9542        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9543            return Ok(());
 9544        };
 9545        if select_next_state.done {
 9546            return Ok(());
 9547        }
 9548
 9549        let mut new_selections = self.selections.all::<usize>(cx);
 9550
 9551        let buffer = &display_map.buffer_snapshot;
 9552        let query_matches = select_next_state
 9553            .query
 9554            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9555
 9556        for query_match in query_matches {
 9557            let query_match = query_match.unwrap(); // can only fail due to I/O
 9558            let offset_range = query_match.start()..query_match.end();
 9559            let display_range = offset_range.start.to_display_point(&display_map)
 9560                ..offset_range.end.to_display_point(&display_map);
 9561
 9562            if !select_next_state.wordwise
 9563                || (!movement::is_inside_word(&display_map, display_range.start)
 9564                    && !movement::is_inside_word(&display_map, display_range.end))
 9565            {
 9566                self.selections.change_with(cx, |selections| {
 9567                    new_selections.push(Selection {
 9568                        id: selections.new_selection_id(),
 9569                        start: offset_range.start,
 9570                        end: offset_range.end,
 9571                        reversed: false,
 9572                        goal: SelectionGoal::None,
 9573                    });
 9574                });
 9575            }
 9576        }
 9577
 9578        new_selections.sort_by_key(|selection| selection.start);
 9579        let mut ix = 0;
 9580        while ix + 1 < new_selections.len() {
 9581            let current_selection = &new_selections[ix];
 9582            let next_selection = &new_selections[ix + 1];
 9583            if current_selection.range().overlaps(&next_selection.range()) {
 9584                if current_selection.id < next_selection.id {
 9585                    new_selections.remove(ix + 1);
 9586                } else {
 9587                    new_selections.remove(ix);
 9588                }
 9589            } else {
 9590                ix += 1;
 9591            }
 9592        }
 9593
 9594        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9595
 9596        for selection in new_selections.iter_mut() {
 9597            selection.reversed = reversed;
 9598        }
 9599
 9600        select_next_state.done = true;
 9601        self.unfold_ranges(
 9602            &new_selections
 9603                .iter()
 9604                .map(|selection| selection.range())
 9605                .collect::<Vec<_>>(),
 9606            false,
 9607            false,
 9608            cx,
 9609        );
 9610        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9611            selections.select(new_selections)
 9612        });
 9613
 9614        Ok(())
 9615    }
 9616
 9617    pub fn select_next(
 9618        &mut self,
 9619        action: &SelectNext,
 9620        window: &mut Window,
 9621        cx: &mut Context<Self>,
 9622    ) -> Result<()> {
 9623        self.push_to_selection_history();
 9624        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9625        self.select_next_match_internal(
 9626            &display_map,
 9627            action.replace_newest,
 9628            Some(Autoscroll::newest()),
 9629            window,
 9630            cx,
 9631        )?;
 9632        Ok(())
 9633    }
 9634
 9635    pub fn select_previous(
 9636        &mut self,
 9637        action: &SelectPrevious,
 9638        window: &mut Window,
 9639        cx: &mut Context<Self>,
 9640    ) -> Result<()> {
 9641        self.push_to_selection_history();
 9642        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9643        let buffer = &display_map.buffer_snapshot;
 9644        let mut selections = self.selections.all::<usize>(cx);
 9645        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9646            let query = &select_prev_state.query;
 9647            if !select_prev_state.done {
 9648                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9649                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9650                let mut next_selected_range = None;
 9651                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9652                let bytes_before_last_selection =
 9653                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9654                let bytes_after_first_selection =
 9655                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9656                let query_matches = query
 9657                    .stream_find_iter(bytes_before_last_selection)
 9658                    .map(|result| (last_selection.start, result))
 9659                    .chain(
 9660                        query
 9661                            .stream_find_iter(bytes_after_first_selection)
 9662                            .map(|result| (buffer.len(), result)),
 9663                    );
 9664                for (end_offset, query_match) in query_matches {
 9665                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9666                    let offset_range =
 9667                        end_offset - query_match.end()..end_offset - query_match.start();
 9668                    let display_range = offset_range.start.to_display_point(&display_map)
 9669                        ..offset_range.end.to_display_point(&display_map);
 9670
 9671                    if !select_prev_state.wordwise
 9672                        || (!movement::is_inside_word(&display_map, display_range.start)
 9673                            && !movement::is_inside_word(&display_map, display_range.end))
 9674                    {
 9675                        next_selected_range = Some(offset_range);
 9676                        break;
 9677                    }
 9678                }
 9679
 9680                if let Some(next_selected_range) = next_selected_range {
 9681                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9682                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9683                        if action.replace_newest {
 9684                            s.delete(s.newest_anchor().id);
 9685                        }
 9686                        s.insert_range(next_selected_range);
 9687                    });
 9688                } else {
 9689                    select_prev_state.done = true;
 9690                }
 9691            }
 9692
 9693            self.select_prev_state = Some(select_prev_state);
 9694        } else {
 9695            let mut only_carets = true;
 9696            let mut same_text_selected = true;
 9697            let mut selected_text = None;
 9698
 9699            let mut selections_iter = selections.iter().peekable();
 9700            while let Some(selection) = selections_iter.next() {
 9701                if selection.start != selection.end {
 9702                    only_carets = false;
 9703                }
 9704
 9705                if same_text_selected {
 9706                    if selected_text.is_none() {
 9707                        selected_text =
 9708                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9709                    }
 9710
 9711                    if let Some(next_selection) = selections_iter.peek() {
 9712                        if next_selection.range().len() == selection.range().len() {
 9713                            let next_selected_text = buffer
 9714                                .text_for_range(next_selection.range())
 9715                                .collect::<String>();
 9716                            if Some(next_selected_text) != selected_text {
 9717                                same_text_selected = false;
 9718                                selected_text = None;
 9719                            }
 9720                        } else {
 9721                            same_text_selected = false;
 9722                            selected_text = None;
 9723                        }
 9724                    }
 9725                }
 9726            }
 9727
 9728            if only_carets {
 9729                for selection in &mut selections {
 9730                    let word_range = movement::surrounding_word(
 9731                        &display_map,
 9732                        selection.start.to_display_point(&display_map),
 9733                    );
 9734                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9735                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9736                    selection.goal = SelectionGoal::None;
 9737                    selection.reversed = false;
 9738                }
 9739                if selections.len() == 1 {
 9740                    let selection = selections
 9741                        .last()
 9742                        .expect("ensured that there's only one selection");
 9743                    let query = buffer
 9744                        .text_for_range(selection.start..selection.end)
 9745                        .collect::<String>();
 9746                    let is_empty = query.is_empty();
 9747                    let select_state = SelectNextState {
 9748                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9749                        wordwise: true,
 9750                        done: is_empty,
 9751                    };
 9752                    self.select_prev_state = Some(select_state);
 9753                } else {
 9754                    self.select_prev_state = None;
 9755                }
 9756
 9757                self.unfold_ranges(
 9758                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9759                    false,
 9760                    true,
 9761                    cx,
 9762                );
 9763                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9764                    s.select(selections);
 9765                });
 9766            } else if let Some(selected_text) = selected_text {
 9767                self.select_prev_state = Some(SelectNextState {
 9768                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9769                    wordwise: false,
 9770                    done: false,
 9771                });
 9772                self.select_previous(action, window, cx)?;
 9773            }
 9774        }
 9775        Ok(())
 9776    }
 9777
 9778    pub fn toggle_comments(
 9779        &mut self,
 9780        action: &ToggleComments,
 9781        window: &mut Window,
 9782        cx: &mut Context<Self>,
 9783    ) {
 9784        if self.read_only(cx) {
 9785            return;
 9786        }
 9787        let text_layout_details = &self.text_layout_details(window);
 9788        self.transact(window, cx, |this, window, cx| {
 9789            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9790            let mut edits = Vec::new();
 9791            let mut selection_edit_ranges = Vec::new();
 9792            let mut last_toggled_row = None;
 9793            let snapshot = this.buffer.read(cx).read(cx);
 9794            let empty_str: Arc<str> = Arc::default();
 9795            let mut suffixes_inserted = Vec::new();
 9796            let ignore_indent = action.ignore_indent;
 9797
 9798            fn comment_prefix_range(
 9799                snapshot: &MultiBufferSnapshot,
 9800                row: MultiBufferRow,
 9801                comment_prefix: &str,
 9802                comment_prefix_whitespace: &str,
 9803                ignore_indent: bool,
 9804            ) -> Range<Point> {
 9805                let indent_size = if ignore_indent {
 9806                    0
 9807                } else {
 9808                    snapshot.indent_size_for_line(row).len
 9809                };
 9810
 9811                let start = Point::new(row.0, indent_size);
 9812
 9813                let mut line_bytes = snapshot
 9814                    .bytes_in_range(start..snapshot.max_point())
 9815                    .flatten()
 9816                    .copied();
 9817
 9818                // If this line currently begins with the line comment prefix, then record
 9819                // the range containing the prefix.
 9820                if line_bytes
 9821                    .by_ref()
 9822                    .take(comment_prefix.len())
 9823                    .eq(comment_prefix.bytes())
 9824                {
 9825                    // Include any whitespace that matches the comment prefix.
 9826                    let matching_whitespace_len = line_bytes
 9827                        .zip(comment_prefix_whitespace.bytes())
 9828                        .take_while(|(a, b)| a == b)
 9829                        .count() as u32;
 9830                    let end = Point::new(
 9831                        start.row,
 9832                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9833                    );
 9834                    start..end
 9835                } else {
 9836                    start..start
 9837                }
 9838            }
 9839
 9840            fn comment_suffix_range(
 9841                snapshot: &MultiBufferSnapshot,
 9842                row: MultiBufferRow,
 9843                comment_suffix: &str,
 9844                comment_suffix_has_leading_space: bool,
 9845            ) -> Range<Point> {
 9846                let end = Point::new(row.0, snapshot.line_len(row));
 9847                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9848
 9849                let mut line_end_bytes = snapshot
 9850                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9851                    .flatten()
 9852                    .copied();
 9853
 9854                let leading_space_len = if suffix_start_column > 0
 9855                    && line_end_bytes.next() == Some(b' ')
 9856                    && comment_suffix_has_leading_space
 9857                {
 9858                    1
 9859                } else {
 9860                    0
 9861                };
 9862
 9863                // If this line currently begins with the line comment prefix, then record
 9864                // the range containing the prefix.
 9865                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9866                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9867                    start..end
 9868                } else {
 9869                    end..end
 9870                }
 9871            }
 9872
 9873            // TODO: Handle selections that cross excerpts
 9874            for selection in &mut selections {
 9875                let start_column = snapshot
 9876                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9877                    .len;
 9878                let language = if let Some(language) =
 9879                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9880                {
 9881                    language
 9882                } else {
 9883                    continue;
 9884                };
 9885
 9886                selection_edit_ranges.clear();
 9887
 9888                // If multiple selections contain a given row, avoid processing that
 9889                // row more than once.
 9890                let mut start_row = MultiBufferRow(selection.start.row);
 9891                if last_toggled_row == Some(start_row) {
 9892                    start_row = start_row.next_row();
 9893                }
 9894                let end_row =
 9895                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9896                        MultiBufferRow(selection.end.row - 1)
 9897                    } else {
 9898                        MultiBufferRow(selection.end.row)
 9899                    };
 9900                last_toggled_row = Some(end_row);
 9901
 9902                if start_row > end_row {
 9903                    continue;
 9904                }
 9905
 9906                // If the language has line comments, toggle those.
 9907                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9908
 9909                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9910                if ignore_indent {
 9911                    full_comment_prefixes = full_comment_prefixes
 9912                        .into_iter()
 9913                        .map(|s| Arc::from(s.trim_end()))
 9914                        .collect();
 9915                }
 9916
 9917                if !full_comment_prefixes.is_empty() {
 9918                    let first_prefix = full_comment_prefixes
 9919                        .first()
 9920                        .expect("prefixes is non-empty");
 9921                    let prefix_trimmed_lengths = full_comment_prefixes
 9922                        .iter()
 9923                        .map(|p| p.trim_end_matches(' ').len())
 9924                        .collect::<SmallVec<[usize; 4]>>();
 9925
 9926                    let mut all_selection_lines_are_comments = true;
 9927
 9928                    for row in start_row.0..=end_row.0 {
 9929                        let row = MultiBufferRow(row);
 9930                        if start_row < end_row && snapshot.is_line_blank(row) {
 9931                            continue;
 9932                        }
 9933
 9934                        let prefix_range = full_comment_prefixes
 9935                            .iter()
 9936                            .zip(prefix_trimmed_lengths.iter().copied())
 9937                            .map(|(prefix, trimmed_prefix_len)| {
 9938                                comment_prefix_range(
 9939                                    snapshot.deref(),
 9940                                    row,
 9941                                    &prefix[..trimmed_prefix_len],
 9942                                    &prefix[trimmed_prefix_len..],
 9943                                    ignore_indent,
 9944                                )
 9945                            })
 9946                            .max_by_key(|range| range.end.column - range.start.column)
 9947                            .expect("prefixes is non-empty");
 9948
 9949                        if prefix_range.is_empty() {
 9950                            all_selection_lines_are_comments = false;
 9951                        }
 9952
 9953                        selection_edit_ranges.push(prefix_range);
 9954                    }
 9955
 9956                    if all_selection_lines_are_comments {
 9957                        edits.extend(
 9958                            selection_edit_ranges
 9959                                .iter()
 9960                                .cloned()
 9961                                .map(|range| (range, empty_str.clone())),
 9962                        );
 9963                    } else {
 9964                        let min_column = selection_edit_ranges
 9965                            .iter()
 9966                            .map(|range| range.start.column)
 9967                            .min()
 9968                            .unwrap_or(0);
 9969                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9970                            let position = Point::new(range.start.row, min_column);
 9971                            (position..position, first_prefix.clone())
 9972                        }));
 9973                    }
 9974                } else if let Some((full_comment_prefix, comment_suffix)) =
 9975                    language.block_comment_delimiters()
 9976                {
 9977                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9978                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9979                    let prefix_range = comment_prefix_range(
 9980                        snapshot.deref(),
 9981                        start_row,
 9982                        comment_prefix,
 9983                        comment_prefix_whitespace,
 9984                        ignore_indent,
 9985                    );
 9986                    let suffix_range = comment_suffix_range(
 9987                        snapshot.deref(),
 9988                        end_row,
 9989                        comment_suffix.trim_start_matches(' '),
 9990                        comment_suffix.starts_with(' '),
 9991                    );
 9992
 9993                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9994                        edits.push((
 9995                            prefix_range.start..prefix_range.start,
 9996                            full_comment_prefix.clone(),
 9997                        ));
 9998                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9999                        suffixes_inserted.push((end_row, comment_suffix.len()));
10000                    } else {
10001                        edits.push((prefix_range, empty_str.clone()));
10002                        edits.push((suffix_range, empty_str.clone()));
10003                    }
10004                } else {
10005                    continue;
10006                }
10007            }
10008
10009            drop(snapshot);
10010            this.buffer.update(cx, |buffer, cx| {
10011                buffer.edit(edits, None, cx);
10012            });
10013
10014            // Adjust selections so that they end before any comment suffixes that
10015            // were inserted.
10016            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
10017            let mut selections = this.selections.all::<Point>(cx);
10018            let snapshot = this.buffer.read(cx).read(cx);
10019            for selection in &mut selections {
10020                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
10021                    match row.cmp(&MultiBufferRow(selection.end.row)) {
10022                        Ordering::Less => {
10023                            suffixes_inserted.next();
10024                            continue;
10025                        }
10026                        Ordering::Greater => break,
10027                        Ordering::Equal => {
10028                            if selection.end.column == snapshot.line_len(row) {
10029                                if selection.is_empty() {
10030                                    selection.start.column -= suffix_len as u32;
10031                                }
10032                                selection.end.column -= suffix_len as u32;
10033                            }
10034                            break;
10035                        }
10036                    }
10037                }
10038            }
10039
10040            drop(snapshot);
10041            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10042                s.select(selections)
10043            });
10044
10045            let selections = this.selections.all::<Point>(cx);
10046            let selections_on_single_row = selections.windows(2).all(|selections| {
10047                selections[0].start.row == selections[1].start.row
10048                    && selections[0].end.row == selections[1].end.row
10049                    && selections[0].start.row == selections[0].end.row
10050            });
10051            let selections_selecting = selections
10052                .iter()
10053                .any(|selection| selection.start != selection.end);
10054            let advance_downwards = action.advance_downwards
10055                && selections_on_single_row
10056                && !selections_selecting
10057                && !matches!(this.mode, EditorMode::SingleLine { .. });
10058
10059            if advance_downwards {
10060                let snapshot = this.buffer.read(cx).snapshot(cx);
10061
10062                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10063                    s.move_cursors_with(|display_snapshot, display_point, _| {
10064                        let mut point = display_point.to_point(display_snapshot);
10065                        point.row += 1;
10066                        point = snapshot.clip_point(point, Bias::Left);
10067                        let display_point = point.to_display_point(display_snapshot);
10068                        let goal = SelectionGoal::HorizontalPosition(
10069                            display_snapshot
10070                                .x_for_display_point(display_point, text_layout_details)
10071                                .into(),
10072                        );
10073                        (display_point, goal)
10074                    })
10075                });
10076            }
10077        });
10078    }
10079
10080    pub fn select_enclosing_symbol(
10081        &mut self,
10082        _: &SelectEnclosingSymbol,
10083        window: &mut Window,
10084        cx: &mut Context<Self>,
10085    ) {
10086        let buffer = self.buffer.read(cx).snapshot(cx);
10087        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10088
10089        fn update_selection(
10090            selection: &Selection<usize>,
10091            buffer_snap: &MultiBufferSnapshot,
10092        ) -> Option<Selection<usize>> {
10093            let cursor = selection.head();
10094            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
10095            for symbol in symbols.iter().rev() {
10096                let start = symbol.range.start.to_offset(buffer_snap);
10097                let end = symbol.range.end.to_offset(buffer_snap);
10098                let new_range = start..end;
10099                if start < selection.start || end > selection.end {
10100                    return Some(Selection {
10101                        id: selection.id,
10102                        start: new_range.start,
10103                        end: new_range.end,
10104                        goal: SelectionGoal::None,
10105                        reversed: selection.reversed,
10106                    });
10107                }
10108            }
10109            None
10110        }
10111
10112        let mut selected_larger_symbol = false;
10113        let new_selections = old_selections
10114            .iter()
10115            .map(|selection| match update_selection(selection, &buffer) {
10116                Some(new_selection) => {
10117                    if new_selection.range() != selection.range() {
10118                        selected_larger_symbol = true;
10119                    }
10120                    new_selection
10121                }
10122                None => selection.clone(),
10123            })
10124            .collect::<Vec<_>>();
10125
10126        if selected_larger_symbol {
10127            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10128                s.select(new_selections);
10129            });
10130        }
10131    }
10132
10133    pub fn select_larger_syntax_node(
10134        &mut self,
10135        _: &SelectLargerSyntaxNode,
10136        window: &mut Window,
10137        cx: &mut Context<Self>,
10138    ) {
10139        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10140        let buffer = self.buffer.read(cx).snapshot(cx);
10141        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
10142
10143        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10144        let mut selected_larger_node = false;
10145        let new_selections = old_selections
10146            .iter()
10147            .map(|selection| {
10148                let old_range = selection.start..selection.end;
10149                let mut new_range = old_range.clone();
10150                let mut new_node = None;
10151                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
10152                {
10153                    new_node = Some(node);
10154                    new_range = containing_range;
10155                    if !display_map.intersects_fold(new_range.start)
10156                        && !display_map.intersects_fold(new_range.end)
10157                    {
10158                        break;
10159                    }
10160                }
10161
10162                if let Some(node) = new_node {
10163                    // Log the ancestor, to support using this action as a way to explore TreeSitter
10164                    // nodes. Parent and grandparent are also logged because this operation will not
10165                    // visit nodes that have the same range as their parent.
10166                    log::info!("Node: {node:?}");
10167                    let parent = node.parent();
10168                    log::info!("Parent: {parent:?}");
10169                    let grandparent = parent.and_then(|x| x.parent());
10170                    log::info!("Grandparent: {grandparent:?}");
10171                }
10172
10173                selected_larger_node |= new_range != old_range;
10174                Selection {
10175                    id: selection.id,
10176                    start: new_range.start,
10177                    end: new_range.end,
10178                    goal: SelectionGoal::None,
10179                    reversed: selection.reversed,
10180                }
10181            })
10182            .collect::<Vec<_>>();
10183
10184        if selected_larger_node {
10185            stack.push(old_selections);
10186            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10187                s.select(new_selections);
10188            });
10189        }
10190        self.select_larger_syntax_node_stack = stack;
10191    }
10192
10193    pub fn select_smaller_syntax_node(
10194        &mut self,
10195        _: &SelectSmallerSyntaxNode,
10196        window: &mut Window,
10197        cx: &mut Context<Self>,
10198    ) {
10199        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
10200        if let Some(selections) = stack.pop() {
10201            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10202                s.select(selections.to_vec());
10203            });
10204        }
10205        self.select_larger_syntax_node_stack = stack;
10206    }
10207
10208    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
10209        if !EditorSettings::get_global(cx).gutter.runnables {
10210            self.clear_tasks();
10211            return Task::ready(());
10212        }
10213        let project = self.project.as_ref().map(Entity::downgrade);
10214        cx.spawn_in(window, |this, mut cx| async move {
10215            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
10216            let Some(project) = project.and_then(|p| p.upgrade()) else {
10217                return;
10218            };
10219            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
10220                this.display_map.update(cx, |map, cx| map.snapshot(cx))
10221            }) else {
10222                return;
10223            };
10224
10225            let hide_runnables = project
10226                .update(&mut cx, |project, cx| {
10227                    // Do not display any test indicators in non-dev server remote projects.
10228                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
10229                })
10230                .unwrap_or(true);
10231            if hide_runnables {
10232                return;
10233            }
10234            let new_rows =
10235                cx.background_spawn({
10236                    let snapshot = display_snapshot.clone();
10237                    async move {
10238                        Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
10239                    }
10240                })
10241                    .await;
10242
10243            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
10244            this.update(&mut cx, |this, _| {
10245                this.clear_tasks();
10246                for (key, value) in rows {
10247                    this.insert_tasks(key, value);
10248                }
10249            })
10250            .ok();
10251        })
10252    }
10253    fn fetch_runnable_ranges(
10254        snapshot: &DisplaySnapshot,
10255        range: Range<Anchor>,
10256    ) -> Vec<language::RunnableRange> {
10257        snapshot.buffer_snapshot.runnable_ranges(range).collect()
10258    }
10259
10260    fn runnable_rows(
10261        project: Entity<Project>,
10262        snapshot: DisplaySnapshot,
10263        runnable_ranges: Vec<RunnableRange>,
10264        mut cx: AsyncWindowContext,
10265    ) -> Vec<((BufferId, u32), RunnableTasks)> {
10266        runnable_ranges
10267            .into_iter()
10268            .filter_map(|mut runnable| {
10269                let tasks = cx
10270                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
10271                    .ok()?;
10272                if tasks.is_empty() {
10273                    return None;
10274                }
10275
10276                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
10277
10278                let row = snapshot
10279                    .buffer_snapshot
10280                    .buffer_line_for_row(MultiBufferRow(point.row))?
10281                    .1
10282                    .start
10283                    .row;
10284
10285                let context_range =
10286                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
10287                Some((
10288                    (runnable.buffer_id, row),
10289                    RunnableTasks {
10290                        templates: tasks,
10291                        offset: MultiBufferOffset(runnable.run_range.start),
10292                        context_range,
10293                        column: point.column,
10294                        extra_variables: runnable.extra_captures,
10295                    },
10296                ))
10297            })
10298            .collect()
10299    }
10300
10301    fn templates_with_tags(
10302        project: &Entity<Project>,
10303        runnable: &mut Runnable,
10304        cx: &mut App,
10305    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
10306        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
10307            let (worktree_id, file) = project
10308                .buffer_for_id(runnable.buffer, cx)
10309                .and_then(|buffer| buffer.read(cx).file())
10310                .map(|file| (file.worktree_id(cx), file.clone()))
10311                .unzip();
10312
10313            (
10314                project.task_store().read(cx).task_inventory().cloned(),
10315                worktree_id,
10316                file,
10317            )
10318        });
10319
10320        let tags = mem::take(&mut runnable.tags);
10321        let mut tags: Vec<_> = tags
10322            .into_iter()
10323            .flat_map(|tag| {
10324                let tag = tag.0.clone();
10325                inventory
10326                    .as_ref()
10327                    .into_iter()
10328                    .flat_map(|inventory| {
10329                        inventory.read(cx).list_tasks(
10330                            file.clone(),
10331                            Some(runnable.language.clone()),
10332                            worktree_id,
10333                            cx,
10334                        )
10335                    })
10336                    .filter(move |(_, template)| {
10337                        template.tags.iter().any(|source_tag| source_tag == &tag)
10338                    })
10339            })
10340            .sorted_by_key(|(kind, _)| kind.to_owned())
10341            .collect();
10342        if let Some((leading_tag_source, _)) = tags.first() {
10343            // Strongest source wins; if we have worktree tag binding, prefer that to
10344            // global and language bindings;
10345            // if we have a global binding, prefer that to language binding.
10346            let first_mismatch = tags
10347                .iter()
10348                .position(|(tag_source, _)| tag_source != leading_tag_source);
10349            if let Some(index) = first_mismatch {
10350                tags.truncate(index);
10351            }
10352        }
10353
10354        tags
10355    }
10356
10357    pub fn move_to_enclosing_bracket(
10358        &mut self,
10359        _: &MoveToEnclosingBracket,
10360        window: &mut Window,
10361        cx: &mut Context<Self>,
10362    ) {
10363        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10364            s.move_offsets_with(|snapshot, selection| {
10365                let Some(enclosing_bracket_ranges) =
10366                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
10367                else {
10368                    return;
10369                };
10370
10371                let mut best_length = usize::MAX;
10372                let mut best_inside = false;
10373                let mut best_in_bracket_range = false;
10374                let mut best_destination = None;
10375                for (open, close) in enclosing_bracket_ranges {
10376                    let close = close.to_inclusive();
10377                    let length = close.end() - open.start;
10378                    let inside = selection.start >= open.end && selection.end <= *close.start();
10379                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
10380                        || close.contains(&selection.head());
10381
10382                    // If best is next to a bracket and current isn't, skip
10383                    if !in_bracket_range && best_in_bracket_range {
10384                        continue;
10385                    }
10386
10387                    // Prefer smaller lengths unless best is inside and current isn't
10388                    if length > best_length && (best_inside || !inside) {
10389                        continue;
10390                    }
10391
10392                    best_length = length;
10393                    best_inside = inside;
10394                    best_in_bracket_range = in_bracket_range;
10395                    best_destination = Some(
10396                        if close.contains(&selection.start) && close.contains(&selection.end) {
10397                            if inside {
10398                                open.end
10399                            } else {
10400                                open.start
10401                            }
10402                        } else if inside {
10403                            *close.start()
10404                        } else {
10405                            *close.end()
10406                        },
10407                    );
10408                }
10409
10410                if let Some(destination) = best_destination {
10411                    selection.collapse_to(destination, SelectionGoal::None);
10412                }
10413            })
10414        });
10415    }
10416
10417    pub fn undo_selection(
10418        &mut self,
10419        _: &UndoSelection,
10420        window: &mut Window,
10421        cx: &mut Context<Self>,
10422    ) {
10423        self.end_selection(window, cx);
10424        self.selection_history.mode = SelectionHistoryMode::Undoing;
10425        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10426            self.change_selections(None, window, cx, |s| {
10427                s.select_anchors(entry.selections.to_vec())
10428            });
10429            self.select_next_state = entry.select_next_state;
10430            self.select_prev_state = entry.select_prev_state;
10431            self.add_selections_state = entry.add_selections_state;
10432            self.request_autoscroll(Autoscroll::newest(), cx);
10433        }
10434        self.selection_history.mode = SelectionHistoryMode::Normal;
10435    }
10436
10437    pub fn redo_selection(
10438        &mut self,
10439        _: &RedoSelection,
10440        window: &mut Window,
10441        cx: &mut Context<Self>,
10442    ) {
10443        self.end_selection(window, cx);
10444        self.selection_history.mode = SelectionHistoryMode::Redoing;
10445        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10446            self.change_selections(None, window, cx, |s| {
10447                s.select_anchors(entry.selections.to_vec())
10448            });
10449            self.select_next_state = entry.select_next_state;
10450            self.select_prev_state = entry.select_prev_state;
10451            self.add_selections_state = entry.add_selections_state;
10452            self.request_autoscroll(Autoscroll::newest(), cx);
10453        }
10454        self.selection_history.mode = SelectionHistoryMode::Normal;
10455    }
10456
10457    pub fn expand_excerpts(
10458        &mut self,
10459        action: &ExpandExcerpts,
10460        _: &mut Window,
10461        cx: &mut Context<Self>,
10462    ) {
10463        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10464    }
10465
10466    pub fn expand_excerpts_down(
10467        &mut self,
10468        action: &ExpandExcerptsDown,
10469        _: &mut Window,
10470        cx: &mut Context<Self>,
10471    ) {
10472        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10473    }
10474
10475    pub fn expand_excerpts_up(
10476        &mut self,
10477        action: &ExpandExcerptsUp,
10478        _: &mut Window,
10479        cx: &mut Context<Self>,
10480    ) {
10481        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10482    }
10483
10484    pub fn expand_excerpts_for_direction(
10485        &mut self,
10486        lines: u32,
10487        direction: ExpandExcerptDirection,
10488
10489        cx: &mut Context<Self>,
10490    ) {
10491        let selections = self.selections.disjoint_anchors();
10492
10493        let lines = if lines == 0 {
10494            EditorSettings::get_global(cx).expand_excerpt_lines
10495        } else {
10496            lines
10497        };
10498
10499        self.buffer.update(cx, |buffer, cx| {
10500            let snapshot = buffer.snapshot(cx);
10501            let mut excerpt_ids = selections
10502                .iter()
10503                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10504                .collect::<Vec<_>>();
10505            excerpt_ids.sort();
10506            excerpt_ids.dedup();
10507            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10508        })
10509    }
10510
10511    pub fn expand_excerpt(
10512        &mut self,
10513        excerpt: ExcerptId,
10514        direction: ExpandExcerptDirection,
10515        cx: &mut Context<Self>,
10516    ) {
10517        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10518        self.buffer.update(cx, |buffer, cx| {
10519            buffer.expand_excerpts([excerpt], lines, direction, cx)
10520        })
10521    }
10522
10523    pub fn go_to_singleton_buffer_point(
10524        &mut self,
10525        point: Point,
10526        window: &mut Window,
10527        cx: &mut Context<Self>,
10528    ) {
10529        self.go_to_singleton_buffer_range(point..point, window, cx);
10530    }
10531
10532    pub fn go_to_singleton_buffer_range(
10533        &mut self,
10534        range: Range<Point>,
10535        window: &mut Window,
10536        cx: &mut Context<Self>,
10537    ) {
10538        let multibuffer = self.buffer().read(cx);
10539        let Some(buffer) = multibuffer.as_singleton() else {
10540            return;
10541        };
10542        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10543            return;
10544        };
10545        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10546            return;
10547        };
10548        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10549            s.select_anchor_ranges([start..end])
10550        });
10551    }
10552
10553    fn go_to_diagnostic(
10554        &mut self,
10555        _: &GoToDiagnostic,
10556        window: &mut Window,
10557        cx: &mut Context<Self>,
10558    ) {
10559        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10560    }
10561
10562    fn go_to_prev_diagnostic(
10563        &mut self,
10564        _: &GoToPrevDiagnostic,
10565        window: &mut Window,
10566        cx: &mut Context<Self>,
10567    ) {
10568        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10569    }
10570
10571    pub fn go_to_diagnostic_impl(
10572        &mut self,
10573        direction: Direction,
10574        window: &mut Window,
10575        cx: &mut Context<Self>,
10576    ) {
10577        let buffer = self.buffer.read(cx).snapshot(cx);
10578        let selection = self.selections.newest::<usize>(cx);
10579
10580        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10581        if direction == Direction::Next {
10582            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10583                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10584                    return;
10585                };
10586                self.activate_diagnostics(
10587                    buffer_id,
10588                    popover.local_diagnostic.diagnostic.group_id,
10589                    window,
10590                    cx,
10591                );
10592                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10593                    let primary_range_start = active_diagnostics.primary_range.start;
10594                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10595                        let mut new_selection = s.newest_anchor().clone();
10596                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10597                        s.select_anchors(vec![new_selection.clone()]);
10598                    });
10599                    self.refresh_inline_completion(false, true, window, cx);
10600                }
10601                return;
10602            }
10603        }
10604
10605        let active_group_id = self
10606            .active_diagnostics
10607            .as_ref()
10608            .map(|active_group| active_group.group_id);
10609        let active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10610            active_diagnostics
10611                .primary_range
10612                .to_offset(&buffer)
10613                .to_inclusive()
10614        });
10615        let search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10616            if active_primary_range.contains(&selection.head()) {
10617                *active_primary_range.start()
10618            } else {
10619                selection.head()
10620            }
10621        } else {
10622            selection.head()
10623        };
10624
10625        let snapshot = self.snapshot(window, cx);
10626        let primary_diagnostics_before = buffer
10627            .diagnostics_in_range::<usize>(0..search_start)
10628            .filter(|entry| entry.diagnostic.is_primary)
10629            .filter(|entry| entry.range.start != entry.range.end)
10630            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10631            .filter(|entry| !snapshot.intersects_fold(entry.range.start))
10632            .collect::<Vec<_>>();
10633        let last_same_group_diagnostic_before = active_group_id.and_then(|active_group_id| {
10634            primary_diagnostics_before
10635                .iter()
10636                .position(|entry| entry.diagnostic.group_id == active_group_id)
10637        });
10638
10639        let primary_diagnostics_after = buffer
10640            .diagnostics_in_range::<usize>(search_start..buffer.len())
10641            .filter(|entry| entry.diagnostic.is_primary)
10642            .filter(|entry| entry.range.start != entry.range.end)
10643            .filter(|entry| entry.diagnostic.severity <= DiagnosticSeverity::WARNING)
10644            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10645            .collect::<Vec<_>>();
10646        let last_same_group_diagnostic_after = active_group_id.and_then(|active_group_id| {
10647            primary_diagnostics_after
10648                .iter()
10649                .enumerate()
10650                .rev()
10651                .find_map(|(i, entry)| {
10652                    if entry.diagnostic.group_id == active_group_id {
10653                        Some(i)
10654                    } else {
10655                        None
10656                    }
10657                })
10658        });
10659
10660        let next_primary_diagnostic = match direction {
10661            Direction::Prev => primary_diagnostics_before
10662                .iter()
10663                .take(last_same_group_diagnostic_before.unwrap_or(usize::MAX))
10664                .rev()
10665                .next(),
10666            Direction::Next => primary_diagnostics_after
10667                .iter()
10668                .skip(
10669                    last_same_group_diagnostic_after
10670                        .map(|index| index + 1)
10671                        .unwrap_or(0),
10672                )
10673                .next(),
10674        };
10675
10676        // Cycle around to the start of the buffer, potentially moving back to the start of
10677        // the currently active diagnostic.
10678        let cycle_around = || match direction {
10679            Direction::Prev => primary_diagnostics_after
10680                .iter()
10681                .rev()
10682                .chain(primary_diagnostics_before.iter().rev())
10683                .next(),
10684            Direction::Next => primary_diagnostics_before
10685                .iter()
10686                .chain(primary_diagnostics_after.iter())
10687                .next(),
10688        };
10689
10690        if let Some((primary_range, group_id)) = next_primary_diagnostic
10691            .or_else(cycle_around)
10692            .map(|entry| (&entry.range, entry.diagnostic.group_id))
10693        {
10694            let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10695                return;
10696            };
10697            self.activate_diagnostics(buffer_id, group_id, window, cx);
10698            if self.active_diagnostics.is_some() {
10699                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10700                    s.select(vec![Selection {
10701                        id: selection.id,
10702                        start: primary_range.start,
10703                        end: primary_range.start,
10704                        reversed: false,
10705                        goal: SelectionGoal::None,
10706                    }]);
10707                });
10708                self.refresh_inline_completion(false, true, window, cx);
10709            }
10710        }
10711    }
10712
10713    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10714        let snapshot = self.snapshot(window, cx);
10715        let selection = self.selections.newest::<Point>(cx);
10716        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10717    }
10718
10719    fn go_to_hunk_after_position(
10720        &mut self,
10721        snapshot: &EditorSnapshot,
10722        position: Point,
10723        window: &mut Window,
10724        cx: &mut Context<Editor>,
10725    ) -> Option<MultiBufferDiffHunk> {
10726        let mut hunk = snapshot
10727            .buffer_snapshot
10728            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10729            .find(|hunk| hunk.row_range.start.0 > position.row);
10730        if hunk.is_none() {
10731            hunk = snapshot
10732                .buffer_snapshot
10733                .diff_hunks_in_range(Point::zero()..position)
10734                .find(|hunk| hunk.row_range.end.0 < position.row)
10735        }
10736        if let Some(hunk) = &hunk {
10737            let destination = Point::new(hunk.row_range.start.0, 0);
10738            self.unfold_ranges(&[destination..destination], false, false, cx);
10739            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10740                s.select_ranges(vec![destination..destination]);
10741            });
10742        }
10743
10744        hunk
10745    }
10746
10747    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10748        let snapshot = self.snapshot(window, cx);
10749        let selection = self.selections.newest::<Point>(cx);
10750        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10751    }
10752
10753    fn go_to_hunk_before_position(
10754        &mut self,
10755        snapshot: &EditorSnapshot,
10756        position: Point,
10757        window: &mut Window,
10758        cx: &mut Context<Editor>,
10759    ) -> Option<MultiBufferDiffHunk> {
10760        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10761        if hunk.is_none() {
10762            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10763        }
10764        if let Some(hunk) = &hunk {
10765            let destination = Point::new(hunk.row_range.start.0, 0);
10766            self.unfold_ranges(&[destination..destination], false, false, cx);
10767            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10768                s.select_ranges(vec![destination..destination]);
10769            });
10770        }
10771
10772        hunk
10773    }
10774
10775    pub fn go_to_definition(
10776        &mut self,
10777        _: &GoToDefinition,
10778        window: &mut Window,
10779        cx: &mut Context<Self>,
10780    ) -> Task<Result<Navigated>> {
10781        let definition =
10782            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10783        cx.spawn_in(window, |editor, mut cx| async move {
10784            if definition.await? == Navigated::Yes {
10785                return Ok(Navigated::Yes);
10786            }
10787            match editor.update_in(&mut cx, |editor, window, cx| {
10788                editor.find_all_references(&FindAllReferences, window, cx)
10789            })? {
10790                Some(references) => references.await,
10791                None => Ok(Navigated::No),
10792            }
10793        })
10794    }
10795
10796    pub fn go_to_declaration(
10797        &mut self,
10798        _: &GoToDeclaration,
10799        window: &mut Window,
10800        cx: &mut Context<Self>,
10801    ) -> Task<Result<Navigated>> {
10802        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10803    }
10804
10805    pub fn go_to_declaration_split(
10806        &mut self,
10807        _: &GoToDeclaration,
10808        window: &mut Window,
10809        cx: &mut Context<Self>,
10810    ) -> Task<Result<Navigated>> {
10811        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10812    }
10813
10814    pub fn go_to_implementation(
10815        &mut self,
10816        _: &GoToImplementation,
10817        window: &mut Window,
10818        cx: &mut Context<Self>,
10819    ) -> Task<Result<Navigated>> {
10820        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10821    }
10822
10823    pub fn go_to_implementation_split(
10824        &mut self,
10825        _: &GoToImplementationSplit,
10826        window: &mut Window,
10827        cx: &mut Context<Self>,
10828    ) -> Task<Result<Navigated>> {
10829        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10830    }
10831
10832    pub fn go_to_type_definition(
10833        &mut self,
10834        _: &GoToTypeDefinition,
10835        window: &mut Window,
10836        cx: &mut Context<Self>,
10837    ) -> Task<Result<Navigated>> {
10838        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10839    }
10840
10841    pub fn go_to_definition_split(
10842        &mut self,
10843        _: &GoToDefinitionSplit,
10844        window: &mut Window,
10845        cx: &mut Context<Self>,
10846    ) -> Task<Result<Navigated>> {
10847        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10848    }
10849
10850    pub fn go_to_type_definition_split(
10851        &mut self,
10852        _: &GoToTypeDefinitionSplit,
10853        window: &mut Window,
10854        cx: &mut Context<Self>,
10855    ) -> Task<Result<Navigated>> {
10856        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10857    }
10858
10859    fn go_to_definition_of_kind(
10860        &mut self,
10861        kind: GotoDefinitionKind,
10862        split: bool,
10863        window: &mut Window,
10864        cx: &mut Context<Self>,
10865    ) -> Task<Result<Navigated>> {
10866        let Some(provider) = self.semantics_provider.clone() else {
10867            return Task::ready(Ok(Navigated::No));
10868        };
10869        let head = self.selections.newest::<usize>(cx).head();
10870        let buffer = self.buffer.read(cx);
10871        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10872            text_anchor
10873        } else {
10874            return Task::ready(Ok(Navigated::No));
10875        };
10876
10877        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10878            return Task::ready(Ok(Navigated::No));
10879        };
10880
10881        cx.spawn_in(window, |editor, mut cx| async move {
10882            let definitions = definitions.await?;
10883            let navigated = editor
10884                .update_in(&mut cx, |editor, window, cx| {
10885                    editor.navigate_to_hover_links(
10886                        Some(kind),
10887                        definitions
10888                            .into_iter()
10889                            .filter(|location| {
10890                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10891                            })
10892                            .map(HoverLink::Text)
10893                            .collect::<Vec<_>>(),
10894                        split,
10895                        window,
10896                        cx,
10897                    )
10898                })?
10899                .await?;
10900            anyhow::Ok(navigated)
10901        })
10902    }
10903
10904    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10905        let selection = self.selections.newest_anchor();
10906        let head = selection.head();
10907        let tail = selection.tail();
10908
10909        let Some((buffer, start_position)) =
10910            self.buffer.read(cx).text_anchor_for_position(head, cx)
10911        else {
10912            return;
10913        };
10914
10915        let end_position = if head != tail {
10916            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10917                return;
10918            };
10919            Some(pos)
10920        } else {
10921            None
10922        };
10923
10924        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10925            let url = if let Some(end_pos) = end_position {
10926                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10927            } else {
10928                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10929            };
10930
10931            if let Some(url) = url {
10932                editor.update(&mut cx, |_, cx| {
10933                    cx.open_url(&url);
10934                })
10935            } else {
10936                Ok(())
10937            }
10938        });
10939
10940        url_finder.detach();
10941    }
10942
10943    pub fn open_selected_filename(
10944        &mut self,
10945        _: &OpenSelectedFilename,
10946        window: &mut Window,
10947        cx: &mut Context<Self>,
10948    ) {
10949        let Some(workspace) = self.workspace() else {
10950            return;
10951        };
10952
10953        let position = self.selections.newest_anchor().head();
10954
10955        let Some((buffer, buffer_position)) =
10956            self.buffer.read(cx).text_anchor_for_position(position, cx)
10957        else {
10958            return;
10959        };
10960
10961        let project = self.project.clone();
10962
10963        cx.spawn_in(window, |_, mut cx| async move {
10964            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10965
10966            if let Some((_, path)) = result {
10967                workspace
10968                    .update_in(&mut cx, |workspace, window, cx| {
10969                        workspace.open_resolved_path(path, window, cx)
10970                    })?
10971                    .await?;
10972            }
10973            anyhow::Ok(())
10974        })
10975        .detach();
10976    }
10977
10978    pub(crate) fn navigate_to_hover_links(
10979        &mut self,
10980        kind: Option<GotoDefinitionKind>,
10981        mut definitions: Vec<HoverLink>,
10982        split: bool,
10983        window: &mut Window,
10984        cx: &mut Context<Editor>,
10985    ) -> Task<Result<Navigated>> {
10986        // If there is one definition, just open it directly
10987        if definitions.len() == 1 {
10988            let definition = definitions.pop().unwrap();
10989
10990            enum TargetTaskResult {
10991                Location(Option<Location>),
10992                AlreadyNavigated,
10993            }
10994
10995            let target_task = match definition {
10996                HoverLink::Text(link) => {
10997                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10998                }
10999                HoverLink::InlayHint(lsp_location, server_id) => {
11000                    let computation =
11001                        self.compute_target_location(lsp_location, server_id, window, cx);
11002                    cx.background_spawn(async move {
11003                        let location = computation.await?;
11004                        Ok(TargetTaskResult::Location(location))
11005                    })
11006                }
11007                HoverLink::Url(url) => {
11008                    cx.open_url(&url);
11009                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
11010                }
11011                HoverLink::File(path) => {
11012                    if let Some(workspace) = self.workspace() {
11013                        cx.spawn_in(window, |_, mut cx| async move {
11014                            workspace
11015                                .update_in(&mut cx, |workspace, window, cx| {
11016                                    workspace.open_resolved_path(path, window, cx)
11017                                })?
11018                                .await
11019                                .map(|_| TargetTaskResult::AlreadyNavigated)
11020                        })
11021                    } else {
11022                        Task::ready(Ok(TargetTaskResult::Location(None)))
11023                    }
11024                }
11025            };
11026            cx.spawn_in(window, |editor, mut cx| async move {
11027                let target = match target_task.await.context("target resolution task")? {
11028                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
11029                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
11030                    TargetTaskResult::Location(Some(target)) => target,
11031                };
11032
11033                editor.update_in(&mut cx, |editor, window, cx| {
11034                    let Some(workspace) = editor.workspace() else {
11035                        return Navigated::No;
11036                    };
11037                    let pane = workspace.read(cx).active_pane().clone();
11038
11039                    let range = target.range.to_point(target.buffer.read(cx));
11040                    let range = editor.range_for_match(&range);
11041                    let range = collapse_multiline_range(range);
11042
11043                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
11044                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
11045                    } else {
11046                        window.defer(cx, move |window, cx| {
11047                            let target_editor: Entity<Self> =
11048                                workspace.update(cx, |workspace, cx| {
11049                                    let pane = if split {
11050                                        workspace.adjacent_pane(window, cx)
11051                                    } else {
11052                                        workspace.active_pane().clone()
11053                                    };
11054
11055                                    workspace.open_project_item(
11056                                        pane,
11057                                        target.buffer.clone(),
11058                                        true,
11059                                        true,
11060                                        window,
11061                                        cx,
11062                                    )
11063                                });
11064                            target_editor.update(cx, |target_editor, cx| {
11065                                // When selecting a definition in a different buffer, disable the nav history
11066                                // to avoid creating a history entry at the previous cursor location.
11067                                pane.update(cx, |pane, _| pane.disable_history());
11068                                target_editor.go_to_singleton_buffer_range(range, window, cx);
11069                                pane.update(cx, |pane, _| pane.enable_history());
11070                            });
11071                        });
11072                    }
11073                    Navigated::Yes
11074                })
11075            })
11076        } else if !definitions.is_empty() {
11077            cx.spawn_in(window, |editor, mut cx| async move {
11078                let (title, location_tasks, workspace) = editor
11079                    .update_in(&mut cx, |editor, window, cx| {
11080                        let tab_kind = match kind {
11081                            Some(GotoDefinitionKind::Implementation) => "Implementations",
11082                            _ => "Definitions",
11083                        };
11084                        let title = definitions
11085                            .iter()
11086                            .find_map(|definition| match definition {
11087                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
11088                                    let buffer = origin.buffer.read(cx);
11089                                    format!(
11090                                        "{} for {}",
11091                                        tab_kind,
11092                                        buffer
11093                                            .text_for_range(origin.range.clone())
11094                                            .collect::<String>()
11095                                    )
11096                                }),
11097                                HoverLink::InlayHint(_, _) => None,
11098                                HoverLink::Url(_) => None,
11099                                HoverLink::File(_) => None,
11100                            })
11101                            .unwrap_or(tab_kind.to_string());
11102                        let location_tasks = definitions
11103                            .into_iter()
11104                            .map(|definition| match definition {
11105                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
11106                                HoverLink::InlayHint(lsp_location, server_id) => editor
11107                                    .compute_target_location(lsp_location, server_id, window, cx),
11108                                HoverLink::Url(_) => Task::ready(Ok(None)),
11109                                HoverLink::File(_) => Task::ready(Ok(None)),
11110                            })
11111                            .collect::<Vec<_>>();
11112                        (title, location_tasks, editor.workspace().clone())
11113                    })
11114                    .context("location tasks preparation")?;
11115
11116                let locations = future::join_all(location_tasks)
11117                    .await
11118                    .into_iter()
11119                    .filter_map(|location| location.transpose())
11120                    .collect::<Result<_>>()
11121                    .context("location tasks")?;
11122
11123                let Some(workspace) = workspace else {
11124                    return Ok(Navigated::No);
11125                };
11126                let opened = workspace
11127                    .update_in(&mut cx, |workspace, window, cx| {
11128                        Self::open_locations_in_multibuffer(
11129                            workspace,
11130                            locations,
11131                            title,
11132                            split,
11133                            MultibufferSelectionMode::First,
11134                            window,
11135                            cx,
11136                        )
11137                    })
11138                    .ok();
11139
11140                anyhow::Ok(Navigated::from_bool(opened.is_some()))
11141            })
11142        } else {
11143            Task::ready(Ok(Navigated::No))
11144        }
11145    }
11146
11147    fn compute_target_location(
11148        &self,
11149        lsp_location: lsp::Location,
11150        server_id: LanguageServerId,
11151        window: &mut Window,
11152        cx: &mut Context<Self>,
11153    ) -> Task<anyhow::Result<Option<Location>>> {
11154        let Some(project) = self.project.clone() else {
11155            return Task::ready(Ok(None));
11156        };
11157
11158        cx.spawn_in(window, move |editor, mut cx| async move {
11159            let location_task = editor.update(&mut cx, |_, cx| {
11160                project.update(cx, |project, cx| {
11161                    let language_server_name = project
11162                        .language_server_statuses(cx)
11163                        .find(|(id, _)| server_id == *id)
11164                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
11165                    language_server_name.map(|language_server_name| {
11166                        project.open_local_buffer_via_lsp(
11167                            lsp_location.uri.clone(),
11168                            server_id,
11169                            language_server_name,
11170                            cx,
11171                        )
11172                    })
11173                })
11174            })?;
11175            let location = match location_task {
11176                Some(task) => Some({
11177                    let target_buffer_handle = task.await.context("open local buffer")?;
11178                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
11179                        let target_start = target_buffer
11180                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
11181                        let target_end = target_buffer
11182                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
11183                        target_buffer.anchor_after(target_start)
11184                            ..target_buffer.anchor_before(target_end)
11185                    })?;
11186                    Location {
11187                        buffer: target_buffer_handle,
11188                        range,
11189                    }
11190                }),
11191                None => None,
11192            };
11193            Ok(location)
11194        })
11195    }
11196
11197    pub fn find_all_references(
11198        &mut self,
11199        _: &FindAllReferences,
11200        window: &mut Window,
11201        cx: &mut Context<Self>,
11202    ) -> Option<Task<Result<Navigated>>> {
11203        let selection = self.selections.newest::<usize>(cx);
11204        let multi_buffer = self.buffer.read(cx);
11205        let head = selection.head();
11206
11207        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
11208        let head_anchor = multi_buffer_snapshot.anchor_at(
11209            head,
11210            if head < selection.tail() {
11211                Bias::Right
11212            } else {
11213                Bias::Left
11214            },
11215        );
11216
11217        match self
11218            .find_all_references_task_sources
11219            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
11220        {
11221            Ok(_) => {
11222                log::info!(
11223                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
11224                );
11225                return None;
11226            }
11227            Err(i) => {
11228                self.find_all_references_task_sources.insert(i, head_anchor);
11229            }
11230        }
11231
11232        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
11233        let workspace = self.workspace()?;
11234        let project = workspace.read(cx).project().clone();
11235        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
11236        Some(cx.spawn_in(window, |editor, mut cx| async move {
11237            let _cleanup = defer({
11238                let mut cx = cx.clone();
11239                move || {
11240                    let _ = editor.update(&mut cx, |editor, _| {
11241                        if let Ok(i) =
11242                            editor
11243                                .find_all_references_task_sources
11244                                .binary_search_by(|anchor| {
11245                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
11246                                })
11247                        {
11248                            editor.find_all_references_task_sources.remove(i);
11249                        }
11250                    });
11251                }
11252            });
11253
11254            let locations = references.await?;
11255            if locations.is_empty() {
11256                return anyhow::Ok(Navigated::No);
11257            }
11258
11259            workspace.update_in(&mut cx, |workspace, window, cx| {
11260                let title = locations
11261                    .first()
11262                    .as_ref()
11263                    .map(|location| {
11264                        let buffer = location.buffer.read(cx);
11265                        format!(
11266                            "References to `{}`",
11267                            buffer
11268                                .text_for_range(location.range.clone())
11269                                .collect::<String>()
11270                        )
11271                    })
11272                    .unwrap();
11273                Self::open_locations_in_multibuffer(
11274                    workspace,
11275                    locations,
11276                    title,
11277                    false,
11278                    MultibufferSelectionMode::First,
11279                    window,
11280                    cx,
11281                );
11282                Navigated::Yes
11283            })
11284        }))
11285    }
11286
11287    /// Opens a multibuffer with the given project locations in it
11288    pub fn open_locations_in_multibuffer(
11289        workspace: &mut Workspace,
11290        mut locations: Vec<Location>,
11291        title: String,
11292        split: bool,
11293        multibuffer_selection_mode: MultibufferSelectionMode,
11294        window: &mut Window,
11295        cx: &mut Context<Workspace>,
11296    ) {
11297        // If there are multiple definitions, open them in a multibuffer
11298        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
11299        let mut locations = locations.into_iter().peekable();
11300        let mut ranges = Vec::new();
11301        let capability = workspace.project().read(cx).capability();
11302
11303        let excerpt_buffer = cx.new(|cx| {
11304            let mut multibuffer = MultiBuffer::new(capability);
11305            while let Some(location) = locations.next() {
11306                let buffer = location.buffer.read(cx);
11307                let mut ranges_for_buffer = Vec::new();
11308                let range = location.range.to_offset(buffer);
11309                ranges_for_buffer.push(range.clone());
11310
11311                while let Some(next_location) = locations.peek() {
11312                    if next_location.buffer == location.buffer {
11313                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
11314                        locations.next();
11315                    } else {
11316                        break;
11317                    }
11318                }
11319
11320                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
11321                ranges.extend(multibuffer.push_excerpts_with_context_lines(
11322                    location.buffer.clone(),
11323                    ranges_for_buffer,
11324                    DEFAULT_MULTIBUFFER_CONTEXT,
11325                    cx,
11326                ))
11327            }
11328
11329            multibuffer.with_title(title)
11330        });
11331
11332        let editor = cx.new(|cx| {
11333            Editor::for_multibuffer(
11334                excerpt_buffer,
11335                Some(workspace.project().clone()),
11336                true,
11337                window,
11338                cx,
11339            )
11340        });
11341        editor.update(cx, |editor, cx| {
11342            match multibuffer_selection_mode {
11343                MultibufferSelectionMode::First => {
11344                    if let Some(first_range) = ranges.first() {
11345                        editor.change_selections(None, window, cx, |selections| {
11346                            selections.clear_disjoint();
11347                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
11348                        });
11349                    }
11350                    editor.highlight_background::<Self>(
11351                        &ranges,
11352                        |theme| theme.editor_highlighted_line_background,
11353                        cx,
11354                    );
11355                }
11356                MultibufferSelectionMode::All => {
11357                    editor.change_selections(None, window, cx, |selections| {
11358                        selections.clear_disjoint();
11359                        selections.select_anchor_ranges(ranges);
11360                    });
11361                }
11362            }
11363            editor.register_buffers_with_language_servers(cx);
11364        });
11365
11366        let item = Box::new(editor);
11367        let item_id = item.item_id();
11368
11369        if split {
11370            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
11371        } else {
11372            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
11373                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
11374                    pane.close_current_preview_item(window, cx)
11375                } else {
11376                    None
11377                }
11378            });
11379            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
11380        }
11381        workspace.active_pane().update(cx, |pane, cx| {
11382            pane.set_preview_item_id(Some(item_id), cx);
11383        });
11384    }
11385
11386    pub fn rename(
11387        &mut self,
11388        _: &Rename,
11389        window: &mut Window,
11390        cx: &mut Context<Self>,
11391    ) -> Option<Task<Result<()>>> {
11392        use language::ToOffset as _;
11393
11394        let provider = self.semantics_provider.clone()?;
11395        let selection = self.selections.newest_anchor().clone();
11396        let (cursor_buffer, cursor_buffer_position) = self
11397            .buffer
11398            .read(cx)
11399            .text_anchor_for_position(selection.head(), cx)?;
11400        let (tail_buffer, cursor_buffer_position_end) = self
11401            .buffer
11402            .read(cx)
11403            .text_anchor_for_position(selection.tail(), cx)?;
11404        if tail_buffer != cursor_buffer {
11405            return None;
11406        }
11407
11408        let snapshot = cursor_buffer.read(cx).snapshot();
11409        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
11410        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11411        let prepare_rename = provider
11412            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11413            .unwrap_or_else(|| Task::ready(Ok(None)));
11414        drop(snapshot);
11415
11416        Some(cx.spawn_in(window, |this, mut cx| async move {
11417            let rename_range = if let Some(range) = prepare_rename.await? {
11418                Some(range)
11419            } else {
11420                this.update(&mut cx, |this, cx| {
11421                    let buffer = this.buffer.read(cx).snapshot(cx);
11422                    let mut buffer_highlights = this
11423                        .document_highlights_for_position(selection.head(), &buffer)
11424                        .filter(|highlight| {
11425                            highlight.start.excerpt_id == selection.head().excerpt_id
11426                                && highlight.end.excerpt_id == selection.head().excerpt_id
11427                        });
11428                    buffer_highlights
11429                        .next()
11430                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11431                })?
11432            };
11433            if let Some(rename_range) = rename_range {
11434                this.update_in(&mut cx, |this, window, cx| {
11435                    let snapshot = cursor_buffer.read(cx).snapshot();
11436                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11437                    let cursor_offset_in_rename_range =
11438                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11439                    let cursor_offset_in_rename_range_end =
11440                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11441
11442                    this.take_rename(false, window, cx);
11443                    let buffer = this.buffer.read(cx).read(cx);
11444                    let cursor_offset = selection.head().to_offset(&buffer);
11445                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11446                    let rename_end = rename_start + rename_buffer_range.len();
11447                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11448                    let mut old_highlight_id = None;
11449                    let old_name: Arc<str> = buffer
11450                        .chunks(rename_start..rename_end, true)
11451                        .map(|chunk| {
11452                            if old_highlight_id.is_none() {
11453                                old_highlight_id = chunk.syntax_highlight_id;
11454                            }
11455                            chunk.text
11456                        })
11457                        .collect::<String>()
11458                        .into();
11459
11460                    drop(buffer);
11461
11462                    // Position the selection in the rename editor so that it matches the current selection.
11463                    this.show_local_selections = false;
11464                    let rename_editor = cx.new(|cx| {
11465                        let mut editor = Editor::single_line(window, cx);
11466                        editor.buffer.update(cx, |buffer, cx| {
11467                            buffer.edit([(0..0, old_name.clone())], None, cx)
11468                        });
11469                        let rename_selection_range = match cursor_offset_in_rename_range
11470                            .cmp(&cursor_offset_in_rename_range_end)
11471                        {
11472                            Ordering::Equal => {
11473                                editor.select_all(&SelectAll, window, cx);
11474                                return editor;
11475                            }
11476                            Ordering::Less => {
11477                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11478                            }
11479                            Ordering::Greater => {
11480                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11481                            }
11482                        };
11483                        if rename_selection_range.end > old_name.len() {
11484                            editor.select_all(&SelectAll, window, cx);
11485                        } else {
11486                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11487                                s.select_ranges([rename_selection_range]);
11488                            });
11489                        }
11490                        editor
11491                    });
11492                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11493                        if e == &EditorEvent::Focused {
11494                            cx.emit(EditorEvent::FocusedIn)
11495                        }
11496                    })
11497                    .detach();
11498
11499                    let write_highlights =
11500                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11501                    let read_highlights =
11502                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11503                    let ranges = write_highlights
11504                        .iter()
11505                        .flat_map(|(_, ranges)| ranges.iter())
11506                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11507                        .cloned()
11508                        .collect();
11509
11510                    this.highlight_text::<Rename>(
11511                        ranges,
11512                        HighlightStyle {
11513                            fade_out: Some(0.6),
11514                            ..Default::default()
11515                        },
11516                        cx,
11517                    );
11518                    let rename_focus_handle = rename_editor.focus_handle(cx);
11519                    window.focus(&rename_focus_handle);
11520                    let block_id = this.insert_blocks(
11521                        [BlockProperties {
11522                            style: BlockStyle::Flex,
11523                            placement: BlockPlacement::Below(range.start),
11524                            height: 1,
11525                            render: Arc::new({
11526                                let rename_editor = rename_editor.clone();
11527                                move |cx: &mut BlockContext| {
11528                                    let mut text_style = cx.editor_style.text.clone();
11529                                    if let Some(highlight_style) = old_highlight_id
11530                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11531                                    {
11532                                        text_style = text_style.highlight(highlight_style);
11533                                    }
11534                                    div()
11535                                        .block_mouse_down()
11536                                        .pl(cx.anchor_x)
11537                                        .child(EditorElement::new(
11538                                            &rename_editor,
11539                                            EditorStyle {
11540                                                background: cx.theme().system().transparent,
11541                                                local_player: cx.editor_style.local_player,
11542                                                text: text_style,
11543                                                scrollbar_width: cx.editor_style.scrollbar_width,
11544                                                syntax: cx.editor_style.syntax.clone(),
11545                                                status: cx.editor_style.status.clone(),
11546                                                inlay_hints_style: HighlightStyle {
11547                                                    font_weight: Some(FontWeight::BOLD),
11548                                                    ..make_inlay_hints_style(cx.app)
11549                                                },
11550                                                inline_completion_styles: make_suggestion_styles(
11551                                                    cx.app,
11552                                                ),
11553                                                ..EditorStyle::default()
11554                                            },
11555                                        ))
11556                                        .into_any_element()
11557                                }
11558                            }),
11559                            priority: 0,
11560                        }],
11561                        Some(Autoscroll::fit()),
11562                        cx,
11563                    )[0];
11564                    this.pending_rename = Some(RenameState {
11565                        range,
11566                        old_name,
11567                        editor: rename_editor,
11568                        block_id,
11569                    });
11570                })?;
11571            }
11572
11573            Ok(())
11574        }))
11575    }
11576
11577    pub fn confirm_rename(
11578        &mut self,
11579        _: &ConfirmRename,
11580        window: &mut Window,
11581        cx: &mut Context<Self>,
11582    ) -> Option<Task<Result<()>>> {
11583        let rename = self.take_rename(false, window, cx)?;
11584        let workspace = self.workspace()?.downgrade();
11585        let (buffer, start) = self
11586            .buffer
11587            .read(cx)
11588            .text_anchor_for_position(rename.range.start, cx)?;
11589        let (end_buffer, _) = self
11590            .buffer
11591            .read(cx)
11592            .text_anchor_for_position(rename.range.end, cx)?;
11593        if buffer != end_buffer {
11594            return None;
11595        }
11596
11597        let old_name = rename.old_name;
11598        let new_name = rename.editor.read(cx).text(cx);
11599
11600        let rename = self.semantics_provider.as_ref()?.perform_rename(
11601            &buffer,
11602            start,
11603            new_name.clone(),
11604            cx,
11605        )?;
11606
11607        Some(cx.spawn_in(window, |editor, mut cx| async move {
11608            let project_transaction = rename.await?;
11609            Self::open_project_transaction(
11610                &editor,
11611                workspace,
11612                project_transaction,
11613                format!("Rename: {}{}", old_name, new_name),
11614                cx.clone(),
11615            )
11616            .await?;
11617
11618            editor.update(&mut cx, |editor, cx| {
11619                editor.refresh_document_highlights(cx);
11620            })?;
11621            Ok(())
11622        }))
11623    }
11624
11625    fn take_rename(
11626        &mut self,
11627        moving_cursor: bool,
11628        window: &mut Window,
11629        cx: &mut Context<Self>,
11630    ) -> Option<RenameState> {
11631        let rename = self.pending_rename.take()?;
11632        if rename.editor.focus_handle(cx).is_focused(window) {
11633            window.focus(&self.focus_handle);
11634        }
11635
11636        self.remove_blocks(
11637            [rename.block_id].into_iter().collect(),
11638            Some(Autoscroll::fit()),
11639            cx,
11640        );
11641        self.clear_highlights::<Rename>(cx);
11642        self.show_local_selections = true;
11643
11644        if moving_cursor {
11645            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11646                editor.selections.newest::<usize>(cx).head()
11647            });
11648
11649            // Update the selection to match the position of the selection inside
11650            // the rename editor.
11651            let snapshot = self.buffer.read(cx).read(cx);
11652            let rename_range = rename.range.to_offset(&snapshot);
11653            let cursor_in_editor = snapshot
11654                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11655                .min(rename_range.end);
11656            drop(snapshot);
11657
11658            self.change_selections(None, window, cx, |s| {
11659                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11660            });
11661        } else {
11662            self.refresh_document_highlights(cx);
11663        }
11664
11665        Some(rename)
11666    }
11667
11668    pub fn pending_rename(&self) -> Option<&RenameState> {
11669        self.pending_rename.as_ref()
11670    }
11671
11672    fn format(
11673        &mut self,
11674        _: &Format,
11675        window: &mut Window,
11676        cx: &mut Context<Self>,
11677    ) -> Option<Task<Result<()>>> {
11678        let project = match &self.project {
11679            Some(project) => project.clone(),
11680            None => return None,
11681        };
11682
11683        Some(self.perform_format(
11684            project,
11685            FormatTrigger::Manual,
11686            FormatTarget::Buffers,
11687            window,
11688            cx,
11689        ))
11690    }
11691
11692    fn format_selections(
11693        &mut self,
11694        _: &FormatSelections,
11695        window: &mut Window,
11696        cx: &mut Context<Self>,
11697    ) -> Option<Task<Result<()>>> {
11698        let project = match &self.project {
11699            Some(project) => project.clone(),
11700            None => return None,
11701        };
11702
11703        let ranges = self
11704            .selections
11705            .all_adjusted(cx)
11706            .into_iter()
11707            .map(|selection| selection.range())
11708            .collect_vec();
11709
11710        Some(self.perform_format(
11711            project,
11712            FormatTrigger::Manual,
11713            FormatTarget::Ranges(ranges),
11714            window,
11715            cx,
11716        ))
11717    }
11718
11719    fn perform_format(
11720        &mut self,
11721        project: Entity<Project>,
11722        trigger: FormatTrigger,
11723        target: FormatTarget,
11724        window: &mut Window,
11725        cx: &mut Context<Self>,
11726    ) -> Task<Result<()>> {
11727        let buffer = self.buffer.clone();
11728        let (buffers, target) = match target {
11729            FormatTarget::Buffers => {
11730                let mut buffers = buffer.read(cx).all_buffers();
11731                if trigger == FormatTrigger::Save {
11732                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11733                }
11734                (buffers, LspFormatTarget::Buffers)
11735            }
11736            FormatTarget::Ranges(selection_ranges) => {
11737                let multi_buffer = buffer.read(cx);
11738                let snapshot = multi_buffer.read(cx);
11739                let mut buffers = HashSet::default();
11740                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11741                    BTreeMap::new();
11742                for selection_range in selection_ranges {
11743                    for (buffer, buffer_range, _) in
11744                        snapshot.range_to_buffer_ranges(selection_range)
11745                    {
11746                        let buffer_id = buffer.remote_id();
11747                        let start = buffer.anchor_before(buffer_range.start);
11748                        let end = buffer.anchor_after(buffer_range.end);
11749                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11750                        buffer_id_to_ranges
11751                            .entry(buffer_id)
11752                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11753                            .or_insert_with(|| vec![start..end]);
11754                    }
11755                }
11756                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11757            }
11758        };
11759
11760        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11761        let format = project.update(cx, |project, cx| {
11762            project.format(buffers, target, true, trigger, cx)
11763        });
11764
11765        cx.spawn_in(window, |_, mut cx| async move {
11766            let transaction = futures::select_biased! {
11767                () = timeout => {
11768                    log::warn!("timed out waiting for formatting");
11769                    None
11770                }
11771                transaction = format.log_err().fuse() => transaction,
11772            };
11773
11774            buffer
11775                .update(&mut cx, |buffer, cx| {
11776                    if let Some(transaction) = transaction {
11777                        if !buffer.is_singleton() {
11778                            buffer.push_transaction(&transaction.0, cx);
11779                        }
11780                    }
11781
11782                    cx.notify();
11783                })
11784                .ok();
11785
11786            Ok(())
11787        })
11788    }
11789
11790    fn restart_language_server(
11791        &mut self,
11792        _: &RestartLanguageServer,
11793        _: &mut Window,
11794        cx: &mut Context<Self>,
11795    ) {
11796        if let Some(project) = self.project.clone() {
11797            self.buffer.update(cx, |multi_buffer, cx| {
11798                project.update(cx, |project, cx| {
11799                    project.restart_language_servers_for_buffers(
11800                        multi_buffer.all_buffers().into_iter().collect(),
11801                        cx,
11802                    );
11803                });
11804            })
11805        }
11806    }
11807
11808    fn cancel_language_server_work(
11809        workspace: &mut Workspace,
11810        _: &actions::CancelLanguageServerWork,
11811        _: &mut Window,
11812        cx: &mut Context<Workspace>,
11813    ) {
11814        let project = workspace.project();
11815        let buffers = workspace
11816            .active_item(cx)
11817            .and_then(|item| item.act_as::<Editor>(cx))
11818            .map_or(HashSet::default(), |editor| {
11819                editor.read(cx).buffer.read(cx).all_buffers()
11820            });
11821        project.update(cx, |project, cx| {
11822            project.cancel_language_server_work_for_buffers(buffers, cx);
11823        });
11824    }
11825
11826    fn show_character_palette(
11827        &mut self,
11828        _: &ShowCharacterPalette,
11829        window: &mut Window,
11830        _: &mut Context<Self>,
11831    ) {
11832        window.show_character_palette();
11833    }
11834
11835    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11836        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11837            let buffer = self.buffer.read(cx).snapshot(cx);
11838            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11839            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11840            let is_valid = buffer
11841                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11842                .any(|entry| {
11843                    entry.diagnostic.is_primary
11844                        && !entry.range.is_empty()
11845                        && entry.range.start == primary_range_start
11846                        && entry.diagnostic.message == active_diagnostics.primary_message
11847                });
11848
11849            if is_valid != active_diagnostics.is_valid {
11850                active_diagnostics.is_valid = is_valid;
11851                let mut new_styles = HashMap::default();
11852                for (block_id, diagnostic) in &active_diagnostics.blocks {
11853                    new_styles.insert(
11854                        *block_id,
11855                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11856                    );
11857                }
11858                self.display_map.update(cx, |display_map, _cx| {
11859                    display_map.replace_blocks(new_styles)
11860                });
11861            }
11862        }
11863    }
11864
11865    fn activate_diagnostics(
11866        &mut self,
11867        buffer_id: BufferId,
11868        group_id: usize,
11869        window: &mut Window,
11870        cx: &mut Context<Self>,
11871    ) {
11872        self.dismiss_diagnostics(cx);
11873        let snapshot = self.snapshot(window, cx);
11874        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11875            let buffer = self.buffer.read(cx).snapshot(cx);
11876
11877            let mut primary_range = None;
11878            let mut primary_message = None;
11879            let diagnostic_group = buffer
11880                .diagnostic_group(buffer_id, group_id)
11881                .filter_map(|entry| {
11882                    let start = entry.range.start;
11883                    let end = entry.range.end;
11884                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11885                        && (start.row == end.row
11886                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11887                    {
11888                        return None;
11889                    }
11890                    if entry.diagnostic.is_primary {
11891                        primary_range = Some(entry.range.clone());
11892                        primary_message = Some(entry.diagnostic.message.clone());
11893                    }
11894                    Some(entry)
11895                })
11896                .collect::<Vec<_>>();
11897            let primary_range = primary_range?;
11898            let primary_message = primary_message?;
11899
11900            let blocks = display_map
11901                .insert_blocks(
11902                    diagnostic_group.iter().map(|entry| {
11903                        let diagnostic = entry.diagnostic.clone();
11904                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11905                        BlockProperties {
11906                            style: BlockStyle::Fixed,
11907                            placement: BlockPlacement::Below(
11908                                buffer.anchor_after(entry.range.start),
11909                            ),
11910                            height: message_height,
11911                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11912                            priority: 0,
11913                        }
11914                    }),
11915                    cx,
11916                )
11917                .into_iter()
11918                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11919                .collect();
11920
11921            Some(ActiveDiagnosticGroup {
11922                primary_range: buffer.anchor_before(primary_range.start)
11923                    ..buffer.anchor_after(primary_range.end),
11924                primary_message,
11925                group_id,
11926                blocks,
11927                is_valid: true,
11928            })
11929        });
11930    }
11931
11932    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11933        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11934            self.display_map.update(cx, |display_map, cx| {
11935                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11936            });
11937            cx.notify();
11938        }
11939    }
11940
11941    pub fn set_selections_from_remote(
11942        &mut self,
11943        selections: Vec<Selection<Anchor>>,
11944        pending_selection: Option<Selection<Anchor>>,
11945        window: &mut Window,
11946        cx: &mut Context<Self>,
11947    ) {
11948        let old_cursor_position = self.selections.newest_anchor().head();
11949        self.selections.change_with(cx, |s| {
11950            s.select_anchors(selections);
11951            if let Some(pending_selection) = pending_selection {
11952                s.set_pending(pending_selection, SelectMode::Character);
11953            } else {
11954                s.clear_pending();
11955            }
11956        });
11957        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11958    }
11959
11960    fn push_to_selection_history(&mut self) {
11961        self.selection_history.push(SelectionHistoryEntry {
11962            selections: self.selections.disjoint_anchors(),
11963            select_next_state: self.select_next_state.clone(),
11964            select_prev_state: self.select_prev_state.clone(),
11965            add_selections_state: self.add_selections_state.clone(),
11966        });
11967    }
11968
11969    pub fn transact(
11970        &mut self,
11971        window: &mut Window,
11972        cx: &mut Context<Self>,
11973        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11974    ) -> Option<TransactionId> {
11975        self.start_transaction_at(Instant::now(), window, cx);
11976        update(self, window, cx);
11977        self.end_transaction_at(Instant::now(), cx)
11978    }
11979
11980    pub fn start_transaction_at(
11981        &mut self,
11982        now: Instant,
11983        window: &mut Window,
11984        cx: &mut Context<Self>,
11985    ) {
11986        self.end_selection(window, cx);
11987        if let Some(tx_id) = self
11988            .buffer
11989            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11990        {
11991            self.selection_history
11992                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11993            cx.emit(EditorEvent::TransactionBegun {
11994                transaction_id: tx_id,
11995            })
11996        }
11997    }
11998
11999    pub fn end_transaction_at(
12000        &mut self,
12001        now: Instant,
12002        cx: &mut Context<Self>,
12003    ) -> Option<TransactionId> {
12004        if let Some(transaction_id) = self
12005            .buffer
12006            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
12007        {
12008            if let Some((_, end_selections)) =
12009                self.selection_history.transaction_mut(transaction_id)
12010            {
12011                *end_selections = Some(self.selections.disjoint_anchors());
12012            } else {
12013                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
12014            }
12015
12016            cx.emit(EditorEvent::Edited { transaction_id });
12017            Some(transaction_id)
12018        } else {
12019            None
12020        }
12021    }
12022
12023    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
12024        if self.selection_mark_mode {
12025            self.change_selections(None, window, cx, |s| {
12026                s.move_with(|_, sel| {
12027                    sel.collapse_to(sel.head(), SelectionGoal::None);
12028                });
12029            })
12030        }
12031        self.selection_mark_mode = true;
12032        cx.notify();
12033    }
12034
12035    pub fn swap_selection_ends(
12036        &mut self,
12037        _: &actions::SwapSelectionEnds,
12038        window: &mut Window,
12039        cx: &mut Context<Self>,
12040    ) {
12041        self.change_selections(None, window, cx, |s| {
12042            s.move_with(|_, sel| {
12043                if sel.start != sel.end {
12044                    sel.reversed = !sel.reversed
12045                }
12046            });
12047        });
12048        self.request_autoscroll(Autoscroll::newest(), cx);
12049        cx.notify();
12050    }
12051
12052    pub fn toggle_fold(
12053        &mut self,
12054        _: &actions::ToggleFold,
12055        window: &mut Window,
12056        cx: &mut Context<Self>,
12057    ) {
12058        if self.is_singleton(cx) {
12059            let selection = self.selections.newest::<Point>(cx);
12060
12061            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12062            let range = if selection.is_empty() {
12063                let point = selection.head().to_display_point(&display_map);
12064                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12065                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12066                    .to_point(&display_map);
12067                start..end
12068            } else {
12069                selection.range()
12070            };
12071            if display_map.folds_in_range(range).next().is_some() {
12072                self.unfold_lines(&Default::default(), window, cx)
12073            } else {
12074                self.fold(&Default::default(), window, cx)
12075            }
12076        } else {
12077            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12078            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12079                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12080                .map(|(snapshot, _, _)| snapshot.remote_id())
12081                .collect();
12082
12083            for buffer_id in buffer_ids {
12084                if self.is_buffer_folded(buffer_id, cx) {
12085                    self.unfold_buffer(buffer_id, cx);
12086                } else {
12087                    self.fold_buffer(buffer_id, cx);
12088                }
12089            }
12090        }
12091    }
12092
12093    pub fn toggle_fold_recursive(
12094        &mut self,
12095        _: &actions::ToggleFoldRecursive,
12096        window: &mut Window,
12097        cx: &mut Context<Self>,
12098    ) {
12099        let selection = self.selections.newest::<Point>(cx);
12100
12101        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12102        let range = if selection.is_empty() {
12103            let point = selection.head().to_display_point(&display_map);
12104            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
12105            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
12106                .to_point(&display_map);
12107            start..end
12108        } else {
12109            selection.range()
12110        };
12111        if display_map.folds_in_range(range).next().is_some() {
12112            self.unfold_recursive(&Default::default(), window, cx)
12113        } else {
12114            self.fold_recursive(&Default::default(), window, cx)
12115        }
12116    }
12117
12118    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
12119        if self.is_singleton(cx) {
12120            let mut to_fold = Vec::new();
12121            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12122            let selections = self.selections.all_adjusted(cx);
12123
12124            for selection in selections {
12125                let range = selection.range().sorted();
12126                let buffer_start_row = range.start.row;
12127
12128                if range.start.row != range.end.row {
12129                    let mut found = false;
12130                    let mut row = range.start.row;
12131                    while row <= range.end.row {
12132                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
12133                        {
12134                            found = true;
12135                            row = crease.range().end.row + 1;
12136                            to_fold.push(crease);
12137                        } else {
12138                            row += 1
12139                        }
12140                    }
12141                    if found {
12142                        continue;
12143                    }
12144                }
12145
12146                for row in (0..=range.start.row).rev() {
12147                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12148                        if crease.range().end.row >= buffer_start_row {
12149                            to_fold.push(crease);
12150                            if row <= range.start.row {
12151                                break;
12152                            }
12153                        }
12154                    }
12155                }
12156            }
12157
12158            self.fold_creases(to_fold, true, window, cx);
12159        } else {
12160            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12161
12162            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12163                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12164                .map(|(snapshot, _, _)| snapshot.remote_id())
12165                .collect();
12166            for buffer_id in buffer_ids {
12167                self.fold_buffer(buffer_id, cx);
12168            }
12169        }
12170    }
12171
12172    fn fold_at_level(
12173        &mut self,
12174        fold_at: &FoldAtLevel,
12175        window: &mut Window,
12176        cx: &mut Context<Self>,
12177    ) {
12178        if !self.buffer.read(cx).is_singleton() {
12179            return;
12180        }
12181
12182        let fold_at_level = fold_at.0;
12183        let snapshot = self.buffer.read(cx).snapshot(cx);
12184        let mut to_fold = Vec::new();
12185        let mut stack = vec![(0, snapshot.max_row().0, 1)];
12186
12187        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
12188            while start_row < end_row {
12189                match self
12190                    .snapshot(window, cx)
12191                    .crease_for_buffer_row(MultiBufferRow(start_row))
12192                {
12193                    Some(crease) => {
12194                        let nested_start_row = crease.range().start.row + 1;
12195                        let nested_end_row = crease.range().end.row;
12196
12197                        if current_level < fold_at_level {
12198                            stack.push((nested_start_row, nested_end_row, current_level + 1));
12199                        } else if current_level == fold_at_level {
12200                            to_fold.push(crease);
12201                        }
12202
12203                        start_row = nested_end_row + 1;
12204                    }
12205                    None => start_row += 1,
12206                }
12207            }
12208        }
12209
12210        self.fold_creases(to_fold, true, window, cx);
12211    }
12212
12213    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
12214        if self.buffer.read(cx).is_singleton() {
12215            let mut fold_ranges = Vec::new();
12216            let snapshot = self.buffer.read(cx).snapshot(cx);
12217
12218            for row in 0..snapshot.max_row().0 {
12219                if let Some(foldable_range) = self
12220                    .snapshot(window, cx)
12221                    .crease_for_buffer_row(MultiBufferRow(row))
12222                {
12223                    fold_ranges.push(foldable_range);
12224                }
12225            }
12226
12227            self.fold_creases(fold_ranges, true, window, cx);
12228        } else {
12229            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
12230                editor
12231                    .update_in(&mut cx, |editor, _, cx| {
12232                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12233                            editor.fold_buffer(buffer_id, cx);
12234                        }
12235                    })
12236                    .ok();
12237            });
12238        }
12239    }
12240
12241    pub fn fold_function_bodies(
12242        &mut self,
12243        _: &actions::FoldFunctionBodies,
12244        window: &mut Window,
12245        cx: &mut Context<Self>,
12246    ) {
12247        let snapshot = self.buffer.read(cx).snapshot(cx);
12248
12249        let ranges = snapshot
12250            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
12251            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
12252            .collect::<Vec<_>>();
12253
12254        let creases = ranges
12255            .into_iter()
12256            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
12257            .collect();
12258
12259        self.fold_creases(creases, true, window, cx);
12260    }
12261
12262    pub fn fold_recursive(
12263        &mut self,
12264        _: &actions::FoldRecursive,
12265        window: &mut Window,
12266        cx: &mut Context<Self>,
12267    ) {
12268        let mut to_fold = Vec::new();
12269        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12270        let selections = self.selections.all_adjusted(cx);
12271
12272        for selection in selections {
12273            let range = selection.range().sorted();
12274            let buffer_start_row = range.start.row;
12275
12276            if range.start.row != range.end.row {
12277                let mut found = false;
12278                for row in range.start.row..=range.end.row {
12279                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12280                        found = true;
12281                        to_fold.push(crease);
12282                    }
12283                }
12284                if found {
12285                    continue;
12286                }
12287            }
12288
12289            for row in (0..=range.start.row).rev() {
12290                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
12291                    if crease.range().end.row >= buffer_start_row {
12292                        to_fold.push(crease);
12293                    } else {
12294                        break;
12295                    }
12296                }
12297            }
12298        }
12299
12300        self.fold_creases(to_fold, true, window, cx);
12301    }
12302
12303    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
12304        let buffer_row = fold_at.buffer_row;
12305        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12306
12307        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
12308            let autoscroll = self
12309                .selections
12310                .all::<Point>(cx)
12311                .iter()
12312                .any(|selection| crease.range().overlaps(&selection.range()));
12313
12314            self.fold_creases(vec![crease], autoscroll, window, cx);
12315        }
12316    }
12317
12318    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
12319        if self.is_singleton(cx) {
12320            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12321            let buffer = &display_map.buffer_snapshot;
12322            let selections = self.selections.all::<Point>(cx);
12323            let ranges = selections
12324                .iter()
12325                .map(|s| {
12326                    let range = s.display_range(&display_map).sorted();
12327                    let mut start = range.start.to_point(&display_map);
12328                    let mut end = range.end.to_point(&display_map);
12329                    start.column = 0;
12330                    end.column = buffer.line_len(MultiBufferRow(end.row));
12331                    start..end
12332                })
12333                .collect::<Vec<_>>();
12334
12335            self.unfold_ranges(&ranges, true, true, cx);
12336        } else {
12337            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12338            let buffer_ids: HashSet<_> = multi_buffer_snapshot
12339                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
12340                .map(|(snapshot, _, _)| snapshot.remote_id())
12341                .collect();
12342            for buffer_id in buffer_ids {
12343                self.unfold_buffer(buffer_id, cx);
12344            }
12345        }
12346    }
12347
12348    pub fn unfold_recursive(
12349        &mut self,
12350        _: &UnfoldRecursive,
12351        _window: &mut Window,
12352        cx: &mut Context<Self>,
12353    ) {
12354        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12355        let selections = self.selections.all::<Point>(cx);
12356        let ranges = selections
12357            .iter()
12358            .map(|s| {
12359                let mut range = s.display_range(&display_map).sorted();
12360                *range.start.column_mut() = 0;
12361                *range.end.column_mut() = display_map.line_len(range.end.row());
12362                let start = range.start.to_point(&display_map);
12363                let end = range.end.to_point(&display_map);
12364                start..end
12365            })
12366            .collect::<Vec<_>>();
12367
12368        self.unfold_ranges(&ranges, true, true, cx);
12369    }
12370
12371    pub fn unfold_at(
12372        &mut self,
12373        unfold_at: &UnfoldAt,
12374        _window: &mut Window,
12375        cx: &mut Context<Self>,
12376    ) {
12377        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12378
12379        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
12380            ..Point::new(
12381                unfold_at.buffer_row.0,
12382                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
12383            );
12384
12385        let autoscroll = self
12386            .selections
12387            .all::<Point>(cx)
12388            .iter()
12389            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
12390
12391        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
12392    }
12393
12394    pub fn unfold_all(
12395        &mut self,
12396        _: &actions::UnfoldAll,
12397        _window: &mut Window,
12398        cx: &mut Context<Self>,
12399    ) {
12400        if self.buffer.read(cx).is_singleton() {
12401            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12402            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
12403        } else {
12404            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
12405                editor
12406                    .update(&mut cx, |editor, cx| {
12407                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
12408                            editor.unfold_buffer(buffer_id, cx);
12409                        }
12410                    })
12411                    .ok();
12412            });
12413        }
12414    }
12415
12416    pub fn fold_selected_ranges(
12417        &mut self,
12418        _: &FoldSelectedRanges,
12419        window: &mut Window,
12420        cx: &mut Context<Self>,
12421    ) {
12422        let selections = self.selections.all::<Point>(cx);
12423        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12424        let line_mode = self.selections.line_mode;
12425        let ranges = selections
12426            .into_iter()
12427            .map(|s| {
12428                if line_mode {
12429                    let start = Point::new(s.start.row, 0);
12430                    let end = Point::new(
12431                        s.end.row,
12432                        display_map
12433                            .buffer_snapshot
12434                            .line_len(MultiBufferRow(s.end.row)),
12435                    );
12436                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12437                } else {
12438                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12439                }
12440            })
12441            .collect::<Vec<_>>();
12442        self.fold_creases(ranges, true, window, cx);
12443    }
12444
12445    pub fn fold_ranges<T: ToOffset + Clone>(
12446        &mut self,
12447        ranges: Vec<Range<T>>,
12448        auto_scroll: bool,
12449        window: &mut Window,
12450        cx: &mut Context<Self>,
12451    ) {
12452        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12453        let ranges = ranges
12454            .into_iter()
12455            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12456            .collect::<Vec<_>>();
12457        self.fold_creases(ranges, auto_scroll, window, cx);
12458    }
12459
12460    pub fn fold_creases<T: ToOffset + Clone>(
12461        &mut self,
12462        creases: Vec<Crease<T>>,
12463        auto_scroll: bool,
12464        window: &mut Window,
12465        cx: &mut Context<Self>,
12466    ) {
12467        if creases.is_empty() {
12468            return;
12469        }
12470
12471        let mut buffers_affected = HashSet::default();
12472        let multi_buffer = self.buffer().read(cx);
12473        for crease in &creases {
12474            if let Some((_, buffer, _)) =
12475                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12476            {
12477                buffers_affected.insert(buffer.read(cx).remote_id());
12478            };
12479        }
12480
12481        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12482
12483        if auto_scroll {
12484            self.request_autoscroll(Autoscroll::fit(), cx);
12485        }
12486
12487        cx.notify();
12488
12489        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12490            // Clear diagnostics block when folding a range that contains it.
12491            let snapshot = self.snapshot(window, cx);
12492            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12493                drop(snapshot);
12494                self.active_diagnostics = Some(active_diagnostics);
12495                self.dismiss_diagnostics(cx);
12496            } else {
12497                self.active_diagnostics = Some(active_diagnostics);
12498            }
12499        }
12500
12501        self.scrollbar_marker_state.dirty = true;
12502    }
12503
12504    /// Removes any folds whose ranges intersect any of the given ranges.
12505    pub fn unfold_ranges<T: ToOffset + Clone>(
12506        &mut self,
12507        ranges: &[Range<T>],
12508        inclusive: bool,
12509        auto_scroll: bool,
12510        cx: &mut Context<Self>,
12511    ) {
12512        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12513            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12514        });
12515    }
12516
12517    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12518        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12519            return;
12520        }
12521        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12522        self.display_map
12523            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12524        cx.emit(EditorEvent::BufferFoldToggled {
12525            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12526            folded: true,
12527        });
12528        cx.notify();
12529    }
12530
12531    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12532        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12533            return;
12534        }
12535        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12536        self.display_map.update(cx, |display_map, cx| {
12537            display_map.unfold_buffer(buffer_id, cx);
12538        });
12539        cx.emit(EditorEvent::BufferFoldToggled {
12540            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12541            folded: false,
12542        });
12543        cx.notify();
12544    }
12545
12546    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12547        self.display_map.read(cx).is_buffer_folded(buffer)
12548    }
12549
12550    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12551        self.display_map.read(cx).folded_buffers()
12552    }
12553
12554    /// Removes any folds with the given ranges.
12555    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12556        &mut self,
12557        ranges: &[Range<T>],
12558        type_id: TypeId,
12559        auto_scroll: bool,
12560        cx: &mut Context<Self>,
12561    ) {
12562        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12563            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12564        });
12565    }
12566
12567    fn remove_folds_with<T: ToOffset + Clone>(
12568        &mut self,
12569        ranges: &[Range<T>],
12570        auto_scroll: bool,
12571        cx: &mut Context<Self>,
12572        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12573    ) {
12574        if ranges.is_empty() {
12575            return;
12576        }
12577
12578        let mut buffers_affected = HashSet::default();
12579        let multi_buffer = self.buffer().read(cx);
12580        for range in ranges {
12581            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12582                buffers_affected.insert(buffer.read(cx).remote_id());
12583            };
12584        }
12585
12586        self.display_map.update(cx, update);
12587
12588        if auto_scroll {
12589            self.request_autoscroll(Autoscroll::fit(), cx);
12590        }
12591
12592        cx.notify();
12593        self.scrollbar_marker_state.dirty = true;
12594        self.active_indent_guides_state.dirty = true;
12595    }
12596
12597    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12598        self.display_map.read(cx).fold_placeholder.clone()
12599    }
12600
12601    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12602        self.buffer.update(cx, |buffer, cx| {
12603            buffer.set_all_diff_hunks_expanded(cx);
12604        });
12605    }
12606
12607    pub fn set_distinguish_unstaged_diff_hunks(&mut self) {
12608        self.distinguish_unstaged_diff_hunks = true;
12609    }
12610
12611    pub fn expand_all_diff_hunks(
12612        &mut self,
12613        _: &ExpandAllHunkDiffs,
12614        _window: &mut Window,
12615        cx: &mut Context<Self>,
12616    ) {
12617        self.buffer.update(cx, |buffer, cx| {
12618            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12619        });
12620    }
12621
12622    pub fn toggle_selected_diff_hunks(
12623        &mut self,
12624        _: &ToggleSelectedDiffHunks,
12625        _window: &mut Window,
12626        cx: &mut Context<Self>,
12627    ) {
12628        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12629        self.toggle_diff_hunks_in_ranges(ranges, cx);
12630    }
12631
12632    fn diff_hunks_in_ranges<'a>(
12633        &'a self,
12634        ranges: &'a [Range<Anchor>],
12635        buffer: &'a MultiBufferSnapshot,
12636    ) -> impl 'a + Iterator<Item = MultiBufferDiffHunk> {
12637        ranges.iter().flat_map(move |range| {
12638            let end_excerpt_id = range.end.excerpt_id;
12639            let range = range.to_point(buffer);
12640            let mut peek_end = range.end;
12641            if range.end.row < buffer.max_row().0 {
12642                peek_end = Point::new(range.end.row + 1, 0);
12643            }
12644            buffer
12645                .diff_hunks_in_range(range.start..peek_end)
12646                .filter(move |hunk| hunk.excerpt_id.cmp(&end_excerpt_id, buffer).is_le())
12647        })
12648    }
12649
12650    pub fn has_stageable_diff_hunks_in_ranges(
12651        &self,
12652        ranges: &[Range<Anchor>],
12653        snapshot: &MultiBufferSnapshot,
12654    ) -> bool {
12655        let mut hunks = self.diff_hunks_in_ranges(ranges, &snapshot);
12656        hunks.any(|hunk| hunk.secondary_status == DiffHunkSecondaryStatus::HasSecondaryHunk)
12657    }
12658
12659    pub fn toggle_staged_selected_diff_hunks(
12660        &mut self,
12661        _: &ToggleStagedSelectedDiffHunks,
12662        _window: &mut Window,
12663        cx: &mut Context<Self>,
12664    ) {
12665        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12666        self.stage_or_unstage_diff_hunks(&ranges, cx);
12667    }
12668
12669    pub fn stage_or_unstage_diff_hunks(
12670        &mut self,
12671        ranges: &[Range<Anchor>],
12672        cx: &mut Context<Self>,
12673    ) {
12674        let Some(project) = &self.project else {
12675            return;
12676        };
12677        let snapshot = self.buffer.read(cx).snapshot(cx);
12678        let stage = self.has_stageable_diff_hunks_in_ranges(ranges, &snapshot);
12679
12680        let chunk_by = self
12681            .diff_hunks_in_ranges(&ranges, &snapshot)
12682            .chunk_by(|hunk| hunk.buffer_id);
12683        for (buffer_id, hunks) in &chunk_by {
12684            let Some(buffer) = project.read(cx).buffer_for_id(buffer_id, cx) else {
12685                log::debug!("no buffer for id");
12686                continue;
12687            };
12688            let buffer = buffer.read(cx).snapshot();
12689            let Some((repo, path)) = project
12690                .read(cx)
12691                .repository_and_path_for_buffer_id(buffer_id, cx)
12692            else {
12693                log::debug!("no git repo for buffer id");
12694                continue;
12695            };
12696            let Some(diff) = snapshot.diff_for_buffer_id(buffer_id) else {
12697                log::debug!("no diff for buffer id");
12698                continue;
12699            };
12700            let Some(secondary_diff) = diff.secondary_diff() else {
12701                log::debug!("no secondary diff for buffer id");
12702                continue;
12703            };
12704
12705            let edits = diff.secondary_edits_for_stage_or_unstage(
12706                stage,
12707                hunks.map(|hunk| {
12708                    (
12709                        hunk.diff_base_byte_range.clone(),
12710                        hunk.secondary_diff_base_byte_range.clone(),
12711                        hunk.buffer_range.clone(),
12712                    )
12713                }),
12714                &buffer,
12715            );
12716
12717            let index_base = secondary_diff.base_text().map_or_else(
12718                || Rope::from(""),
12719                |snapshot| snapshot.text.as_rope().clone(),
12720            );
12721            let index_buffer = cx.new(|cx| {
12722                Buffer::local_normalized(index_base.clone(), text::LineEnding::default(), cx)
12723            });
12724            let new_index_text = index_buffer.update(cx, |index_buffer, cx| {
12725                index_buffer.edit(edits, None, cx);
12726                index_buffer.snapshot().as_rope().to_string()
12727            });
12728            let new_index_text = if new_index_text.is_empty()
12729                && (diff.is_single_insertion
12730                    || buffer
12731                        .file()
12732                        .map_or(false, |file| file.disk_state() == DiskState::New))
12733            {
12734                log::debug!("removing from index");
12735                None
12736            } else {
12737                Some(new_index_text)
12738            };
12739
12740            let _ = repo.read(cx).set_index_text(&path, new_index_text);
12741        }
12742    }
12743
12744    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12745        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12746        self.buffer
12747            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12748    }
12749
12750    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12751        self.buffer.update(cx, |buffer, cx| {
12752            let ranges = vec![Anchor::min()..Anchor::max()];
12753            if !buffer.all_diff_hunks_expanded()
12754                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12755            {
12756                buffer.collapse_diff_hunks(ranges, cx);
12757                true
12758            } else {
12759                false
12760            }
12761        })
12762    }
12763
12764    fn toggle_diff_hunks_in_ranges(
12765        &mut self,
12766        ranges: Vec<Range<Anchor>>,
12767        cx: &mut Context<'_, Editor>,
12768    ) {
12769        self.buffer.update(cx, |buffer, cx| {
12770            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12771            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12772        })
12773    }
12774
12775    fn toggle_diff_hunks_in_ranges_narrow(
12776        &mut self,
12777        ranges: Vec<Range<Anchor>>,
12778        cx: &mut Context<'_, Editor>,
12779    ) {
12780        self.buffer.update(cx, |buffer, cx| {
12781            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12782            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12783        })
12784    }
12785
12786    pub(crate) fn apply_all_diff_hunks(
12787        &mut self,
12788        _: &ApplyAllDiffHunks,
12789        window: &mut Window,
12790        cx: &mut Context<Self>,
12791    ) {
12792        let buffers = self.buffer.read(cx).all_buffers();
12793        for branch_buffer in buffers {
12794            branch_buffer.update(cx, |branch_buffer, cx| {
12795                branch_buffer.merge_into_base(Vec::new(), cx);
12796            });
12797        }
12798
12799        if let Some(project) = self.project.clone() {
12800            self.save(true, project, window, cx).detach_and_log_err(cx);
12801        }
12802    }
12803
12804    pub(crate) fn apply_selected_diff_hunks(
12805        &mut self,
12806        _: &ApplyDiffHunk,
12807        window: &mut Window,
12808        cx: &mut Context<Self>,
12809    ) {
12810        let snapshot = self.snapshot(window, cx);
12811        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12812        let mut ranges_by_buffer = HashMap::default();
12813        self.transact(window, cx, |editor, _window, cx| {
12814            for hunk in hunks {
12815                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12816                    ranges_by_buffer
12817                        .entry(buffer.clone())
12818                        .or_insert_with(Vec::new)
12819                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12820                }
12821            }
12822
12823            for (buffer, ranges) in ranges_by_buffer {
12824                buffer.update(cx, |buffer, cx| {
12825                    buffer.merge_into_base(ranges, cx);
12826                });
12827            }
12828        });
12829
12830        if let Some(project) = self.project.clone() {
12831            self.save(true, project, window, cx).detach_and_log_err(cx);
12832        }
12833    }
12834
12835    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12836        if hovered != self.gutter_hovered {
12837            self.gutter_hovered = hovered;
12838            cx.notify();
12839        }
12840    }
12841
12842    pub fn insert_blocks(
12843        &mut self,
12844        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12845        autoscroll: Option<Autoscroll>,
12846        cx: &mut Context<Self>,
12847    ) -> Vec<CustomBlockId> {
12848        let blocks = self
12849            .display_map
12850            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12851        if let Some(autoscroll) = autoscroll {
12852            self.request_autoscroll(autoscroll, cx);
12853        }
12854        cx.notify();
12855        blocks
12856    }
12857
12858    pub fn resize_blocks(
12859        &mut self,
12860        heights: HashMap<CustomBlockId, u32>,
12861        autoscroll: Option<Autoscroll>,
12862        cx: &mut Context<Self>,
12863    ) {
12864        self.display_map
12865            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12866        if let Some(autoscroll) = autoscroll {
12867            self.request_autoscroll(autoscroll, cx);
12868        }
12869        cx.notify();
12870    }
12871
12872    pub fn replace_blocks(
12873        &mut self,
12874        renderers: HashMap<CustomBlockId, RenderBlock>,
12875        autoscroll: Option<Autoscroll>,
12876        cx: &mut Context<Self>,
12877    ) {
12878        self.display_map
12879            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12880        if let Some(autoscroll) = autoscroll {
12881            self.request_autoscroll(autoscroll, cx);
12882        }
12883        cx.notify();
12884    }
12885
12886    pub fn remove_blocks(
12887        &mut self,
12888        block_ids: HashSet<CustomBlockId>,
12889        autoscroll: Option<Autoscroll>,
12890        cx: &mut Context<Self>,
12891    ) {
12892        self.display_map.update(cx, |display_map, cx| {
12893            display_map.remove_blocks(block_ids, cx)
12894        });
12895        if let Some(autoscroll) = autoscroll {
12896            self.request_autoscroll(autoscroll, cx);
12897        }
12898        cx.notify();
12899    }
12900
12901    pub fn row_for_block(
12902        &self,
12903        block_id: CustomBlockId,
12904        cx: &mut Context<Self>,
12905    ) -> Option<DisplayRow> {
12906        self.display_map
12907            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12908    }
12909
12910    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12911        self.focused_block = Some(focused_block);
12912    }
12913
12914    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12915        self.focused_block.take()
12916    }
12917
12918    pub fn insert_creases(
12919        &mut self,
12920        creases: impl IntoIterator<Item = Crease<Anchor>>,
12921        cx: &mut Context<Self>,
12922    ) -> Vec<CreaseId> {
12923        self.display_map
12924            .update(cx, |map, cx| map.insert_creases(creases, cx))
12925    }
12926
12927    pub fn remove_creases(
12928        &mut self,
12929        ids: impl IntoIterator<Item = CreaseId>,
12930        cx: &mut Context<Self>,
12931    ) {
12932        self.display_map
12933            .update(cx, |map, cx| map.remove_creases(ids, cx));
12934    }
12935
12936    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12937        self.display_map
12938            .update(cx, |map, cx| map.snapshot(cx))
12939            .longest_row()
12940    }
12941
12942    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12943        self.display_map
12944            .update(cx, |map, cx| map.snapshot(cx))
12945            .max_point()
12946    }
12947
12948    pub fn text(&self, cx: &App) -> String {
12949        self.buffer.read(cx).read(cx).text()
12950    }
12951
12952    pub fn is_empty(&self, cx: &App) -> bool {
12953        self.buffer.read(cx).read(cx).is_empty()
12954    }
12955
12956    pub fn text_option(&self, cx: &App) -> Option<String> {
12957        let text = self.text(cx);
12958        let text = text.trim();
12959
12960        if text.is_empty() {
12961            return None;
12962        }
12963
12964        Some(text.to_string())
12965    }
12966
12967    pub fn set_text(
12968        &mut self,
12969        text: impl Into<Arc<str>>,
12970        window: &mut Window,
12971        cx: &mut Context<Self>,
12972    ) {
12973        self.transact(window, cx, |this, _, cx| {
12974            this.buffer
12975                .read(cx)
12976                .as_singleton()
12977                .expect("you can only call set_text on editors for singleton buffers")
12978                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12979        });
12980    }
12981
12982    pub fn display_text(&self, cx: &mut App) -> String {
12983        self.display_map
12984            .update(cx, |map, cx| map.snapshot(cx))
12985            .text()
12986    }
12987
12988    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12989        let mut wrap_guides = smallvec::smallvec![];
12990
12991        if self.show_wrap_guides == Some(false) {
12992            return wrap_guides;
12993        }
12994
12995        let settings = self.buffer.read(cx).settings_at(0, cx);
12996        if settings.show_wrap_guides {
12997            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12998                wrap_guides.push((soft_wrap as usize, true));
12999            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
13000                wrap_guides.push((soft_wrap as usize, true));
13001            }
13002            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
13003        }
13004
13005        wrap_guides
13006    }
13007
13008    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
13009        let settings = self.buffer.read(cx).settings_at(0, cx);
13010        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
13011        match mode {
13012            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
13013                SoftWrap::None
13014            }
13015            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
13016            language_settings::SoftWrap::PreferredLineLength => {
13017                SoftWrap::Column(settings.preferred_line_length)
13018            }
13019            language_settings::SoftWrap::Bounded => {
13020                SoftWrap::Bounded(settings.preferred_line_length)
13021            }
13022        }
13023    }
13024
13025    pub fn set_soft_wrap_mode(
13026        &mut self,
13027        mode: language_settings::SoftWrap,
13028
13029        cx: &mut Context<Self>,
13030    ) {
13031        self.soft_wrap_mode_override = Some(mode);
13032        cx.notify();
13033    }
13034
13035    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
13036        self.text_style_refinement = Some(style);
13037    }
13038
13039    /// called by the Element so we know what style we were most recently rendered with.
13040    pub(crate) fn set_style(
13041        &mut self,
13042        style: EditorStyle,
13043        window: &mut Window,
13044        cx: &mut Context<Self>,
13045    ) {
13046        let rem_size = window.rem_size();
13047        self.display_map.update(cx, |map, cx| {
13048            map.set_font(
13049                style.text.font(),
13050                style.text.font_size.to_pixels(rem_size),
13051                cx,
13052            )
13053        });
13054        self.style = Some(style);
13055    }
13056
13057    pub fn style(&self) -> Option<&EditorStyle> {
13058        self.style.as_ref()
13059    }
13060
13061    // Called by the element. This method is not designed to be called outside of the editor
13062    // element's layout code because it does not notify when rewrapping is computed synchronously.
13063    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
13064        self.display_map
13065            .update(cx, |map, cx| map.set_wrap_width(width, cx))
13066    }
13067
13068    pub fn set_soft_wrap(&mut self) {
13069        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
13070    }
13071
13072    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
13073        if self.soft_wrap_mode_override.is_some() {
13074            self.soft_wrap_mode_override.take();
13075        } else {
13076            let soft_wrap = match self.soft_wrap_mode(cx) {
13077                SoftWrap::GitDiff => return,
13078                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
13079                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
13080                    language_settings::SoftWrap::None
13081                }
13082            };
13083            self.soft_wrap_mode_override = Some(soft_wrap);
13084        }
13085        cx.notify();
13086    }
13087
13088    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
13089        let Some(workspace) = self.workspace() else {
13090            return;
13091        };
13092        let fs = workspace.read(cx).app_state().fs.clone();
13093        let current_show = TabBarSettings::get_global(cx).show;
13094        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
13095            setting.show = Some(!current_show);
13096        });
13097    }
13098
13099    pub fn toggle_indent_guides(
13100        &mut self,
13101        _: &ToggleIndentGuides,
13102        _: &mut Window,
13103        cx: &mut Context<Self>,
13104    ) {
13105        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
13106            self.buffer
13107                .read(cx)
13108                .settings_at(0, cx)
13109                .indent_guides
13110                .enabled
13111        });
13112        self.show_indent_guides = Some(!currently_enabled);
13113        cx.notify();
13114    }
13115
13116    fn should_show_indent_guides(&self) -> Option<bool> {
13117        self.show_indent_guides
13118    }
13119
13120    pub fn toggle_line_numbers(
13121        &mut self,
13122        _: &ToggleLineNumbers,
13123        _: &mut Window,
13124        cx: &mut Context<Self>,
13125    ) {
13126        let mut editor_settings = EditorSettings::get_global(cx).clone();
13127        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
13128        EditorSettings::override_global(editor_settings, cx);
13129    }
13130
13131    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
13132        self.use_relative_line_numbers
13133            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
13134    }
13135
13136    pub fn toggle_relative_line_numbers(
13137        &mut self,
13138        _: &ToggleRelativeLineNumbers,
13139        _: &mut Window,
13140        cx: &mut Context<Self>,
13141    ) {
13142        let is_relative = self.should_use_relative_line_numbers(cx);
13143        self.set_relative_line_number(Some(!is_relative), cx)
13144    }
13145
13146    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
13147        self.use_relative_line_numbers = is_relative;
13148        cx.notify();
13149    }
13150
13151    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
13152        self.show_gutter = show_gutter;
13153        cx.notify();
13154    }
13155
13156    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
13157        self.show_scrollbars = show_scrollbars;
13158        cx.notify();
13159    }
13160
13161    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
13162        self.show_line_numbers = Some(show_line_numbers);
13163        cx.notify();
13164    }
13165
13166    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
13167        self.show_git_diff_gutter = Some(show_git_diff_gutter);
13168        cx.notify();
13169    }
13170
13171    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
13172        self.show_code_actions = Some(show_code_actions);
13173        cx.notify();
13174    }
13175
13176    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
13177        self.show_runnables = Some(show_runnables);
13178        cx.notify();
13179    }
13180
13181    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
13182        if self.display_map.read(cx).masked != masked {
13183            self.display_map.update(cx, |map, _| map.masked = masked);
13184        }
13185        cx.notify()
13186    }
13187
13188    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
13189        self.show_wrap_guides = Some(show_wrap_guides);
13190        cx.notify();
13191    }
13192
13193    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
13194        self.show_indent_guides = Some(show_indent_guides);
13195        cx.notify();
13196    }
13197
13198    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
13199        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
13200            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
13201                if let Some(dir) = file.abs_path(cx).parent() {
13202                    return Some(dir.to_owned());
13203                }
13204            }
13205
13206            if let Some(project_path) = buffer.read(cx).project_path(cx) {
13207                return Some(project_path.path.to_path_buf());
13208            }
13209        }
13210
13211        None
13212    }
13213
13214    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
13215        self.active_excerpt(cx)?
13216            .1
13217            .read(cx)
13218            .file()
13219            .and_then(|f| f.as_local())
13220    }
13221
13222    pub fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13223        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13224            let buffer = buffer.read(cx);
13225            if let Some(project_path) = buffer.project_path(cx) {
13226                let project = self.project.as_ref()?.read(cx);
13227                project.absolute_path(&project_path, cx)
13228            } else {
13229                buffer
13230                    .file()
13231                    .and_then(|file| file.as_local().map(|file| file.abs_path(cx)))
13232            }
13233        })
13234    }
13235
13236    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
13237        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
13238            let project_path = buffer.read(cx).project_path(cx)?;
13239            let project = self.project.as_ref()?.read(cx);
13240            let entry = project.entry_for_path(&project_path, cx)?;
13241            let path = entry.path.to_path_buf();
13242            Some(path)
13243        })
13244    }
13245
13246    pub fn reveal_in_finder(
13247        &mut self,
13248        _: &RevealInFileManager,
13249        _window: &mut Window,
13250        cx: &mut Context<Self>,
13251    ) {
13252        if let Some(target) = self.target_file(cx) {
13253            cx.reveal_path(&target.abs_path(cx));
13254        }
13255    }
13256
13257    pub fn copy_path(
13258        &mut self,
13259        _: &zed_actions::workspace::CopyPath,
13260        _window: &mut Window,
13261        cx: &mut Context<Self>,
13262    ) {
13263        if let Some(path) = self.target_file_abs_path(cx) {
13264            if let Some(path) = path.to_str() {
13265                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13266            }
13267        }
13268    }
13269
13270    pub fn copy_relative_path(
13271        &mut self,
13272        _: &zed_actions::workspace::CopyRelativePath,
13273        _window: &mut Window,
13274        cx: &mut Context<Self>,
13275    ) {
13276        if let Some(path) = self.target_file_path(cx) {
13277            if let Some(path) = path.to_str() {
13278                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
13279            }
13280        }
13281    }
13282
13283    pub fn copy_file_name_without_extension(
13284        &mut self,
13285        _: &CopyFileNameWithoutExtension,
13286        _: &mut Window,
13287        cx: &mut Context<Self>,
13288    ) {
13289        if let Some(file) = self.target_file(cx) {
13290            if let Some(file_stem) = file.path().file_stem() {
13291                if let Some(name) = file_stem.to_str() {
13292                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13293                }
13294            }
13295        }
13296    }
13297
13298    pub fn copy_file_name(&mut self, _: &CopyFileName, _: &mut Window, cx: &mut Context<Self>) {
13299        if let Some(file) = self.target_file(cx) {
13300            if let Some(file_name) = file.path().file_name() {
13301                if let Some(name) = file_name.to_str() {
13302                    cx.write_to_clipboard(ClipboardItem::new_string(name.to_string()));
13303                }
13304            }
13305        }
13306    }
13307
13308    pub fn toggle_git_blame(
13309        &mut self,
13310        _: &ToggleGitBlame,
13311        window: &mut Window,
13312        cx: &mut Context<Self>,
13313    ) {
13314        self.show_git_blame_gutter = !self.show_git_blame_gutter;
13315
13316        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
13317            self.start_git_blame(true, window, cx);
13318        }
13319
13320        cx.notify();
13321    }
13322
13323    pub fn toggle_git_blame_inline(
13324        &mut self,
13325        _: &ToggleGitBlameInline,
13326        window: &mut Window,
13327        cx: &mut Context<Self>,
13328    ) {
13329        self.toggle_git_blame_inline_internal(true, window, cx);
13330        cx.notify();
13331    }
13332
13333    pub fn git_blame_inline_enabled(&self) -> bool {
13334        self.git_blame_inline_enabled
13335    }
13336
13337    pub fn toggle_selection_menu(
13338        &mut self,
13339        _: &ToggleSelectionMenu,
13340        _: &mut Window,
13341        cx: &mut Context<Self>,
13342    ) {
13343        self.show_selection_menu = self
13344            .show_selection_menu
13345            .map(|show_selections_menu| !show_selections_menu)
13346            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
13347
13348        cx.notify();
13349    }
13350
13351    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
13352        self.show_selection_menu
13353            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
13354    }
13355
13356    fn start_git_blame(
13357        &mut self,
13358        user_triggered: bool,
13359        window: &mut Window,
13360        cx: &mut Context<Self>,
13361    ) {
13362        if let Some(project) = self.project.as_ref() {
13363            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
13364                return;
13365            };
13366
13367            if buffer.read(cx).file().is_none() {
13368                return;
13369            }
13370
13371            let focused = self.focus_handle(cx).contains_focused(window, cx);
13372
13373            let project = project.clone();
13374            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
13375            self.blame_subscription =
13376                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
13377            self.blame = Some(blame);
13378        }
13379    }
13380
13381    fn toggle_git_blame_inline_internal(
13382        &mut self,
13383        user_triggered: bool,
13384        window: &mut Window,
13385        cx: &mut Context<Self>,
13386    ) {
13387        if self.git_blame_inline_enabled {
13388            self.git_blame_inline_enabled = false;
13389            self.show_git_blame_inline = false;
13390            self.show_git_blame_inline_delay_task.take();
13391        } else {
13392            self.git_blame_inline_enabled = true;
13393            self.start_git_blame_inline(user_triggered, window, cx);
13394        }
13395
13396        cx.notify();
13397    }
13398
13399    fn start_git_blame_inline(
13400        &mut self,
13401        user_triggered: bool,
13402        window: &mut Window,
13403        cx: &mut Context<Self>,
13404    ) {
13405        self.start_git_blame(user_triggered, window, cx);
13406
13407        if ProjectSettings::get_global(cx)
13408            .git
13409            .inline_blame_delay()
13410            .is_some()
13411        {
13412            self.start_inline_blame_timer(window, cx);
13413        } else {
13414            self.show_git_blame_inline = true
13415        }
13416    }
13417
13418    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
13419        self.blame.as_ref()
13420    }
13421
13422    pub fn show_git_blame_gutter(&self) -> bool {
13423        self.show_git_blame_gutter
13424    }
13425
13426    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
13427        self.show_git_blame_gutter && self.has_blame_entries(cx)
13428    }
13429
13430    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
13431        self.show_git_blame_inline
13432            && self.focus_handle.is_focused(window)
13433            && !self.newest_selection_head_on_empty_line(cx)
13434            && self.has_blame_entries(cx)
13435    }
13436
13437    fn has_blame_entries(&self, cx: &App) -> bool {
13438        self.blame()
13439            .map_or(false, |blame| blame.read(cx).has_generated_entries())
13440    }
13441
13442    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
13443        let cursor_anchor = self.selections.newest_anchor().head();
13444
13445        let snapshot = self.buffer.read(cx).snapshot(cx);
13446        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
13447
13448        snapshot.line_len(buffer_row) == 0
13449    }
13450
13451    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
13452        let buffer_and_selection = maybe!({
13453            let selection = self.selections.newest::<Point>(cx);
13454            let selection_range = selection.range();
13455
13456            let multi_buffer = self.buffer().read(cx);
13457            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13458            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
13459
13460            let (buffer, range, _) = if selection.reversed {
13461                buffer_ranges.first()
13462            } else {
13463                buffer_ranges.last()
13464            }?;
13465
13466            let selection = text::ToPoint::to_point(&range.start, &buffer).row
13467                ..text::ToPoint::to_point(&range.end, &buffer).row;
13468            Some((
13469                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
13470                selection,
13471            ))
13472        });
13473
13474        let Some((buffer, selection)) = buffer_and_selection else {
13475            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
13476        };
13477
13478        let Some(project) = self.project.as_ref() else {
13479            return Task::ready(Err(anyhow!("editor does not have project")));
13480        };
13481
13482        project.update(cx, |project, cx| {
13483            project.get_permalink_to_line(&buffer, selection, cx)
13484        })
13485    }
13486
13487    pub fn copy_permalink_to_line(
13488        &mut self,
13489        _: &CopyPermalinkToLine,
13490        window: &mut Window,
13491        cx: &mut Context<Self>,
13492    ) {
13493        let permalink_task = self.get_permalink_to_line(cx);
13494        let workspace = self.workspace();
13495
13496        cx.spawn_in(window, |_, mut cx| async move {
13497            match permalink_task.await {
13498                Ok(permalink) => {
13499                    cx.update(|_, cx| {
13500                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
13501                    })
13502                    .ok();
13503                }
13504                Err(err) => {
13505                    let message = format!("Failed to copy permalink: {err}");
13506
13507                    Err::<(), anyhow::Error>(err).log_err();
13508
13509                    if let Some(workspace) = workspace {
13510                        workspace
13511                            .update_in(&mut cx, |workspace, _, cx| {
13512                                struct CopyPermalinkToLine;
13513
13514                                workspace.show_toast(
13515                                    Toast::new(
13516                                        NotificationId::unique::<CopyPermalinkToLine>(),
13517                                        message,
13518                                    ),
13519                                    cx,
13520                                )
13521                            })
13522                            .ok();
13523                    }
13524                }
13525            }
13526        })
13527        .detach();
13528    }
13529
13530    pub fn copy_file_location(
13531        &mut self,
13532        _: &CopyFileLocation,
13533        _: &mut Window,
13534        cx: &mut Context<Self>,
13535    ) {
13536        let selection = self.selections.newest::<Point>(cx).start.row + 1;
13537        if let Some(file) = self.target_file(cx) {
13538            if let Some(path) = file.path().to_str() {
13539                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
13540            }
13541        }
13542    }
13543
13544    pub fn open_permalink_to_line(
13545        &mut self,
13546        _: &OpenPermalinkToLine,
13547        window: &mut Window,
13548        cx: &mut Context<Self>,
13549    ) {
13550        let permalink_task = self.get_permalink_to_line(cx);
13551        let workspace = self.workspace();
13552
13553        cx.spawn_in(window, |_, mut cx| async move {
13554            match permalink_task.await {
13555                Ok(permalink) => {
13556                    cx.update(|_, cx| {
13557                        cx.open_url(permalink.as_ref());
13558                    })
13559                    .ok();
13560                }
13561                Err(err) => {
13562                    let message = format!("Failed to open permalink: {err}");
13563
13564                    Err::<(), anyhow::Error>(err).log_err();
13565
13566                    if let Some(workspace) = workspace {
13567                        workspace
13568                            .update(&mut cx, |workspace, cx| {
13569                                struct OpenPermalinkToLine;
13570
13571                                workspace.show_toast(
13572                                    Toast::new(
13573                                        NotificationId::unique::<OpenPermalinkToLine>(),
13574                                        message,
13575                                    ),
13576                                    cx,
13577                                )
13578                            })
13579                            .ok();
13580                    }
13581                }
13582            }
13583        })
13584        .detach();
13585    }
13586
13587    pub fn insert_uuid_v4(
13588        &mut self,
13589        _: &InsertUuidV4,
13590        window: &mut Window,
13591        cx: &mut Context<Self>,
13592    ) {
13593        self.insert_uuid(UuidVersion::V4, window, cx);
13594    }
13595
13596    pub fn insert_uuid_v7(
13597        &mut self,
13598        _: &InsertUuidV7,
13599        window: &mut Window,
13600        cx: &mut Context<Self>,
13601    ) {
13602        self.insert_uuid(UuidVersion::V7, window, cx);
13603    }
13604
13605    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13606        self.transact(window, cx, |this, window, cx| {
13607            let edits = this
13608                .selections
13609                .all::<Point>(cx)
13610                .into_iter()
13611                .map(|selection| {
13612                    let uuid = match version {
13613                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13614                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13615                    };
13616
13617                    (selection.range(), uuid.to_string())
13618                });
13619            this.edit(edits, cx);
13620            this.refresh_inline_completion(true, false, window, cx);
13621        });
13622    }
13623
13624    pub fn open_selections_in_multibuffer(
13625        &mut self,
13626        _: &OpenSelectionsInMultibuffer,
13627        window: &mut Window,
13628        cx: &mut Context<Self>,
13629    ) {
13630        let multibuffer = self.buffer.read(cx);
13631
13632        let Some(buffer) = multibuffer.as_singleton() else {
13633            return;
13634        };
13635
13636        let Some(workspace) = self.workspace() else {
13637            return;
13638        };
13639
13640        let locations = self
13641            .selections
13642            .disjoint_anchors()
13643            .iter()
13644            .map(|range| Location {
13645                buffer: buffer.clone(),
13646                range: range.start.text_anchor..range.end.text_anchor,
13647            })
13648            .collect::<Vec<_>>();
13649
13650        let title = multibuffer.title(cx).to_string();
13651
13652        cx.spawn_in(window, |_, mut cx| async move {
13653            workspace.update_in(&mut cx, |workspace, window, cx| {
13654                Self::open_locations_in_multibuffer(
13655                    workspace,
13656                    locations,
13657                    format!("Selections for '{title}'"),
13658                    false,
13659                    MultibufferSelectionMode::All,
13660                    window,
13661                    cx,
13662                );
13663            })
13664        })
13665        .detach();
13666    }
13667
13668    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13669    /// last highlight added will be used.
13670    ///
13671    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13672    pub fn highlight_rows<T: 'static>(
13673        &mut self,
13674        range: Range<Anchor>,
13675        color: Hsla,
13676        should_autoscroll: bool,
13677        cx: &mut Context<Self>,
13678    ) {
13679        let snapshot = self.buffer().read(cx).snapshot(cx);
13680        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13681        let ix = row_highlights.binary_search_by(|highlight| {
13682            Ordering::Equal
13683                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13684                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13685        });
13686
13687        if let Err(mut ix) = ix {
13688            let index = post_inc(&mut self.highlight_order);
13689
13690            // If this range intersects with the preceding highlight, then merge it with
13691            // the preceding highlight. Otherwise insert a new highlight.
13692            let mut merged = false;
13693            if ix > 0 {
13694                let prev_highlight = &mut row_highlights[ix - 1];
13695                if prev_highlight
13696                    .range
13697                    .end
13698                    .cmp(&range.start, &snapshot)
13699                    .is_ge()
13700                {
13701                    ix -= 1;
13702                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13703                        prev_highlight.range.end = range.end;
13704                    }
13705                    merged = true;
13706                    prev_highlight.index = index;
13707                    prev_highlight.color = color;
13708                    prev_highlight.should_autoscroll = should_autoscroll;
13709                }
13710            }
13711
13712            if !merged {
13713                row_highlights.insert(
13714                    ix,
13715                    RowHighlight {
13716                        range: range.clone(),
13717                        index,
13718                        color,
13719                        should_autoscroll,
13720                    },
13721                );
13722            }
13723
13724            // If any of the following highlights intersect with this one, merge them.
13725            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13726                let highlight = &row_highlights[ix];
13727                if next_highlight
13728                    .range
13729                    .start
13730                    .cmp(&highlight.range.end, &snapshot)
13731                    .is_le()
13732                {
13733                    if next_highlight
13734                        .range
13735                        .end
13736                        .cmp(&highlight.range.end, &snapshot)
13737                        .is_gt()
13738                    {
13739                        row_highlights[ix].range.end = next_highlight.range.end;
13740                    }
13741                    row_highlights.remove(ix + 1);
13742                } else {
13743                    break;
13744                }
13745            }
13746        }
13747    }
13748
13749    /// Remove any highlighted row ranges of the given type that intersect the
13750    /// given ranges.
13751    pub fn remove_highlighted_rows<T: 'static>(
13752        &mut self,
13753        ranges_to_remove: Vec<Range<Anchor>>,
13754        cx: &mut Context<Self>,
13755    ) {
13756        let snapshot = self.buffer().read(cx).snapshot(cx);
13757        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13758        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13759        row_highlights.retain(|highlight| {
13760            while let Some(range_to_remove) = ranges_to_remove.peek() {
13761                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13762                    Ordering::Less | Ordering::Equal => {
13763                        ranges_to_remove.next();
13764                    }
13765                    Ordering::Greater => {
13766                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13767                            Ordering::Less | Ordering::Equal => {
13768                                return false;
13769                            }
13770                            Ordering::Greater => break,
13771                        }
13772                    }
13773                }
13774            }
13775
13776            true
13777        })
13778    }
13779
13780    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13781    pub fn clear_row_highlights<T: 'static>(&mut self) {
13782        self.highlighted_rows.remove(&TypeId::of::<T>());
13783    }
13784
13785    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13786    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13787        self.highlighted_rows
13788            .get(&TypeId::of::<T>())
13789            .map_or(&[] as &[_], |vec| vec.as_slice())
13790            .iter()
13791            .map(|highlight| (highlight.range.clone(), highlight.color))
13792    }
13793
13794    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13795    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13796    /// Allows to ignore certain kinds of highlights.
13797    pub fn highlighted_display_rows(
13798        &self,
13799        window: &mut Window,
13800        cx: &mut App,
13801    ) -> BTreeMap<DisplayRow, Background> {
13802        let snapshot = self.snapshot(window, cx);
13803        let mut used_highlight_orders = HashMap::default();
13804        self.highlighted_rows
13805            .iter()
13806            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13807            .fold(
13808                BTreeMap::<DisplayRow, Background>::new(),
13809                |mut unique_rows, highlight| {
13810                    let start = highlight.range.start.to_display_point(&snapshot);
13811                    let end = highlight.range.end.to_display_point(&snapshot);
13812                    let start_row = start.row().0;
13813                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13814                        && end.column() == 0
13815                    {
13816                        end.row().0.saturating_sub(1)
13817                    } else {
13818                        end.row().0
13819                    };
13820                    for row in start_row..=end_row {
13821                        let used_index =
13822                            used_highlight_orders.entry(row).or_insert(highlight.index);
13823                        if highlight.index >= *used_index {
13824                            *used_index = highlight.index;
13825                            unique_rows.insert(DisplayRow(row), highlight.color.into());
13826                        }
13827                    }
13828                    unique_rows
13829                },
13830            )
13831    }
13832
13833    pub fn highlighted_display_row_for_autoscroll(
13834        &self,
13835        snapshot: &DisplaySnapshot,
13836    ) -> Option<DisplayRow> {
13837        self.highlighted_rows
13838            .values()
13839            .flat_map(|highlighted_rows| highlighted_rows.iter())
13840            .filter_map(|highlight| {
13841                if highlight.should_autoscroll {
13842                    Some(highlight.range.start.to_display_point(snapshot).row())
13843                } else {
13844                    None
13845                }
13846            })
13847            .min()
13848    }
13849
13850    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13851        self.highlight_background::<SearchWithinRange>(
13852            ranges,
13853            |colors| colors.editor_document_highlight_read_background,
13854            cx,
13855        )
13856    }
13857
13858    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13859        self.breadcrumb_header = Some(new_header);
13860    }
13861
13862    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13863        self.clear_background_highlights::<SearchWithinRange>(cx);
13864    }
13865
13866    pub fn highlight_background<T: 'static>(
13867        &mut self,
13868        ranges: &[Range<Anchor>],
13869        color_fetcher: fn(&ThemeColors) -> Hsla,
13870        cx: &mut Context<Self>,
13871    ) {
13872        self.background_highlights
13873            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13874        self.scrollbar_marker_state.dirty = true;
13875        cx.notify();
13876    }
13877
13878    pub fn clear_background_highlights<T: 'static>(
13879        &mut self,
13880        cx: &mut Context<Self>,
13881    ) -> Option<BackgroundHighlight> {
13882        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13883        if !text_highlights.1.is_empty() {
13884            self.scrollbar_marker_state.dirty = true;
13885            cx.notify();
13886        }
13887        Some(text_highlights)
13888    }
13889
13890    pub fn highlight_gutter<T: 'static>(
13891        &mut self,
13892        ranges: &[Range<Anchor>],
13893        color_fetcher: fn(&App) -> Hsla,
13894        cx: &mut Context<Self>,
13895    ) {
13896        self.gutter_highlights
13897            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13898        cx.notify();
13899    }
13900
13901    pub fn clear_gutter_highlights<T: 'static>(
13902        &mut self,
13903        cx: &mut Context<Self>,
13904    ) -> Option<GutterHighlight> {
13905        cx.notify();
13906        self.gutter_highlights.remove(&TypeId::of::<T>())
13907    }
13908
13909    #[cfg(feature = "test-support")]
13910    pub fn all_text_background_highlights(
13911        &self,
13912        window: &mut Window,
13913        cx: &mut Context<Self>,
13914    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13915        let snapshot = self.snapshot(window, cx);
13916        let buffer = &snapshot.buffer_snapshot;
13917        let start = buffer.anchor_before(0);
13918        let end = buffer.anchor_after(buffer.len());
13919        let theme = cx.theme().colors();
13920        self.background_highlights_in_range(start..end, &snapshot, theme)
13921    }
13922
13923    #[cfg(feature = "test-support")]
13924    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13925        let snapshot = self.buffer().read(cx).snapshot(cx);
13926
13927        let highlights = self
13928            .background_highlights
13929            .get(&TypeId::of::<items::BufferSearchHighlights>());
13930
13931        if let Some((_color, ranges)) = highlights {
13932            ranges
13933                .iter()
13934                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13935                .collect_vec()
13936        } else {
13937            vec![]
13938        }
13939    }
13940
13941    fn document_highlights_for_position<'a>(
13942        &'a self,
13943        position: Anchor,
13944        buffer: &'a MultiBufferSnapshot,
13945    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13946        let read_highlights = self
13947            .background_highlights
13948            .get(&TypeId::of::<DocumentHighlightRead>())
13949            .map(|h| &h.1);
13950        let write_highlights = self
13951            .background_highlights
13952            .get(&TypeId::of::<DocumentHighlightWrite>())
13953            .map(|h| &h.1);
13954        let left_position = position.bias_left(buffer);
13955        let right_position = position.bias_right(buffer);
13956        read_highlights
13957            .into_iter()
13958            .chain(write_highlights)
13959            .flat_map(move |ranges| {
13960                let start_ix = match ranges.binary_search_by(|probe| {
13961                    let cmp = probe.end.cmp(&left_position, buffer);
13962                    if cmp.is_ge() {
13963                        Ordering::Greater
13964                    } else {
13965                        Ordering::Less
13966                    }
13967                }) {
13968                    Ok(i) | Err(i) => i,
13969                };
13970
13971                ranges[start_ix..]
13972                    .iter()
13973                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13974            })
13975    }
13976
13977    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13978        self.background_highlights
13979            .get(&TypeId::of::<T>())
13980            .map_or(false, |(_, highlights)| !highlights.is_empty())
13981    }
13982
13983    pub fn background_highlights_in_range(
13984        &self,
13985        search_range: Range<Anchor>,
13986        display_snapshot: &DisplaySnapshot,
13987        theme: &ThemeColors,
13988    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13989        let mut results = Vec::new();
13990        for (color_fetcher, ranges) in self.background_highlights.values() {
13991            let color = color_fetcher(theme);
13992            let start_ix = match ranges.binary_search_by(|probe| {
13993                let cmp = probe
13994                    .end
13995                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13996                if cmp.is_gt() {
13997                    Ordering::Greater
13998                } else {
13999                    Ordering::Less
14000                }
14001            }) {
14002                Ok(i) | Err(i) => i,
14003            };
14004            for range in &ranges[start_ix..] {
14005                if range
14006                    .start
14007                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14008                    .is_ge()
14009                {
14010                    break;
14011                }
14012
14013                let start = range.start.to_display_point(display_snapshot);
14014                let end = range.end.to_display_point(display_snapshot);
14015                results.push((start..end, color))
14016            }
14017        }
14018        results
14019    }
14020
14021    pub fn background_highlight_row_ranges<T: 'static>(
14022        &self,
14023        search_range: Range<Anchor>,
14024        display_snapshot: &DisplaySnapshot,
14025        count: usize,
14026    ) -> Vec<RangeInclusive<DisplayPoint>> {
14027        let mut results = Vec::new();
14028        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
14029            return vec![];
14030        };
14031
14032        let start_ix = match ranges.binary_search_by(|probe| {
14033            let cmp = probe
14034                .end
14035                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14036            if cmp.is_gt() {
14037                Ordering::Greater
14038            } else {
14039                Ordering::Less
14040            }
14041        }) {
14042            Ok(i) | Err(i) => i,
14043        };
14044        let mut push_region = |start: Option<Point>, end: Option<Point>| {
14045            if let (Some(start_display), Some(end_display)) = (start, end) {
14046                results.push(
14047                    start_display.to_display_point(display_snapshot)
14048                        ..=end_display.to_display_point(display_snapshot),
14049                );
14050            }
14051        };
14052        let mut start_row: Option<Point> = None;
14053        let mut end_row: Option<Point> = None;
14054        if ranges.len() > count {
14055            return Vec::new();
14056        }
14057        for range in &ranges[start_ix..] {
14058            if range
14059                .start
14060                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14061                .is_ge()
14062            {
14063                break;
14064            }
14065            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
14066            if let Some(current_row) = &end_row {
14067                if end.row == current_row.row {
14068                    continue;
14069                }
14070            }
14071            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
14072            if start_row.is_none() {
14073                assert_eq!(end_row, None);
14074                start_row = Some(start);
14075                end_row = Some(end);
14076                continue;
14077            }
14078            if let Some(current_end) = end_row.as_mut() {
14079                if start.row > current_end.row + 1 {
14080                    push_region(start_row, end_row);
14081                    start_row = Some(start);
14082                    end_row = Some(end);
14083                } else {
14084                    // Merge two hunks.
14085                    *current_end = end;
14086                }
14087            } else {
14088                unreachable!();
14089            }
14090        }
14091        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
14092        push_region(start_row, end_row);
14093        results
14094    }
14095
14096    pub fn gutter_highlights_in_range(
14097        &self,
14098        search_range: Range<Anchor>,
14099        display_snapshot: &DisplaySnapshot,
14100        cx: &App,
14101    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
14102        let mut results = Vec::new();
14103        for (color_fetcher, ranges) in self.gutter_highlights.values() {
14104            let color = color_fetcher(cx);
14105            let start_ix = match ranges.binary_search_by(|probe| {
14106                let cmp = probe
14107                    .end
14108                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
14109                if cmp.is_gt() {
14110                    Ordering::Greater
14111                } else {
14112                    Ordering::Less
14113                }
14114            }) {
14115                Ok(i) | Err(i) => i,
14116            };
14117            for range in &ranges[start_ix..] {
14118                if range
14119                    .start
14120                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
14121                    .is_ge()
14122                {
14123                    break;
14124                }
14125
14126                let start = range.start.to_display_point(display_snapshot);
14127                let end = range.end.to_display_point(display_snapshot);
14128                results.push((start..end, color))
14129            }
14130        }
14131        results
14132    }
14133
14134    /// Get the text ranges corresponding to the redaction query
14135    pub fn redacted_ranges(
14136        &self,
14137        search_range: Range<Anchor>,
14138        display_snapshot: &DisplaySnapshot,
14139        cx: &App,
14140    ) -> Vec<Range<DisplayPoint>> {
14141        display_snapshot
14142            .buffer_snapshot
14143            .redacted_ranges(search_range, |file| {
14144                if let Some(file) = file {
14145                    file.is_private()
14146                        && EditorSettings::get(
14147                            Some(SettingsLocation {
14148                                worktree_id: file.worktree_id(cx),
14149                                path: file.path().as_ref(),
14150                            }),
14151                            cx,
14152                        )
14153                        .redact_private_values
14154                } else {
14155                    false
14156                }
14157            })
14158            .map(|range| {
14159                range.start.to_display_point(display_snapshot)
14160                    ..range.end.to_display_point(display_snapshot)
14161            })
14162            .collect()
14163    }
14164
14165    pub fn highlight_text<T: 'static>(
14166        &mut self,
14167        ranges: Vec<Range<Anchor>>,
14168        style: HighlightStyle,
14169        cx: &mut Context<Self>,
14170    ) {
14171        self.display_map.update(cx, |map, _| {
14172            map.highlight_text(TypeId::of::<T>(), ranges, style)
14173        });
14174        cx.notify();
14175    }
14176
14177    pub(crate) fn highlight_inlays<T: 'static>(
14178        &mut self,
14179        highlights: Vec<InlayHighlight>,
14180        style: HighlightStyle,
14181        cx: &mut Context<Self>,
14182    ) {
14183        self.display_map.update(cx, |map, _| {
14184            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
14185        });
14186        cx.notify();
14187    }
14188
14189    pub fn text_highlights<'a, T: 'static>(
14190        &'a self,
14191        cx: &'a App,
14192    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
14193        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
14194    }
14195
14196    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
14197        let cleared = self
14198            .display_map
14199            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
14200        if cleared {
14201            cx.notify();
14202        }
14203    }
14204
14205    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
14206        (self.read_only(cx) || self.blink_manager.read(cx).visible())
14207            && self.focus_handle.is_focused(window)
14208    }
14209
14210    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
14211        self.show_cursor_when_unfocused = is_enabled;
14212        cx.notify();
14213    }
14214
14215    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
14216        cx.notify();
14217    }
14218
14219    fn on_buffer_event(
14220        &mut self,
14221        multibuffer: &Entity<MultiBuffer>,
14222        event: &multi_buffer::Event,
14223        window: &mut Window,
14224        cx: &mut Context<Self>,
14225    ) {
14226        match event {
14227            multi_buffer::Event::Edited {
14228                singleton_buffer_edited,
14229                edited_buffer: buffer_edited,
14230            } => {
14231                self.scrollbar_marker_state.dirty = true;
14232                self.active_indent_guides_state.dirty = true;
14233                self.refresh_active_diagnostics(cx);
14234                self.refresh_code_actions(window, cx);
14235                if self.has_active_inline_completion() {
14236                    self.update_visible_inline_completion(window, cx);
14237                }
14238                if let Some(buffer) = buffer_edited {
14239                    let buffer_id = buffer.read(cx).remote_id();
14240                    if !self.registered_buffers.contains_key(&buffer_id) {
14241                        if let Some(project) = self.project.as_ref() {
14242                            project.update(cx, |project, cx| {
14243                                self.registered_buffers.insert(
14244                                    buffer_id,
14245                                    project.register_buffer_with_language_servers(&buffer, cx),
14246                                );
14247                            })
14248                        }
14249                    }
14250                }
14251                cx.emit(EditorEvent::BufferEdited);
14252                cx.emit(SearchEvent::MatchesInvalidated);
14253                if *singleton_buffer_edited {
14254                    if let Some(project) = &self.project {
14255                        #[allow(clippy::mutable_key_type)]
14256                        let languages_affected = multibuffer.update(cx, |multibuffer, cx| {
14257                            multibuffer
14258                                .all_buffers()
14259                                .into_iter()
14260                                .filter_map(|buffer| {
14261                                    buffer.update(cx, |buffer, cx| {
14262                                        let language = buffer.language()?;
14263                                        let should_discard = project.update(cx, |project, cx| {
14264                                            project.is_local()
14265                                                && !project.has_language_servers_for(buffer, cx)
14266                                        });
14267                                        should_discard.not().then_some(language.clone())
14268                                    })
14269                                })
14270                                .collect::<HashSet<_>>()
14271                        });
14272                        if !languages_affected.is_empty() {
14273                            self.refresh_inlay_hints(
14274                                InlayHintRefreshReason::BufferEdited(languages_affected),
14275                                cx,
14276                            );
14277                        }
14278                    }
14279                }
14280
14281                let Some(project) = &self.project else { return };
14282                let (telemetry, is_via_ssh) = {
14283                    let project = project.read(cx);
14284                    let telemetry = project.client().telemetry().clone();
14285                    let is_via_ssh = project.is_via_ssh();
14286                    (telemetry, is_via_ssh)
14287                };
14288                refresh_linked_ranges(self, window, cx);
14289                telemetry.log_edit_event("editor", is_via_ssh);
14290            }
14291            multi_buffer::Event::ExcerptsAdded {
14292                buffer,
14293                predecessor,
14294                excerpts,
14295            } => {
14296                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14297                let buffer_id = buffer.read(cx).remote_id();
14298                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
14299                    if let Some(project) = &self.project {
14300                        get_uncommitted_diff_for_buffer(
14301                            project,
14302                            [buffer.clone()],
14303                            self.buffer.clone(),
14304                            cx,
14305                        )
14306                        .detach();
14307                    }
14308                }
14309                cx.emit(EditorEvent::ExcerptsAdded {
14310                    buffer: buffer.clone(),
14311                    predecessor: *predecessor,
14312                    excerpts: excerpts.clone(),
14313                });
14314                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14315            }
14316            multi_buffer::Event::ExcerptsRemoved { ids } => {
14317                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
14318                let buffer = self.buffer.read(cx);
14319                self.registered_buffers
14320                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
14321                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
14322            }
14323            multi_buffer::Event::ExcerptsEdited { ids } => {
14324                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
14325            }
14326            multi_buffer::Event::ExcerptsExpanded { ids } => {
14327                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
14328                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
14329            }
14330            multi_buffer::Event::Reparsed(buffer_id) => {
14331                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14332
14333                cx.emit(EditorEvent::Reparsed(*buffer_id));
14334            }
14335            multi_buffer::Event::DiffHunksToggled => {
14336                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14337            }
14338            multi_buffer::Event::LanguageChanged(buffer_id) => {
14339                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
14340                cx.emit(EditorEvent::Reparsed(*buffer_id));
14341                cx.notify();
14342            }
14343            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
14344            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
14345            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
14346                cx.emit(EditorEvent::TitleChanged)
14347            }
14348            // multi_buffer::Event::DiffBaseChanged => {
14349            //     self.scrollbar_marker_state.dirty = true;
14350            //     cx.emit(EditorEvent::DiffBaseChanged);
14351            //     cx.notify();
14352            // }
14353            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
14354            multi_buffer::Event::DiagnosticsUpdated => {
14355                self.refresh_active_diagnostics(cx);
14356                self.scrollbar_marker_state.dirty = true;
14357                cx.notify();
14358            }
14359            _ => {}
14360        };
14361    }
14362
14363    fn on_display_map_changed(
14364        &mut self,
14365        _: Entity<DisplayMap>,
14366        _: &mut Window,
14367        cx: &mut Context<Self>,
14368    ) {
14369        cx.notify();
14370    }
14371
14372    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14373        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
14374        self.refresh_inline_completion(true, false, window, cx);
14375        self.refresh_inlay_hints(
14376            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
14377                self.selections.newest_anchor().head(),
14378                &self.buffer.read(cx).snapshot(cx),
14379                cx,
14380            )),
14381            cx,
14382        );
14383
14384        let old_cursor_shape = self.cursor_shape;
14385
14386        {
14387            let editor_settings = EditorSettings::get_global(cx);
14388            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
14389            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
14390            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
14391        }
14392
14393        if old_cursor_shape != self.cursor_shape {
14394            cx.emit(EditorEvent::CursorShapeChanged);
14395        }
14396
14397        let project_settings = ProjectSettings::get_global(cx);
14398        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
14399
14400        if self.mode == EditorMode::Full {
14401            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
14402            if self.git_blame_inline_enabled != inline_blame_enabled {
14403                self.toggle_git_blame_inline_internal(false, window, cx);
14404            }
14405        }
14406
14407        cx.notify();
14408    }
14409
14410    pub fn set_searchable(&mut self, searchable: bool) {
14411        self.searchable = searchable;
14412    }
14413
14414    pub fn searchable(&self) -> bool {
14415        self.searchable
14416    }
14417
14418    fn open_proposed_changes_editor(
14419        &mut self,
14420        _: &OpenProposedChangesEditor,
14421        window: &mut Window,
14422        cx: &mut Context<Self>,
14423    ) {
14424        let Some(workspace) = self.workspace() else {
14425            cx.propagate();
14426            return;
14427        };
14428
14429        let selections = self.selections.all::<usize>(cx);
14430        let multi_buffer = self.buffer.read(cx);
14431        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
14432        let mut new_selections_by_buffer = HashMap::default();
14433        for selection in selections {
14434            for (buffer, range, _) in
14435                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
14436            {
14437                let mut range = range.to_point(buffer);
14438                range.start.column = 0;
14439                range.end.column = buffer.line_len(range.end.row);
14440                new_selections_by_buffer
14441                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
14442                    .or_insert(Vec::new())
14443                    .push(range)
14444            }
14445        }
14446
14447        let proposed_changes_buffers = new_selections_by_buffer
14448            .into_iter()
14449            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
14450            .collect::<Vec<_>>();
14451        let proposed_changes_editor = cx.new(|cx| {
14452            ProposedChangesEditor::new(
14453                "Proposed changes",
14454                proposed_changes_buffers,
14455                self.project.clone(),
14456                window,
14457                cx,
14458            )
14459        });
14460
14461        window.defer(cx, move |window, cx| {
14462            workspace.update(cx, |workspace, cx| {
14463                workspace.active_pane().update(cx, |pane, cx| {
14464                    pane.add_item(
14465                        Box::new(proposed_changes_editor),
14466                        true,
14467                        true,
14468                        None,
14469                        window,
14470                        cx,
14471                    );
14472                });
14473            });
14474        });
14475    }
14476
14477    pub fn open_excerpts_in_split(
14478        &mut self,
14479        _: &OpenExcerptsSplit,
14480        window: &mut Window,
14481        cx: &mut Context<Self>,
14482    ) {
14483        self.open_excerpts_common(None, true, window, cx)
14484    }
14485
14486    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
14487        self.open_excerpts_common(None, false, window, cx)
14488    }
14489
14490    fn open_excerpts_common(
14491        &mut self,
14492        jump_data: Option<JumpData>,
14493        split: bool,
14494        window: &mut Window,
14495        cx: &mut Context<Self>,
14496    ) {
14497        let Some(workspace) = self.workspace() else {
14498            cx.propagate();
14499            return;
14500        };
14501
14502        if self.buffer.read(cx).is_singleton() {
14503            cx.propagate();
14504            return;
14505        }
14506
14507        let mut new_selections_by_buffer = HashMap::default();
14508        match &jump_data {
14509            Some(JumpData::MultiBufferPoint {
14510                excerpt_id,
14511                position,
14512                anchor,
14513                line_offset_from_top,
14514            }) => {
14515                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
14516                if let Some(buffer) = multi_buffer_snapshot
14517                    .buffer_id_for_excerpt(*excerpt_id)
14518                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
14519                {
14520                    let buffer_snapshot = buffer.read(cx).snapshot();
14521                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
14522                        language::ToPoint::to_point(anchor, &buffer_snapshot)
14523                    } else {
14524                        buffer_snapshot.clip_point(*position, Bias::Left)
14525                    };
14526                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
14527                    new_selections_by_buffer.insert(
14528                        buffer,
14529                        (
14530                            vec![jump_to_offset..jump_to_offset],
14531                            Some(*line_offset_from_top),
14532                        ),
14533                    );
14534                }
14535            }
14536            Some(JumpData::MultiBufferRow {
14537                row,
14538                line_offset_from_top,
14539            }) => {
14540                let point = MultiBufferPoint::new(row.0, 0);
14541                if let Some((buffer, buffer_point, _)) =
14542                    self.buffer.read(cx).point_to_buffer_point(point, cx)
14543                {
14544                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
14545                    new_selections_by_buffer
14546                        .entry(buffer)
14547                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
14548                        .0
14549                        .push(buffer_offset..buffer_offset)
14550                }
14551            }
14552            None => {
14553                let selections = self.selections.all::<usize>(cx);
14554                let multi_buffer = self.buffer.read(cx);
14555                for selection in selections {
14556                    for (buffer, mut range, _) in multi_buffer
14557                        .snapshot(cx)
14558                        .range_to_buffer_ranges(selection.range())
14559                    {
14560                        // When editing branch buffers, jump to the corresponding location
14561                        // in their base buffer.
14562                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14563                        let buffer = buffer_handle.read(cx);
14564                        if let Some(base_buffer) = buffer.base_buffer() {
14565                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14566                            buffer_handle = base_buffer;
14567                        }
14568
14569                        if selection.reversed {
14570                            mem::swap(&mut range.start, &mut range.end);
14571                        }
14572                        new_selections_by_buffer
14573                            .entry(buffer_handle)
14574                            .or_insert((Vec::new(), None))
14575                            .0
14576                            .push(range)
14577                    }
14578                }
14579            }
14580        }
14581
14582        if new_selections_by_buffer.is_empty() {
14583            return;
14584        }
14585
14586        // We defer the pane interaction because we ourselves are a workspace item
14587        // and activating a new item causes the pane to call a method on us reentrantly,
14588        // which panics if we're on the stack.
14589        window.defer(cx, move |window, cx| {
14590            workspace.update(cx, |workspace, cx| {
14591                let pane = if split {
14592                    workspace.adjacent_pane(window, cx)
14593                } else {
14594                    workspace.active_pane().clone()
14595                };
14596
14597                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14598                    let editor = buffer
14599                        .read(cx)
14600                        .file()
14601                        .is_none()
14602                        .then(|| {
14603                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14604                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14605                            // Instead, we try to activate the existing editor in the pane first.
14606                            let (editor, pane_item_index) =
14607                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14608                                    let editor = item.downcast::<Editor>()?;
14609                                    let singleton_buffer =
14610                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14611                                    if singleton_buffer == buffer {
14612                                        Some((editor, i))
14613                                    } else {
14614                                        None
14615                                    }
14616                                })?;
14617                            pane.update(cx, |pane, cx| {
14618                                pane.activate_item(pane_item_index, true, true, window, cx)
14619                            });
14620                            Some(editor)
14621                        })
14622                        .flatten()
14623                        .unwrap_or_else(|| {
14624                            workspace.open_project_item::<Self>(
14625                                pane.clone(),
14626                                buffer,
14627                                true,
14628                                true,
14629                                window,
14630                                cx,
14631                            )
14632                        });
14633
14634                    editor.update(cx, |editor, cx| {
14635                        let autoscroll = match scroll_offset {
14636                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14637                            None => Autoscroll::newest(),
14638                        };
14639                        let nav_history = editor.nav_history.take();
14640                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14641                            s.select_ranges(ranges);
14642                        });
14643                        editor.nav_history = nav_history;
14644                    });
14645                }
14646            })
14647        });
14648    }
14649
14650    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14651        let snapshot = self.buffer.read(cx).read(cx);
14652        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14653        Some(
14654            ranges
14655                .iter()
14656                .map(move |range| {
14657                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14658                })
14659                .collect(),
14660        )
14661    }
14662
14663    fn selection_replacement_ranges(
14664        &self,
14665        range: Range<OffsetUtf16>,
14666        cx: &mut App,
14667    ) -> Vec<Range<OffsetUtf16>> {
14668        let selections = self.selections.all::<OffsetUtf16>(cx);
14669        let newest_selection = selections
14670            .iter()
14671            .max_by_key(|selection| selection.id)
14672            .unwrap();
14673        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14674        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14675        let snapshot = self.buffer.read(cx).read(cx);
14676        selections
14677            .into_iter()
14678            .map(|mut selection| {
14679                selection.start.0 =
14680                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14681                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14682                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14683                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14684            })
14685            .collect()
14686    }
14687
14688    fn report_editor_event(
14689        &self,
14690        event_type: &'static str,
14691        file_extension: Option<String>,
14692        cx: &App,
14693    ) {
14694        if cfg!(any(test, feature = "test-support")) {
14695            return;
14696        }
14697
14698        let Some(project) = &self.project else { return };
14699
14700        // If None, we are in a file without an extension
14701        let file = self
14702            .buffer
14703            .read(cx)
14704            .as_singleton()
14705            .and_then(|b| b.read(cx).file());
14706        let file_extension = file_extension.or(file
14707            .as_ref()
14708            .and_then(|file| Path::new(file.file_name(cx)).extension())
14709            .and_then(|e| e.to_str())
14710            .map(|a| a.to_string()));
14711
14712        let vim_mode = cx
14713            .global::<SettingsStore>()
14714            .raw_user_settings()
14715            .get("vim_mode")
14716            == Some(&serde_json::Value::Bool(true));
14717
14718        let edit_predictions_provider = all_language_settings(file, cx).edit_predictions.provider;
14719        let copilot_enabled = edit_predictions_provider
14720            == language::language_settings::EditPredictionProvider::Copilot;
14721        let copilot_enabled_for_language = self
14722            .buffer
14723            .read(cx)
14724            .settings_at(0, cx)
14725            .show_edit_predictions;
14726
14727        let project = project.read(cx);
14728        telemetry::event!(
14729            event_type,
14730            file_extension,
14731            vim_mode,
14732            copilot_enabled,
14733            copilot_enabled_for_language,
14734            edit_predictions_provider,
14735            is_via_ssh = project.is_via_ssh(),
14736        );
14737    }
14738
14739    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14740    /// with each line being an array of {text, highlight} objects.
14741    fn copy_highlight_json(
14742        &mut self,
14743        _: &CopyHighlightJson,
14744        window: &mut Window,
14745        cx: &mut Context<Self>,
14746    ) {
14747        #[derive(Serialize)]
14748        struct Chunk<'a> {
14749            text: String,
14750            highlight: Option<&'a str>,
14751        }
14752
14753        let snapshot = self.buffer.read(cx).snapshot(cx);
14754        let range = self
14755            .selected_text_range(false, window, cx)
14756            .and_then(|selection| {
14757                if selection.range.is_empty() {
14758                    None
14759                } else {
14760                    Some(selection.range)
14761                }
14762            })
14763            .unwrap_or_else(|| 0..snapshot.len());
14764
14765        let chunks = snapshot.chunks(range, true);
14766        let mut lines = Vec::new();
14767        let mut line: VecDeque<Chunk> = VecDeque::new();
14768
14769        let Some(style) = self.style.as_ref() else {
14770            return;
14771        };
14772
14773        for chunk in chunks {
14774            let highlight = chunk
14775                .syntax_highlight_id
14776                .and_then(|id| id.name(&style.syntax));
14777            let mut chunk_lines = chunk.text.split('\n').peekable();
14778            while let Some(text) = chunk_lines.next() {
14779                let mut merged_with_last_token = false;
14780                if let Some(last_token) = line.back_mut() {
14781                    if last_token.highlight == highlight {
14782                        last_token.text.push_str(text);
14783                        merged_with_last_token = true;
14784                    }
14785                }
14786
14787                if !merged_with_last_token {
14788                    line.push_back(Chunk {
14789                        text: text.into(),
14790                        highlight,
14791                    });
14792                }
14793
14794                if chunk_lines.peek().is_some() {
14795                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14796                        line.pop_front();
14797                    }
14798                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14799                        line.pop_back();
14800                    }
14801
14802                    lines.push(mem::take(&mut line));
14803                }
14804            }
14805        }
14806
14807        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14808            return;
14809        };
14810        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14811    }
14812
14813    pub fn open_context_menu(
14814        &mut self,
14815        _: &OpenContextMenu,
14816        window: &mut Window,
14817        cx: &mut Context<Self>,
14818    ) {
14819        self.request_autoscroll(Autoscroll::newest(), cx);
14820        let position = self.selections.newest_display(cx).start;
14821        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14822    }
14823
14824    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14825        &self.inlay_hint_cache
14826    }
14827
14828    pub fn replay_insert_event(
14829        &mut self,
14830        text: &str,
14831        relative_utf16_range: Option<Range<isize>>,
14832        window: &mut Window,
14833        cx: &mut Context<Self>,
14834    ) {
14835        if !self.input_enabled {
14836            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14837            return;
14838        }
14839        if let Some(relative_utf16_range) = relative_utf16_range {
14840            let selections = self.selections.all::<OffsetUtf16>(cx);
14841            self.change_selections(None, window, cx, |s| {
14842                let new_ranges = selections.into_iter().map(|range| {
14843                    let start = OffsetUtf16(
14844                        range
14845                            .head()
14846                            .0
14847                            .saturating_add_signed(relative_utf16_range.start),
14848                    );
14849                    let end = OffsetUtf16(
14850                        range
14851                            .head()
14852                            .0
14853                            .saturating_add_signed(relative_utf16_range.end),
14854                    );
14855                    start..end
14856                });
14857                s.select_ranges(new_ranges);
14858            });
14859        }
14860
14861        self.handle_input(text, window, cx);
14862    }
14863
14864    pub fn supports_inlay_hints(&self, cx: &mut App) -> bool {
14865        let Some(provider) = self.semantics_provider.as_ref() else {
14866            return false;
14867        };
14868
14869        let mut supports = false;
14870        self.buffer().update(cx, |this, cx| {
14871            this.for_each_buffer(|buffer| {
14872                supports |= provider.supports_inlay_hints(buffer, cx);
14873            });
14874        });
14875
14876        supports
14877    }
14878
14879    pub fn is_focused(&self, window: &Window) -> bool {
14880        self.focus_handle.is_focused(window)
14881    }
14882
14883    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14884        cx.emit(EditorEvent::Focused);
14885
14886        if let Some(descendant) = self
14887            .last_focused_descendant
14888            .take()
14889            .and_then(|descendant| descendant.upgrade())
14890        {
14891            window.focus(&descendant);
14892        } else {
14893            if let Some(blame) = self.blame.as_ref() {
14894                blame.update(cx, GitBlame::focus)
14895            }
14896
14897            self.blink_manager.update(cx, BlinkManager::enable);
14898            self.show_cursor_names(window, cx);
14899            self.buffer.update(cx, |buffer, cx| {
14900                buffer.finalize_last_transaction(cx);
14901                if self.leader_peer_id.is_none() {
14902                    buffer.set_active_selections(
14903                        &self.selections.disjoint_anchors(),
14904                        self.selections.line_mode,
14905                        self.cursor_shape,
14906                        cx,
14907                    );
14908                }
14909            });
14910        }
14911    }
14912
14913    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14914        cx.emit(EditorEvent::FocusedIn)
14915    }
14916
14917    fn handle_focus_out(
14918        &mut self,
14919        event: FocusOutEvent,
14920        _window: &mut Window,
14921        _cx: &mut Context<Self>,
14922    ) {
14923        if event.blurred != self.focus_handle {
14924            self.last_focused_descendant = Some(event.blurred);
14925        }
14926    }
14927
14928    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14929        self.blink_manager.update(cx, BlinkManager::disable);
14930        self.buffer
14931            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14932
14933        if let Some(blame) = self.blame.as_ref() {
14934            blame.update(cx, GitBlame::blur)
14935        }
14936        if !self.hover_state.focused(window, cx) {
14937            hide_hover(self, cx);
14938        }
14939        if !self
14940            .context_menu
14941            .borrow()
14942            .as_ref()
14943            .is_some_and(|context_menu| context_menu.focused(window, cx))
14944        {
14945            self.hide_context_menu(window, cx);
14946        }
14947        self.discard_inline_completion(false, cx);
14948        cx.emit(EditorEvent::Blurred);
14949        cx.notify();
14950    }
14951
14952    pub fn register_action<A: Action>(
14953        &mut self,
14954        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14955    ) -> Subscription {
14956        let id = self.next_editor_action_id.post_inc();
14957        let listener = Arc::new(listener);
14958        self.editor_actions.borrow_mut().insert(
14959            id,
14960            Box::new(move |window, _| {
14961                let listener = listener.clone();
14962                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14963                    let action = action.downcast_ref().unwrap();
14964                    if phase == DispatchPhase::Bubble {
14965                        listener(action, window, cx)
14966                    }
14967                })
14968            }),
14969        );
14970
14971        let editor_actions = self.editor_actions.clone();
14972        Subscription::new(move || {
14973            editor_actions.borrow_mut().remove(&id);
14974        })
14975    }
14976
14977    pub fn file_header_size(&self) -> u32 {
14978        FILE_HEADER_HEIGHT
14979    }
14980
14981    pub fn revert(
14982        &mut self,
14983        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14984        window: &mut Window,
14985        cx: &mut Context<Self>,
14986    ) {
14987        self.buffer().update(cx, |multi_buffer, cx| {
14988            for (buffer_id, changes) in revert_changes {
14989                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14990                    buffer.update(cx, |buffer, cx| {
14991                        buffer.edit(
14992                            changes.into_iter().map(|(range, text)| {
14993                                (range, text.to_string().map(Arc::<str>::from))
14994                            }),
14995                            None,
14996                            cx,
14997                        );
14998                    });
14999                }
15000            }
15001        });
15002        self.change_selections(None, window, cx, |selections| selections.refresh());
15003    }
15004
15005    pub fn to_pixel_point(
15006        &self,
15007        source: multi_buffer::Anchor,
15008        editor_snapshot: &EditorSnapshot,
15009        window: &mut Window,
15010    ) -> Option<gpui::Point<Pixels>> {
15011        let source_point = source.to_display_point(editor_snapshot);
15012        self.display_to_pixel_point(source_point, editor_snapshot, window)
15013    }
15014
15015    pub fn display_to_pixel_point(
15016        &self,
15017        source: DisplayPoint,
15018        editor_snapshot: &EditorSnapshot,
15019        window: &mut Window,
15020    ) -> Option<gpui::Point<Pixels>> {
15021        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
15022        let text_layout_details = self.text_layout_details(window);
15023        let scroll_top = text_layout_details
15024            .scroll_anchor
15025            .scroll_position(editor_snapshot)
15026            .y;
15027
15028        if source.row().as_f32() < scroll_top.floor() {
15029            return None;
15030        }
15031        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
15032        let source_y = line_height * (source.row().as_f32() - scroll_top);
15033        Some(gpui::Point::new(source_x, source_y))
15034    }
15035
15036    pub fn has_visible_completions_menu(&self) -> bool {
15037        !self.edit_prediction_preview_is_active()
15038            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
15039                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
15040            })
15041    }
15042
15043    pub fn register_addon<T: Addon>(&mut self, instance: T) {
15044        self.addons
15045            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
15046    }
15047
15048    pub fn unregister_addon<T: Addon>(&mut self) {
15049        self.addons.remove(&std::any::TypeId::of::<T>());
15050    }
15051
15052    pub fn addon<T: Addon>(&self) -> Option<&T> {
15053        let type_id = std::any::TypeId::of::<T>();
15054        self.addons
15055            .get(&type_id)
15056            .and_then(|item| item.to_any().downcast_ref::<T>())
15057    }
15058
15059    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
15060        let text_layout_details = self.text_layout_details(window);
15061        let style = &text_layout_details.editor_style;
15062        let font_id = window.text_system().resolve_font(&style.text.font());
15063        let font_size = style.text.font_size.to_pixels(window.rem_size());
15064        let line_height = style.text.line_height_in_pixels(window.rem_size());
15065        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
15066
15067        gpui::Size::new(em_width, line_height)
15068    }
15069
15070    pub fn wait_for_diff_to_load(&self) -> Option<Shared<Task<()>>> {
15071        self.load_diff_task.clone()
15072    }
15073
15074    fn read_selections_from_db(
15075        &mut self,
15076        item_id: u64,
15077        workspace_id: WorkspaceId,
15078        window: &mut Window,
15079        cx: &mut Context<Editor>,
15080    ) {
15081        if !self.is_singleton(cx)
15082            || WorkspaceSettings::get(None, cx).restore_on_startup == RestoreOnStartupBehavior::None
15083        {
15084            return;
15085        }
15086        let Some(selections) = DB.get_editor_selections(item_id, workspace_id).log_err() else {
15087            return;
15088        };
15089        if selections.is_empty() {
15090            return;
15091        }
15092
15093        let snapshot = self.buffer.read(cx).snapshot(cx);
15094        self.change_selections(None, window, cx, |s| {
15095            s.select_ranges(selections.into_iter().map(|(start, end)| {
15096                snapshot.clip_offset(start, Bias::Left)..snapshot.clip_offset(end, Bias::Right)
15097            }));
15098        });
15099    }
15100}
15101
15102fn get_uncommitted_diff_for_buffer(
15103    project: &Entity<Project>,
15104    buffers: impl IntoIterator<Item = Entity<Buffer>>,
15105    buffer: Entity<MultiBuffer>,
15106    cx: &mut App,
15107) -> Task<()> {
15108    let mut tasks = Vec::new();
15109    project.update(cx, |project, cx| {
15110        for buffer in buffers {
15111            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
15112        }
15113    });
15114    cx.spawn(|mut cx| async move {
15115        let diffs = futures::future::join_all(tasks).await;
15116        buffer
15117            .update(&mut cx, |buffer, cx| {
15118                for diff in diffs.into_iter().flatten() {
15119                    buffer.add_diff(diff, cx);
15120                }
15121            })
15122            .ok();
15123    })
15124}
15125
15126fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
15127    let tab_size = tab_size.get() as usize;
15128    let mut width = offset;
15129
15130    for ch in text.chars() {
15131        width += if ch == '\t' {
15132            tab_size - (width % tab_size)
15133        } else {
15134            1
15135        };
15136    }
15137
15138    width - offset
15139}
15140
15141#[cfg(test)]
15142mod tests {
15143    use super::*;
15144
15145    #[test]
15146    fn test_string_size_with_expanded_tabs() {
15147        let nz = |val| NonZeroU32::new(val).unwrap();
15148        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
15149        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
15150        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
15151        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
15152        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
15153        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
15154        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
15155        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
15156    }
15157}
15158
15159/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
15160struct WordBreakingTokenizer<'a> {
15161    input: &'a str,
15162}
15163
15164impl<'a> WordBreakingTokenizer<'a> {
15165    fn new(input: &'a str) -> Self {
15166        Self { input }
15167    }
15168}
15169
15170fn is_char_ideographic(ch: char) -> bool {
15171    use unicode_script::Script::*;
15172    use unicode_script::UnicodeScript;
15173    matches!(ch.script(), Han | Tangut | Yi)
15174}
15175
15176fn is_grapheme_ideographic(text: &str) -> bool {
15177    text.chars().any(is_char_ideographic)
15178}
15179
15180fn is_grapheme_whitespace(text: &str) -> bool {
15181    text.chars().any(|x| x.is_whitespace())
15182}
15183
15184fn should_stay_with_preceding_ideograph(text: &str) -> bool {
15185    text.chars().next().map_or(false, |ch| {
15186        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
15187    })
15188}
15189
15190#[derive(PartialEq, Eq, Debug, Clone, Copy)]
15191struct WordBreakToken<'a> {
15192    token: &'a str,
15193    grapheme_len: usize,
15194    is_whitespace: bool,
15195}
15196
15197impl<'a> Iterator for WordBreakingTokenizer<'a> {
15198    /// Yields a span, the count of graphemes in the token, and whether it was
15199    /// whitespace. Note that it also breaks at word boundaries.
15200    type Item = WordBreakToken<'a>;
15201
15202    fn next(&mut self) -> Option<Self::Item> {
15203        use unicode_segmentation::UnicodeSegmentation;
15204        if self.input.is_empty() {
15205            return None;
15206        }
15207
15208        let mut iter = self.input.graphemes(true).peekable();
15209        let mut offset = 0;
15210        let mut graphemes = 0;
15211        if let Some(first_grapheme) = iter.next() {
15212            let is_whitespace = is_grapheme_whitespace(first_grapheme);
15213            offset += first_grapheme.len();
15214            graphemes += 1;
15215            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
15216                if let Some(grapheme) = iter.peek().copied() {
15217                    if should_stay_with_preceding_ideograph(grapheme) {
15218                        offset += grapheme.len();
15219                        graphemes += 1;
15220                    }
15221                }
15222            } else {
15223                let mut words = self.input[offset..].split_word_bound_indices().peekable();
15224                let mut next_word_bound = words.peek().copied();
15225                if next_word_bound.map_or(false, |(i, _)| i == 0) {
15226                    next_word_bound = words.next();
15227                }
15228                while let Some(grapheme) = iter.peek().copied() {
15229                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
15230                        break;
15231                    };
15232                    if is_grapheme_whitespace(grapheme) != is_whitespace {
15233                        break;
15234                    };
15235                    offset += grapheme.len();
15236                    graphemes += 1;
15237                    iter.next();
15238                }
15239            }
15240            let token = &self.input[..offset];
15241            self.input = &self.input[offset..];
15242            if is_whitespace {
15243                Some(WordBreakToken {
15244                    token: " ",
15245                    grapheme_len: 1,
15246                    is_whitespace: true,
15247                })
15248            } else {
15249                Some(WordBreakToken {
15250                    token,
15251                    grapheme_len: graphemes,
15252                    is_whitespace: false,
15253                })
15254            }
15255        } else {
15256            None
15257        }
15258    }
15259}
15260
15261#[test]
15262fn test_word_breaking_tokenizer() {
15263    let tests: &[(&str, &[(&str, usize, bool)])] = &[
15264        ("", &[]),
15265        ("  ", &[(" ", 1, true)]),
15266        ("Ʒ", &[("Ʒ", 1, false)]),
15267        ("Ǽ", &[("Ǽ", 1, false)]),
15268        ("", &[("", 1, false)]),
15269        ("⋑⋑", &[("⋑⋑", 2, false)]),
15270        (
15271            "原理,进而",
15272            &[
15273                ("", 1, false),
15274                ("理,", 2, false),
15275                ("", 1, false),
15276                ("", 1, false),
15277            ],
15278        ),
15279        (
15280            "hello world",
15281            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
15282        ),
15283        (
15284            "hello, world",
15285            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
15286        ),
15287        (
15288            "  hello world",
15289            &[
15290                (" ", 1, true),
15291                ("hello", 5, false),
15292                (" ", 1, true),
15293                ("world", 5, false),
15294            ],
15295        ),
15296        (
15297            "这是什么 \n 钢笔",
15298            &[
15299                ("", 1, false),
15300                ("", 1, false),
15301                ("", 1, false),
15302                ("", 1, false),
15303                (" ", 1, true),
15304                ("", 1, false),
15305                ("", 1, false),
15306            ],
15307        ),
15308        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
15309    ];
15310
15311    for (input, result) in tests {
15312        assert_eq!(
15313            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
15314            result
15315                .iter()
15316                .copied()
15317                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
15318                    token,
15319                    grapheme_len,
15320                    is_whitespace,
15321                })
15322                .collect::<Vec<_>>()
15323        );
15324    }
15325}
15326
15327fn wrap_with_prefix(
15328    line_prefix: String,
15329    unwrapped_text: String,
15330    wrap_column: usize,
15331    tab_size: NonZeroU32,
15332) -> String {
15333    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
15334    let mut wrapped_text = String::new();
15335    let mut current_line = line_prefix.clone();
15336
15337    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
15338    let mut current_line_len = line_prefix_len;
15339    for WordBreakToken {
15340        token,
15341        grapheme_len,
15342        is_whitespace,
15343    } in tokenizer
15344    {
15345        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
15346            wrapped_text.push_str(current_line.trim_end());
15347            wrapped_text.push('\n');
15348            current_line.truncate(line_prefix.len());
15349            current_line_len = line_prefix_len;
15350            if !is_whitespace {
15351                current_line.push_str(token);
15352                current_line_len += grapheme_len;
15353            }
15354        } else if !is_whitespace {
15355            current_line.push_str(token);
15356            current_line_len += grapheme_len;
15357        } else if current_line_len != line_prefix_len {
15358            current_line.push(' ');
15359            current_line_len += 1;
15360        }
15361    }
15362
15363    if !current_line.is_empty() {
15364        wrapped_text.push_str(&current_line);
15365    }
15366    wrapped_text
15367}
15368
15369#[test]
15370fn test_wrap_with_prefix() {
15371    assert_eq!(
15372        wrap_with_prefix(
15373            "# ".to_string(),
15374            "abcdefg".to_string(),
15375            4,
15376            NonZeroU32::new(4).unwrap()
15377        ),
15378        "# abcdefg"
15379    );
15380    assert_eq!(
15381        wrap_with_prefix(
15382            "".to_string(),
15383            "\thello world".to_string(),
15384            8,
15385            NonZeroU32::new(4).unwrap()
15386        ),
15387        "hello\nworld"
15388    );
15389    assert_eq!(
15390        wrap_with_prefix(
15391            "// ".to_string(),
15392            "xx \nyy zz aa bb cc".to_string(),
15393            12,
15394            NonZeroU32::new(4).unwrap()
15395        ),
15396        "// xx yy zz\n// aa bb cc"
15397    );
15398    assert_eq!(
15399        wrap_with_prefix(
15400            String::new(),
15401            "这是什么 \n 钢笔".to_string(),
15402            3,
15403            NonZeroU32::new(4).unwrap()
15404        ),
15405        "这是什\n么 钢\n"
15406    );
15407}
15408
15409pub trait CollaborationHub {
15410    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
15411    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
15412    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
15413}
15414
15415impl CollaborationHub for Entity<Project> {
15416    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
15417        self.read(cx).collaborators()
15418    }
15419
15420    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
15421        self.read(cx).user_store().read(cx).participant_indices()
15422    }
15423
15424    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
15425        let this = self.read(cx);
15426        let user_ids = this.collaborators().values().map(|c| c.user_id);
15427        this.user_store().read_with(cx, |user_store, cx| {
15428            user_store.participant_names(user_ids, cx)
15429        })
15430    }
15431}
15432
15433pub trait SemanticsProvider {
15434    fn hover(
15435        &self,
15436        buffer: &Entity<Buffer>,
15437        position: text::Anchor,
15438        cx: &mut App,
15439    ) -> Option<Task<Vec<project::Hover>>>;
15440
15441    fn inlay_hints(
15442        &self,
15443        buffer_handle: Entity<Buffer>,
15444        range: Range<text::Anchor>,
15445        cx: &mut App,
15446    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
15447
15448    fn resolve_inlay_hint(
15449        &self,
15450        hint: InlayHint,
15451        buffer_handle: Entity<Buffer>,
15452        server_id: LanguageServerId,
15453        cx: &mut App,
15454    ) -> Option<Task<anyhow::Result<InlayHint>>>;
15455
15456    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool;
15457
15458    fn document_highlights(
15459        &self,
15460        buffer: &Entity<Buffer>,
15461        position: text::Anchor,
15462        cx: &mut App,
15463    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
15464
15465    fn definitions(
15466        &self,
15467        buffer: &Entity<Buffer>,
15468        position: text::Anchor,
15469        kind: GotoDefinitionKind,
15470        cx: &mut App,
15471    ) -> Option<Task<Result<Vec<LocationLink>>>>;
15472
15473    fn range_for_rename(
15474        &self,
15475        buffer: &Entity<Buffer>,
15476        position: text::Anchor,
15477        cx: &mut App,
15478    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
15479
15480    fn perform_rename(
15481        &self,
15482        buffer: &Entity<Buffer>,
15483        position: text::Anchor,
15484        new_name: String,
15485        cx: &mut App,
15486    ) -> Option<Task<Result<ProjectTransaction>>>;
15487}
15488
15489pub trait CompletionProvider {
15490    fn completions(
15491        &self,
15492        buffer: &Entity<Buffer>,
15493        buffer_position: text::Anchor,
15494        trigger: CompletionContext,
15495        window: &mut Window,
15496        cx: &mut Context<Editor>,
15497    ) -> Task<Result<Vec<Completion>>>;
15498
15499    fn resolve_completions(
15500        &self,
15501        buffer: Entity<Buffer>,
15502        completion_indices: Vec<usize>,
15503        completions: Rc<RefCell<Box<[Completion]>>>,
15504        cx: &mut Context<Editor>,
15505    ) -> Task<Result<bool>>;
15506
15507    fn apply_additional_edits_for_completion(
15508        &self,
15509        _buffer: Entity<Buffer>,
15510        _completions: Rc<RefCell<Box<[Completion]>>>,
15511        _completion_index: usize,
15512        _push_to_history: bool,
15513        _cx: &mut Context<Editor>,
15514    ) -> Task<Result<Option<language::Transaction>>> {
15515        Task::ready(Ok(None))
15516    }
15517
15518    fn is_completion_trigger(
15519        &self,
15520        buffer: &Entity<Buffer>,
15521        position: language::Anchor,
15522        text: &str,
15523        trigger_in_words: bool,
15524        cx: &mut Context<Editor>,
15525    ) -> bool;
15526
15527    fn sort_completions(&self) -> bool {
15528        true
15529    }
15530}
15531
15532pub trait CodeActionProvider {
15533    fn id(&self) -> Arc<str>;
15534
15535    fn code_actions(
15536        &self,
15537        buffer: &Entity<Buffer>,
15538        range: Range<text::Anchor>,
15539        window: &mut Window,
15540        cx: &mut App,
15541    ) -> Task<Result<Vec<CodeAction>>>;
15542
15543    fn apply_code_action(
15544        &self,
15545        buffer_handle: Entity<Buffer>,
15546        action: CodeAction,
15547        excerpt_id: ExcerptId,
15548        push_to_history: bool,
15549        window: &mut Window,
15550        cx: &mut App,
15551    ) -> Task<Result<ProjectTransaction>>;
15552}
15553
15554impl CodeActionProvider for Entity<Project> {
15555    fn id(&self) -> Arc<str> {
15556        "project".into()
15557    }
15558
15559    fn code_actions(
15560        &self,
15561        buffer: &Entity<Buffer>,
15562        range: Range<text::Anchor>,
15563        _window: &mut Window,
15564        cx: &mut App,
15565    ) -> Task<Result<Vec<CodeAction>>> {
15566        self.update(cx, |project, cx| {
15567            project.code_actions(buffer, range, None, cx)
15568        })
15569    }
15570
15571    fn apply_code_action(
15572        &self,
15573        buffer_handle: Entity<Buffer>,
15574        action: CodeAction,
15575        _excerpt_id: ExcerptId,
15576        push_to_history: bool,
15577        _window: &mut Window,
15578        cx: &mut App,
15579    ) -> Task<Result<ProjectTransaction>> {
15580        self.update(cx, |project, cx| {
15581            project.apply_code_action(buffer_handle, action, push_to_history, cx)
15582        })
15583    }
15584}
15585
15586fn snippet_completions(
15587    project: &Project,
15588    buffer: &Entity<Buffer>,
15589    buffer_position: text::Anchor,
15590    cx: &mut App,
15591) -> Task<Result<Vec<Completion>>> {
15592    let language = buffer.read(cx).language_at(buffer_position);
15593    let language_name = language.as_ref().map(|language| language.lsp_id());
15594    let snippet_store = project.snippets().read(cx);
15595    let snippets = snippet_store.snippets_for(language_name, cx);
15596
15597    if snippets.is_empty() {
15598        return Task::ready(Ok(vec![]));
15599    }
15600    let snapshot = buffer.read(cx).text_snapshot();
15601    let chars: String = snapshot
15602        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15603        .collect();
15604
15605    let scope = language.map(|language| language.default_scope());
15606    let executor = cx.background_executor().clone();
15607
15608    cx.background_spawn(async move {
15609        let classifier = CharClassifier::new(scope).for_completion(true);
15610        let mut last_word = chars
15611            .chars()
15612            .take_while(|c| classifier.is_word(*c))
15613            .collect::<String>();
15614        last_word = last_word.chars().rev().collect();
15615
15616        if last_word.is_empty() {
15617            return Ok(vec![]);
15618        }
15619
15620        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15621        let to_lsp = |point: &text::Anchor| {
15622            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15623            point_to_lsp(end)
15624        };
15625        let lsp_end = to_lsp(&buffer_position);
15626
15627        let candidates = snippets
15628            .iter()
15629            .enumerate()
15630            .flat_map(|(ix, snippet)| {
15631                snippet
15632                    .prefix
15633                    .iter()
15634                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15635            })
15636            .collect::<Vec<StringMatchCandidate>>();
15637
15638        let mut matches = fuzzy::match_strings(
15639            &candidates,
15640            &last_word,
15641            last_word.chars().any(|c| c.is_uppercase()),
15642            100,
15643            &Default::default(),
15644            executor,
15645        )
15646        .await;
15647
15648        // Remove all candidates where the query's start does not match the start of any word in the candidate
15649        if let Some(query_start) = last_word.chars().next() {
15650            matches.retain(|string_match| {
15651                split_words(&string_match.string).any(|word| {
15652                    // Check that the first codepoint of the word as lowercase matches the first
15653                    // codepoint of the query as lowercase
15654                    word.chars()
15655                        .flat_map(|codepoint| codepoint.to_lowercase())
15656                        .zip(query_start.to_lowercase())
15657                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15658                })
15659            });
15660        }
15661
15662        let matched_strings = matches
15663            .into_iter()
15664            .map(|m| m.string)
15665            .collect::<HashSet<_>>();
15666
15667        let result: Vec<Completion> = snippets
15668            .into_iter()
15669            .filter_map(|snippet| {
15670                let matching_prefix = snippet
15671                    .prefix
15672                    .iter()
15673                    .find(|prefix| matched_strings.contains(*prefix))?;
15674                let start = as_offset - last_word.len();
15675                let start = snapshot.anchor_before(start);
15676                let range = start..buffer_position;
15677                let lsp_start = to_lsp(&start);
15678                let lsp_range = lsp::Range {
15679                    start: lsp_start,
15680                    end: lsp_end,
15681                };
15682                Some(Completion {
15683                    old_range: range,
15684                    new_text: snippet.body.clone(),
15685                    resolved: false,
15686                    label: CodeLabel {
15687                        text: matching_prefix.clone(),
15688                        runs: vec![],
15689                        filter_range: 0..matching_prefix.len(),
15690                    },
15691                    server_id: LanguageServerId(usize::MAX),
15692                    documentation: snippet
15693                        .description
15694                        .clone()
15695                        .map(|description| CompletionDocumentation::SingleLine(description.into())),
15696                    lsp_completion: lsp::CompletionItem {
15697                        label: snippet.prefix.first().unwrap().clone(),
15698                        kind: Some(CompletionItemKind::SNIPPET),
15699                        label_details: snippet.description.as_ref().map(|description| {
15700                            lsp::CompletionItemLabelDetails {
15701                                detail: Some(description.clone()),
15702                                description: None,
15703                            }
15704                        }),
15705                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15706                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15707                            lsp::InsertReplaceEdit {
15708                                new_text: snippet.body.clone(),
15709                                insert: lsp_range,
15710                                replace: lsp_range,
15711                            },
15712                        )),
15713                        filter_text: Some(snippet.body.clone()),
15714                        sort_text: Some(char::MAX.to_string()),
15715                        ..Default::default()
15716                    },
15717                    confirm: None,
15718                })
15719            })
15720            .collect();
15721
15722        Ok(result)
15723    })
15724}
15725
15726impl CompletionProvider for Entity<Project> {
15727    fn completions(
15728        &self,
15729        buffer: &Entity<Buffer>,
15730        buffer_position: text::Anchor,
15731        options: CompletionContext,
15732        _window: &mut Window,
15733        cx: &mut Context<Editor>,
15734    ) -> Task<Result<Vec<Completion>>> {
15735        self.update(cx, |project, cx| {
15736            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15737            let project_completions = project.completions(buffer, buffer_position, options, cx);
15738            cx.background_spawn(async move {
15739                let mut completions = project_completions.await?;
15740                let snippets_completions = snippets.await?;
15741                completions.extend(snippets_completions);
15742                Ok(completions)
15743            })
15744        })
15745    }
15746
15747    fn resolve_completions(
15748        &self,
15749        buffer: Entity<Buffer>,
15750        completion_indices: Vec<usize>,
15751        completions: Rc<RefCell<Box<[Completion]>>>,
15752        cx: &mut Context<Editor>,
15753    ) -> Task<Result<bool>> {
15754        self.update(cx, |project, cx| {
15755            project.lsp_store().update(cx, |lsp_store, cx| {
15756                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15757            })
15758        })
15759    }
15760
15761    fn apply_additional_edits_for_completion(
15762        &self,
15763        buffer: Entity<Buffer>,
15764        completions: Rc<RefCell<Box<[Completion]>>>,
15765        completion_index: usize,
15766        push_to_history: bool,
15767        cx: &mut Context<Editor>,
15768    ) -> Task<Result<Option<language::Transaction>>> {
15769        self.update(cx, |project, cx| {
15770            project.lsp_store().update(cx, |lsp_store, cx| {
15771                lsp_store.apply_additional_edits_for_completion(
15772                    buffer,
15773                    completions,
15774                    completion_index,
15775                    push_to_history,
15776                    cx,
15777                )
15778            })
15779        })
15780    }
15781
15782    fn is_completion_trigger(
15783        &self,
15784        buffer: &Entity<Buffer>,
15785        position: language::Anchor,
15786        text: &str,
15787        trigger_in_words: bool,
15788        cx: &mut Context<Editor>,
15789    ) -> bool {
15790        let mut chars = text.chars();
15791        let char = if let Some(char) = chars.next() {
15792            char
15793        } else {
15794            return false;
15795        };
15796        if chars.next().is_some() {
15797            return false;
15798        }
15799
15800        let buffer = buffer.read(cx);
15801        let snapshot = buffer.snapshot();
15802        if !snapshot.settings_at(position, cx).show_completions_on_input {
15803            return false;
15804        }
15805        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15806        if trigger_in_words && classifier.is_word(char) {
15807            return true;
15808        }
15809
15810        buffer.completion_triggers().contains(text)
15811    }
15812}
15813
15814impl SemanticsProvider for Entity<Project> {
15815    fn hover(
15816        &self,
15817        buffer: &Entity<Buffer>,
15818        position: text::Anchor,
15819        cx: &mut App,
15820    ) -> Option<Task<Vec<project::Hover>>> {
15821        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15822    }
15823
15824    fn document_highlights(
15825        &self,
15826        buffer: &Entity<Buffer>,
15827        position: text::Anchor,
15828        cx: &mut App,
15829    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15830        Some(self.update(cx, |project, cx| {
15831            project.document_highlights(buffer, position, cx)
15832        }))
15833    }
15834
15835    fn definitions(
15836        &self,
15837        buffer: &Entity<Buffer>,
15838        position: text::Anchor,
15839        kind: GotoDefinitionKind,
15840        cx: &mut App,
15841    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15842        Some(self.update(cx, |project, cx| match kind {
15843            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15844            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15845            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15846            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15847        }))
15848    }
15849
15850    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &mut App) -> bool {
15851        // TODO: make this work for remote projects
15852        self.update(cx, |this, cx| {
15853            buffer.update(cx, |buffer, cx| {
15854                this.any_language_server_supports_inlay_hints(buffer, cx)
15855            })
15856        })
15857    }
15858
15859    fn inlay_hints(
15860        &self,
15861        buffer_handle: Entity<Buffer>,
15862        range: Range<text::Anchor>,
15863        cx: &mut App,
15864    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15865        Some(self.update(cx, |project, cx| {
15866            project.inlay_hints(buffer_handle, range, cx)
15867        }))
15868    }
15869
15870    fn resolve_inlay_hint(
15871        &self,
15872        hint: InlayHint,
15873        buffer_handle: Entity<Buffer>,
15874        server_id: LanguageServerId,
15875        cx: &mut App,
15876    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15877        Some(self.update(cx, |project, cx| {
15878            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15879        }))
15880    }
15881
15882    fn range_for_rename(
15883        &self,
15884        buffer: &Entity<Buffer>,
15885        position: text::Anchor,
15886        cx: &mut App,
15887    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15888        Some(self.update(cx, |project, cx| {
15889            let buffer = buffer.clone();
15890            let task = project.prepare_rename(buffer.clone(), position, cx);
15891            cx.spawn(|_, mut cx| async move {
15892                Ok(match task.await? {
15893                    PrepareRenameResponse::Success(range) => Some(range),
15894                    PrepareRenameResponse::InvalidPosition => None,
15895                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15896                        // Fallback on using TreeSitter info to determine identifier range
15897                        buffer.update(&mut cx, |buffer, _| {
15898                            let snapshot = buffer.snapshot();
15899                            let (range, kind) = snapshot.surrounding_word(position);
15900                            if kind != Some(CharKind::Word) {
15901                                return None;
15902                            }
15903                            Some(
15904                                snapshot.anchor_before(range.start)
15905                                    ..snapshot.anchor_after(range.end),
15906                            )
15907                        })?
15908                    }
15909                })
15910            })
15911        }))
15912    }
15913
15914    fn perform_rename(
15915        &self,
15916        buffer: &Entity<Buffer>,
15917        position: text::Anchor,
15918        new_name: String,
15919        cx: &mut App,
15920    ) -> Option<Task<Result<ProjectTransaction>>> {
15921        Some(self.update(cx, |project, cx| {
15922            project.perform_rename(buffer.clone(), position, new_name, cx)
15923        }))
15924    }
15925}
15926
15927fn inlay_hint_settings(
15928    location: Anchor,
15929    snapshot: &MultiBufferSnapshot,
15930    cx: &mut Context<Editor>,
15931) -> InlayHintSettings {
15932    let file = snapshot.file_at(location);
15933    let language = snapshot.language_at(location).map(|l| l.name());
15934    language_settings(language, file, cx).inlay_hints
15935}
15936
15937fn consume_contiguous_rows(
15938    contiguous_row_selections: &mut Vec<Selection<Point>>,
15939    selection: &Selection<Point>,
15940    display_map: &DisplaySnapshot,
15941    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15942) -> (MultiBufferRow, MultiBufferRow) {
15943    contiguous_row_selections.push(selection.clone());
15944    let start_row = MultiBufferRow(selection.start.row);
15945    let mut end_row = ending_row(selection, display_map);
15946
15947    while let Some(next_selection) = selections.peek() {
15948        if next_selection.start.row <= end_row.0 {
15949            end_row = ending_row(next_selection, display_map);
15950            contiguous_row_selections.push(selections.next().unwrap().clone());
15951        } else {
15952            break;
15953        }
15954    }
15955    (start_row, end_row)
15956}
15957
15958fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15959    if next_selection.end.column > 0 || next_selection.is_empty() {
15960        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15961    } else {
15962        MultiBufferRow(next_selection.end.row)
15963    }
15964}
15965
15966impl EditorSnapshot {
15967    pub fn remote_selections_in_range<'a>(
15968        &'a self,
15969        range: &'a Range<Anchor>,
15970        collaboration_hub: &dyn CollaborationHub,
15971        cx: &'a App,
15972    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15973        let participant_names = collaboration_hub.user_names(cx);
15974        let participant_indices = collaboration_hub.user_participant_indices(cx);
15975        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15976        let collaborators_by_replica_id = collaborators_by_peer_id
15977            .iter()
15978            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15979            .collect::<HashMap<_, _>>();
15980        self.buffer_snapshot
15981            .selections_in_range(range, false)
15982            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15983                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15984                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15985                let user_name = participant_names.get(&collaborator.user_id).cloned();
15986                Some(RemoteSelection {
15987                    replica_id,
15988                    selection,
15989                    cursor_shape,
15990                    line_mode,
15991                    participant_index,
15992                    peer_id: collaborator.peer_id,
15993                    user_name,
15994                })
15995            })
15996    }
15997
15998    pub fn hunks_for_ranges(
15999        &self,
16000        ranges: impl Iterator<Item = Range<Point>>,
16001    ) -> Vec<MultiBufferDiffHunk> {
16002        let mut hunks = Vec::new();
16003        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
16004            HashMap::default();
16005        for query_range in ranges {
16006            let query_rows =
16007                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
16008            for hunk in self.buffer_snapshot.diff_hunks_in_range(
16009                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
16010            ) {
16011                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
16012                // when the caret is just above or just below the deleted hunk.
16013                let allow_adjacent = hunk.status().is_removed();
16014                let related_to_selection = if allow_adjacent {
16015                    hunk.row_range.overlaps(&query_rows)
16016                        || hunk.row_range.start == query_rows.end
16017                        || hunk.row_range.end == query_rows.start
16018                } else {
16019                    hunk.row_range.overlaps(&query_rows)
16020                };
16021                if related_to_selection {
16022                    if !processed_buffer_rows
16023                        .entry(hunk.buffer_id)
16024                        .or_default()
16025                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
16026                    {
16027                        continue;
16028                    }
16029                    hunks.push(hunk);
16030                }
16031            }
16032        }
16033
16034        hunks
16035    }
16036
16037    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
16038        self.display_snapshot.buffer_snapshot.language_at(position)
16039    }
16040
16041    pub fn is_focused(&self) -> bool {
16042        self.is_focused
16043    }
16044
16045    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
16046        self.placeholder_text.as_ref()
16047    }
16048
16049    pub fn scroll_position(&self) -> gpui::Point<f32> {
16050        self.scroll_anchor.scroll_position(&self.display_snapshot)
16051    }
16052
16053    fn gutter_dimensions(
16054        &self,
16055        font_id: FontId,
16056        font_size: Pixels,
16057        max_line_number_width: Pixels,
16058        cx: &App,
16059    ) -> Option<GutterDimensions> {
16060        if !self.show_gutter {
16061            return None;
16062        }
16063
16064        let descent = cx.text_system().descent(font_id, font_size);
16065        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
16066        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
16067
16068        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
16069            matches!(
16070                ProjectSettings::get_global(cx).git.git_gutter,
16071                Some(GitGutterSetting::TrackedFiles)
16072            )
16073        });
16074        let gutter_settings = EditorSettings::get_global(cx).gutter;
16075        let show_line_numbers = self
16076            .show_line_numbers
16077            .unwrap_or(gutter_settings.line_numbers);
16078        let line_gutter_width = if show_line_numbers {
16079            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
16080            let min_width_for_number_on_gutter = em_advance * 4.0;
16081            max_line_number_width.max(min_width_for_number_on_gutter)
16082        } else {
16083            0.0.into()
16084        };
16085
16086        let show_code_actions = self
16087            .show_code_actions
16088            .unwrap_or(gutter_settings.code_actions);
16089
16090        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
16091
16092        let git_blame_entries_width =
16093            self.git_blame_gutter_max_author_length
16094                .map(|max_author_length| {
16095                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
16096
16097                    /// The number of characters to dedicate to gaps and margins.
16098                    const SPACING_WIDTH: usize = 4;
16099
16100                    let max_char_count = max_author_length
16101                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
16102                        + ::git::SHORT_SHA_LENGTH
16103                        + MAX_RELATIVE_TIMESTAMP.len()
16104                        + SPACING_WIDTH;
16105
16106                    em_advance * max_char_count
16107                });
16108
16109        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
16110        left_padding += if show_code_actions || show_runnables {
16111            em_width * 3.0
16112        } else if show_git_gutter && show_line_numbers {
16113            em_width * 2.0
16114        } else if show_git_gutter || show_line_numbers {
16115            em_width
16116        } else {
16117            px(0.)
16118        };
16119
16120        let right_padding = if gutter_settings.folds && show_line_numbers {
16121            em_width * 4.0
16122        } else if gutter_settings.folds {
16123            em_width * 3.0
16124        } else if show_line_numbers {
16125            em_width
16126        } else {
16127            px(0.)
16128        };
16129
16130        Some(GutterDimensions {
16131            left_padding,
16132            right_padding,
16133            width: line_gutter_width + left_padding + right_padding,
16134            margin: -descent,
16135            git_blame_entries_width,
16136        })
16137    }
16138
16139    pub fn render_crease_toggle(
16140        &self,
16141        buffer_row: MultiBufferRow,
16142        row_contains_cursor: bool,
16143        editor: Entity<Editor>,
16144        window: &mut Window,
16145        cx: &mut App,
16146    ) -> Option<AnyElement> {
16147        let folded = self.is_line_folded(buffer_row);
16148        let mut is_foldable = false;
16149
16150        if let Some(crease) = self
16151            .crease_snapshot
16152            .query_row(buffer_row, &self.buffer_snapshot)
16153        {
16154            is_foldable = true;
16155            match crease {
16156                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
16157                    if let Some(render_toggle) = render_toggle {
16158                        let toggle_callback =
16159                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
16160                                if folded {
16161                                    editor.update(cx, |editor, cx| {
16162                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
16163                                    });
16164                                } else {
16165                                    editor.update(cx, |editor, cx| {
16166                                        editor.unfold_at(
16167                                            &crate::UnfoldAt { buffer_row },
16168                                            window,
16169                                            cx,
16170                                        )
16171                                    });
16172                                }
16173                            });
16174                        return Some((render_toggle)(
16175                            buffer_row,
16176                            folded,
16177                            toggle_callback,
16178                            window,
16179                            cx,
16180                        ));
16181                    }
16182                }
16183            }
16184        }
16185
16186        is_foldable |= self.starts_indent(buffer_row);
16187
16188        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
16189            Some(
16190                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
16191                    .toggle_state(folded)
16192                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
16193                        if folded {
16194                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
16195                        } else {
16196                            this.fold_at(&FoldAt { buffer_row }, window, cx);
16197                        }
16198                    }))
16199                    .into_any_element(),
16200            )
16201        } else {
16202            None
16203        }
16204    }
16205
16206    pub fn render_crease_trailer(
16207        &self,
16208        buffer_row: MultiBufferRow,
16209        window: &mut Window,
16210        cx: &mut App,
16211    ) -> Option<AnyElement> {
16212        let folded = self.is_line_folded(buffer_row);
16213        if let Crease::Inline { render_trailer, .. } = self
16214            .crease_snapshot
16215            .query_row(buffer_row, &self.buffer_snapshot)?
16216        {
16217            let render_trailer = render_trailer.as_ref()?;
16218            Some(render_trailer(buffer_row, folded, window, cx))
16219        } else {
16220            None
16221        }
16222    }
16223}
16224
16225impl Deref for EditorSnapshot {
16226    type Target = DisplaySnapshot;
16227
16228    fn deref(&self) -> &Self::Target {
16229        &self.display_snapshot
16230    }
16231}
16232
16233#[derive(Clone, Debug, PartialEq, Eq)]
16234pub enum EditorEvent {
16235    InputIgnored {
16236        text: Arc<str>,
16237    },
16238    InputHandled {
16239        utf16_range_to_replace: Option<Range<isize>>,
16240        text: Arc<str>,
16241    },
16242    ExcerptsAdded {
16243        buffer: Entity<Buffer>,
16244        predecessor: ExcerptId,
16245        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
16246    },
16247    ExcerptsRemoved {
16248        ids: Vec<ExcerptId>,
16249    },
16250    BufferFoldToggled {
16251        ids: Vec<ExcerptId>,
16252        folded: bool,
16253    },
16254    ExcerptsEdited {
16255        ids: Vec<ExcerptId>,
16256    },
16257    ExcerptsExpanded {
16258        ids: Vec<ExcerptId>,
16259    },
16260    BufferEdited,
16261    Edited {
16262        transaction_id: clock::Lamport,
16263    },
16264    Reparsed(BufferId),
16265    Focused,
16266    FocusedIn,
16267    Blurred,
16268    DirtyChanged,
16269    Saved,
16270    TitleChanged,
16271    DiffBaseChanged,
16272    SelectionsChanged {
16273        local: bool,
16274    },
16275    ScrollPositionChanged {
16276        local: bool,
16277        autoscroll: bool,
16278    },
16279    Closed,
16280    TransactionUndone {
16281        transaction_id: clock::Lamport,
16282    },
16283    TransactionBegun {
16284        transaction_id: clock::Lamport,
16285    },
16286    Reloaded,
16287    CursorShapeChanged,
16288}
16289
16290impl EventEmitter<EditorEvent> for Editor {}
16291
16292impl Focusable for Editor {
16293    fn focus_handle(&self, _cx: &App) -> FocusHandle {
16294        self.focus_handle.clone()
16295    }
16296}
16297
16298impl Render for Editor {
16299    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
16300        let settings = ThemeSettings::get_global(cx);
16301
16302        let mut text_style = match self.mode {
16303            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
16304                color: cx.theme().colors().editor_foreground,
16305                font_family: settings.ui_font.family.clone(),
16306                font_features: settings.ui_font.features.clone(),
16307                font_fallbacks: settings.ui_font.fallbacks.clone(),
16308                font_size: rems(0.875).into(),
16309                font_weight: settings.ui_font.weight,
16310                line_height: relative(settings.buffer_line_height.value()),
16311                ..Default::default()
16312            },
16313            EditorMode::Full => TextStyle {
16314                color: cx.theme().colors().editor_foreground,
16315                font_family: settings.buffer_font.family.clone(),
16316                font_features: settings.buffer_font.features.clone(),
16317                font_fallbacks: settings.buffer_font.fallbacks.clone(),
16318                font_size: settings.buffer_font_size(cx).into(),
16319                font_weight: settings.buffer_font.weight,
16320                line_height: relative(settings.buffer_line_height.value()),
16321                ..Default::default()
16322            },
16323        };
16324        if let Some(text_style_refinement) = &self.text_style_refinement {
16325            text_style.refine(text_style_refinement)
16326        }
16327
16328        let background = match self.mode {
16329            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
16330            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
16331            EditorMode::Full => cx.theme().colors().editor_background,
16332        };
16333
16334        EditorElement::new(
16335            &cx.entity(),
16336            EditorStyle {
16337                background,
16338                local_player: cx.theme().players().local(),
16339                text: text_style,
16340                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
16341                syntax: cx.theme().syntax().clone(),
16342                status: cx.theme().status().clone(),
16343                inlay_hints_style: make_inlay_hints_style(cx),
16344                inline_completion_styles: make_suggestion_styles(cx),
16345                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
16346            },
16347        )
16348    }
16349}
16350
16351impl EntityInputHandler for Editor {
16352    fn text_for_range(
16353        &mut self,
16354        range_utf16: Range<usize>,
16355        adjusted_range: &mut Option<Range<usize>>,
16356        _: &mut Window,
16357        cx: &mut Context<Self>,
16358    ) -> Option<String> {
16359        let snapshot = self.buffer.read(cx).read(cx);
16360        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
16361        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
16362        if (start.0..end.0) != range_utf16 {
16363            adjusted_range.replace(start.0..end.0);
16364        }
16365        Some(snapshot.text_for_range(start..end).collect())
16366    }
16367
16368    fn selected_text_range(
16369        &mut self,
16370        ignore_disabled_input: bool,
16371        _: &mut Window,
16372        cx: &mut Context<Self>,
16373    ) -> Option<UTF16Selection> {
16374        // Prevent the IME menu from appearing when holding down an alphabetic key
16375        // while input is disabled.
16376        if !ignore_disabled_input && !self.input_enabled {
16377            return None;
16378        }
16379
16380        let selection = self.selections.newest::<OffsetUtf16>(cx);
16381        let range = selection.range();
16382
16383        Some(UTF16Selection {
16384            range: range.start.0..range.end.0,
16385            reversed: selection.reversed,
16386        })
16387    }
16388
16389    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
16390        let snapshot = self.buffer.read(cx).read(cx);
16391        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
16392        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
16393    }
16394
16395    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
16396        self.clear_highlights::<InputComposition>(cx);
16397        self.ime_transaction.take();
16398    }
16399
16400    fn replace_text_in_range(
16401        &mut self,
16402        range_utf16: Option<Range<usize>>,
16403        text: &str,
16404        window: &mut Window,
16405        cx: &mut Context<Self>,
16406    ) {
16407        if !self.input_enabled {
16408            cx.emit(EditorEvent::InputIgnored { text: text.into() });
16409            return;
16410        }
16411
16412        self.transact(window, cx, |this, window, cx| {
16413            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
16414                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16415                Some(this.selection_replacement_ranges(range_utf16, cx))
16416            } else {
16417                this.marked_text_ranges(cx)
16418            };
16419
16420            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
16421                let newest_selection_id = this.selections.newest_anchor().id;
16422                this.selections
16423                    .all::<OffsetUtf16>(cx)
16424                    .iter()
16425                    .zip(ranges_to_replace.iter())
16426                    .find_map(|(selection, range)| {
16427                        if selection.id == newest_selection_id {
16428                            Some(
16429                                (range.start.0 as isize - selection.head().0 as isize)
16430                                    ..(range.end.0 as isize - selection.head().0 as isize),
16431                            )
16432                        } else {
16433                            None
16434                        }
16435                    })
16436            });
16437
16438            cx.emit(EditorEvent::InputHandled {
16439                utf16_range_to_replace: range_to_replace,
16440                text: text.into(),
16441            });
16442
16443            if let Some(new_selected_ranges) = new_selected_ranges {
16444                this.change_selections(None, window, cx, |selections| {
16445                    selections.select_ranges(new_selected_ranges)
16446                });
16447                this.backspace(&Default::default(), window, cx);
16448            }
16449
16450            this.handle_input(text, window, cx);
16451        });
16452
16453        if let Some(transaction) = self.ime_transaction {
16454            self.buffer.update(cx, |buffer, cx| {
16455                buffer.group_until_transaction(transaction, cx);
16456            });
16457        }
16458
16459        self.unmark_text(window, cx);
16460    }
16461
16462    fn replace_and_mark_text_in_range(
16463        &mut self,
16464        range_utf16: Option<Range<usize>>,
16465        text: &str,
16466        new_selected_range_utf16: Option<Range<usize>>,
16467        window: &mut Window,
16468        cx: &mut Context<Self>,
16469    ) {
16470        if !self.input_enabled {
16471            return;
16472        }
16473
16474        let transaction = self.transact(window, cx, |this, window, cx| {
16475            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
16476                let snapshot = this.buffer.read(cx).read(cx);
16477                if let Some(relative_range_utf16) = range_utf16.as_ref() {
16478                    for marked_range in &mut marked_ranges {
16479                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
16480                        marked_range.start.0 += relative_range_utf16.start;
16481                        marked_range.start =
16482                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
16483                        marked_range.end =
16484                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
16485                    }
16486                }
16487                Some(marked_ranges)
16488            } else if let Some(range_utf16) = range_utf16 {
16489                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
16490                Some(this.selection_replacement_ranges(range_utf16, cx))
16491            } else {
16492                None
16493            };
16494
16495            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
16496                let newest_selection_id = this.selections.newest_anchor().id;
16497                this.selections
16498                    .all::<OffsetUtf16>(cx)
16499                    .iter()
16500                    .zip(ranges_to_replace.iter())
16501                    .find_map(|(selection, range)| {
16502                        if selection.id == newest_selection_id {
16503                            Some(
16504                                (range.start.0 as isize - selection.head().0 as isize)
16505                                    ..(range.end.0 as isize - selection.head().0 as isize),
16506                            )
16507                        } else {
16508                            None
16509                        }
16510                    })
16511            });
16512
16513            cx.emit(EditorEvent::InputHandled {
16514                utf16_range_to_replace: range_to_replace,
16515                text: text.into(),
16516            });
16517
16518            if let Some(ranges) = ranges_to_replace {
16519                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
16520            }
16521
16522            let marked_ranges = {
16523                let snapshot = this.buffer.read(cx).read(cx);
16524                this.selections
16525                    .disjoint_anchors()
16526                    .iter()
16527                    .map(|selection| {
16528                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
16529                    })
16530                    .collect::<Vec<_>>()
16531            };
16532
16533            if text.is_empty() {
16534                this.unmark_text(window, cx);
16535            } else {
16536                this.highlight_text::<InputComposition>(
16537                    marked_ranges.clone(),
16538                    HighlightStyle {
16539                        underline: Some(UnderlineStyle {
16540                            thickness: px(1.),
16541                            color: None,
16542                            wavy: false,
16543                        }),
16544                        ..Default::default()
16545                    },
16546                    cx,
16547                );
16548            }
16549
16550            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
16551            let use_autoclose = this.use_autoclose;
16552            let use_auto_surround = this.use_auto_surround;
16553            this.set_use_autoclose(false);
16554            this.set_use_auto_surround(false);
16555            this.handle_input(text, window, cx);
16556            this.set_use_autoclose(use_autoclose);
16557            this.set_use_auto_surround(use_auto_surround);
16558
16559            if let Some(new_selected_range) = new_selected_range_utf16 {
16560                let snapshot = this.buffer.read(cx).read(cx);
16561                let new_selected_ranges = marked_ranges
16562                    .into_iter()
16563                    .map(|marked_range| {
16564                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
16565                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
16566                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
16567                        snapshot.clip_offset_utf16(new_start, Bias::Left)
16568                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
16569                    })
16570                    .collect::<Vec<_>>();
16571
16572                drop(snapshot);
16573                this.change_selections(None, window, cx, |selections| {
16574                    selections.select_ranges(new_selected_ranges)
16575                });
16576            }
16577        });
16578
16579        self.ime_transaction = self.ime_transaction.or(transaction);
16580        if let Some(transaction) = self.ime_transaction {
16581            self.buffer.update(cx, |buffer, cx| {
16582                buffer.group_until_transaction(transaction, cx);
16583            });
16584        }
16585
16586        if self.text_highlights::<InputComposition>(cx).is_none() {
16587            self.ime_transaction.take();
16588        }
16589    }
16590
16591    fn bounds_for_range(
16592        &mut self,
16593        range_utf16: Range<usize>,
16594        element_bounds: gpui::Bounds<Pixels>,
16595        window: &mut Window,
16596        cx: &mut Context<Self>,
16597    ) -> Option<gpui::Bounds<Pixels>> {
16598        let text_layout_details = self.text_layout_details(window);
16599        let gpui::Size {
16600            width: em_width,
16601            height: line_height,
16602        } = self.character_size(window);
16603
16604        let snapshot = self.snapshot(window, cx);
16605        let scroll_position = snapshot.scroll_position();
16606        let scroll_left = scroll_position.x * em_width;
16607
16608        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16609        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16610            + self.gutter_dimensions.width
16611            + self.gutter_dimensions.margin;
16612        let y = line_height * (start.row().as_f32() - scroll_position.y);
16613
16614        Some(Bounds {
16615            origin: element_bounds.origin + point(x, y),
16616            size: size(em_width, line_height),
16617        })
16618    }
16619
16620    fn character_index_for_point(
16621        &mut self,
16622        point: gpui::Point<Pixels>,
16623        _window: &mut Window,
16624        _cx: &mut Context<Self>,
16625    ) -> Option<usize> {
16626        let position_map = self.last_position_map.as_ref()?;
16627        if !position_map.text_hitbox.contains(&point) {
16628            return None;
16629        }
16630        let display_point = position_map.point_for_position(point).previous_valid;
16631        let anchor = position_map
16632            .snapshot
16633            .display_point_to_anchor(display_point, Bias::Left);
16634        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16635        Some(utf16_offset.0)
16636    }
16637}
16638
16639trait SelectionExt {
16640    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16641    fn spanned_rows(
16642        &self,
16643        include_end_if_at_line_start: bool,
16644        map: &DisplaySnapshot,
16645    ) -> Range<MultiBufferRow>;
16646}
16647
16648impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16649    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16650        let start = self
16651            .start
16652            .to_point(&map.buffer_snapshot)
16653            .to_display_point(map);
16654        let end = self
16655            .end
16656            .to_point(&map.buffer_snapshot)
16657            .to_display_point(map);
16658        if self.reversed {
16659            end..start
16660        } else {
16661            start..end
16662        }
16663    }
16664
16665    fn spanned_rows(
16666        &self,
16667        include_end_if_at_line_start: bool,
16668        map: &DisplaySnapshot,
16669    ) -> Range<MultiBufferRow> {
16670        let start = self.start.to_point(&map.buffer_snapshot);
16671        let mut end = self.end.to_point(&map.buffer_snapshot);
16672        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16673            end.row -= 1;
16674        }
16675
16676        let buffer_start = map.prev_line_boundary(start).0;
16677        let buffer_end = map.next_line_boundary(end).0;
16678        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16679    }
16680}
16681
16682impl<T: InvalidationRegion> InvalidationStack<T> {
16683    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16684    where
16685        S: Clone + ToOffset,
16686    {
16687        while let Some(region) = self.last() {
16688            let all_selections_inside_invalidation_ranges =
16689                if selections.len() == region.ranges().len() {
16690                    selections
16691                        .iter()
16692                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16693                        .all(|(selection, invalidation_range)| {
16694                            let head = selection.head().to_offset(buffer);
16695                            invalidation_range.start <= head && invalidation_range.end >= head
16696                        })
16697                } else {
16698                    false
16699                };
16700
16701            if all_selections_inside_invalidation_ranges {
16702                break;
16703            } else {
16704                self.pop();
16705            }
16706        }
16707    }
16708}
16709
16710impl<T> Default for InvalidationStack<T> {
16711    fn default() -> Self {
16712        Self(Default::default())
16713    }
16714}
16715
16716impl<T> Deref for InvalidationStack<T> {
16717    type Target = Vec<T>;
16718
16719    fn deref(&self) -> &Self::Target {
16720        &self.0
16721    }
16722}
16723
16724impl<T> DerefMut for InvalidationStack<T> {
16725    fn deref_mut(&mut self) -> &mut Self::Target {
16726        &mut self.0
16727    }
16728}
16729
16730impl InvalidationRegion for SnippetState {
16731    fn ranges(&self) -> &[Range<Anchor>] {
16732        &self.ranges[self.active_index]
16733    }
16734}
16735
16736pub fn diagnostic_block_renderer(
16737    diagnostic: Diagnostic,
16738    max_message_rows: Option<u8>,
16739    allow_closing: bool,
16740    _is_valid: bool,
16741) -> RenderBlock {
16742    let (text_without_backticks, code_ranges) =
16743        highlight_diagnostic_message(&diagnostic, max_message_rows);
16744
16745    Arc::new(move |cx: &mut BlockContext| {
16746        let group_id: SharedString = cx.block_id.to_string().into();
16747
16748        let mut text_style = cx.window.text_style().clone();
16749        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16750        let theme_settings = ThemeSettings::get_global(cx);
16751        text_style.font_family = theme_settings.buffer_font.family.clone();
16752        text_style.font_style = theme_settings.buffer_font.style;
16753        text_style.font_features = theme_settings.buffer_font.features.clone();
16754        text_style.font_weight = theme_settings.buffer_font.weight;
16755
16756        let multi_line_diagnostic = diagnostic.message.contains('\n');
16757
16758        let buttons = |diagnostic: &Diagnostic| {
16759            if multi_line_diagnostic {
16760                v_flex()
16761            } else {
16762                h_flex()
16763            }
16764            .when(allow_closing, |div| {
16765                div.children(diagnostic.is_primary.then(|| {
16766                    IconButton::new("close-block", IconName::XCircle)
16767                        .icon_color(Color::Muted)
16768                        .size(ButtonSize::Compact)
16769                        .style(ButtonStyle::Transparent)
16770                        .visible_on_hover(group_id.clone())
16771                        .on_click(move |_click, window, cx| {
16772                            window.dispatch_action(Box::new(Cancel), cx)
16773                        })
16774                        .tooltip(|window, cx| {
16775                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16776                        })
16777                }))
16778            })
16779            .child(
16780                IconButton::new("copy-block", IconName::Copy)
16781                    .icon_color(Color::Muted)
16782                    .size(ButtonSize::Compact)
16783                    .style(ButtonStyle::Transparent)
16784                    .visible_on_hover(group_id.clone())
16785                    .on_click({
16786                        let message = diagnostic.message.clone();
16787                        move |_click, _, cx| {
16788                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16789                        }
16790                    })
16791                    .tooltip(Tooltip::text("Copy diagnostic message")),
16792            )
16793        };
16794
16795        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16796            AvailableSpace::min_size(),
16797            cx.window,
16798            cx.app,
16799        );
16800
16801        h_flex()
16802            .id(cx.block_id)
16803            .group(group_id.clone())
16804            .relative()
16805            .size_full()
16806            .block_mouse_down()
16807            .pl(cx.gutter_dimensions.width)
16808            .w(cx.max_width - cx.gutter_dimensions.full_width())
16809            .child(
16810                div()
16811                    .flex()
16812                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16813                    .flex_shrink(),
16814            )
16815            .child(buttons(&diagnostic))
16816            .child(div().flex().flex_shrink_0().child(
16817                StyledText::new(text_without_backticks.clone()).with_highlights(
16818                    &text_style,
16819                    code_ranges.iter().map(|range| {
16820                        (
16821                            range.clone(),
16822                            HighlightStyle {
16823                                font_weight: Some(FontWeight::BOLD),
16824                                ..Default::default()
16825                            },
16826                        )
16827                    }),
16828                ),
16829            ))
16830            .into_any_element()
16831    })
16832}
16833
16834fn inline_completion_edit_text(
16835    current_snapshot: &BufferSnapshot,
16836    edits: &[(Range<Anchor>, String)],
16837    edit_preview: &EditPreview,
16838    include_deletions: bool,
16839    cx: &App,
16840) -> HighlightedText {
16841    let edits = edits
16842        .iter()
16843        .map(|(anchor, text)| {
16844            (
16845                anchor.start.text_anchor..anchor.end.text_anchor,
16846                text.clone(),
16847            )
16848        })
16849        .collect::<Vec<_>>();
16850
16851    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16852}
16853
16854pub fn highlight_diagnostic_message(
16855    diagnostic: &Diagnostic,
16856    mut max_message_rows: Option<u8>,
16857) -> (SharedString, Vec<Range<usize>>) {
16858    let mut text_without_backticks = String::new();
16859    let mut code_ranges = Vec::new();
16860
16861    if let Some(source) = &diagnostic.source {
16862        text_without_backticks.push_str(source);
16863        code_ranges.push(0..source.len());
16864        text_without_backticks.push_str(": ");
16865    }
16866
16867    let mut prev_offset = 0;
16868    let mut in_code_block = false;
16869    let has_row_limit = max_message_rows.is_some();
16870    let mut newline_indices = diagnostic
16871        .message
16872        .match_indices('\n')
16873        .filter(|_| has_row_limit)
16874        .map(|(ix, _)| ix)
16875        .fuse()
16876        .peekable();
16877
16878    for (quote_ix, _) in diagnostic
16879        .message
16880        .match_indices('`')
16881        .chain([(diagnostic.message.len(), "")])
16882    {
16883        let mut first_newline_ix = None;
16884        let mut last_newline_ix = None;
16885        while let Some(newline_ix) = newline_indices.peek() {
16886            if *newline_ix < quote_ix {
16887                if first_newline_ix.is_none() {
16888                    first_newline_ix = Some(*newline_ix);
16889                }
16890                last_newline_ix = Some(*newline_ix);
16891
16892                if let Some(rows_left) = &mut max_message_rows {
16893                    if *rows_left == 0 {
16894                        break;
16895                    } else {
16896                        *rows_left -= 1;
16897                    }
16898                }
16899                let _ = newline_indices.next();
16900            } else {
16901                break;
16902            }
16903        }
16904        let prev_len = text_without_backticks.len();
16905        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16906        text_without_backticks.push_str(new_text);
16907        if in_code_block {
16908            code_ranges.push(prev_len..text_without_backticks.len());
16909        }
16910        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16911        in_code_block = !in_code_block;
16912        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16913            text_without_backticks.push_str("...");
16914            break;
16915        }
16916    }
16917
16918    (text_without_backticks.into(), code_ranges)
16919}
16920
16921fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16922    match severity {
16923        DiagnosticSeverity::ERROR => colors.error,
16924        DiagnosticSeverity::WARNING => colors.warning,
16925        DiagnosticSeverity::INFORMATION => colors.info,
16926        DiagnosticSeverity::HINT => colors.info,
16927        _ => colors.ignored,
16928    }
16929}
16930
16931pub fn styled_runs_for_code_label<'a>(
16932    label: &'a CodeLabel,
16933    syntax_theme: &'a theme::SyntaxTheme,
16934) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16935    let fade_out = HighlightStyle {
16936        fade_out: Some(0.35),
16937        ..Default::default()
16938    };
16939
16940    let mut prev_end = label.filter_range.end;
16941    label
16942        .runs
16943        .iter()
16944        .enumerate()
16945        .flat_map(move |(ix, (range, highlight_id))| {
16946            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16947                style
16948            } else {
16949                return Default::default();
16950            };
16951            let mut muted_style = style;
16952            muted_style.highlight(fade_out);
16953
16954            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16955            if range.start >= label.filter_range.end {
16956                if range.start > prev_end {
16957                    runs.push((prev_end..range.start, fade_out));
16958                }
16959                runs.push((range.clone(), muted_style));
16960            } else if range.end <= label.filter_range.end {
16961                runs.push((range.clone(), style));
16962            } else {
16963                runs.push((range.start..label.filter_range.end, style));
16964                runs.push((label.filter_range.end..range.end, muted_style));
16965            }
16966            prev_end = cmp::max(prev_end, range.end);
16967
16968            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16969                runs.push((prev_end..label.text.len(), fade_out));
16970            }
16971
16972            runs
16973        })
16974}
16975
16976pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16977    let mut prev_index = 0;
16978    let mut prev_codepoint: Option<char> = None;
16979    text.char_indices()
16980        .chain([(text.len(), '\0')])
16981        .filter_map(move |(index, codepoint)| {
16982            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16983            let is_boundary = index == text.len()
16984                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16985                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16986            if is_boundary {
16987                let chunk = &text[prev_index..index];
16988                prev_index = index;
16989                Some(chunk)
16990            } else {
16991                None
16992            }
16993        })
16994}
16995
16996pub trait RangeToAnchorExt: Sized {
16997    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16998
16999    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
17000        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
17001        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
17002    }
17003}
17004
17005impl<T: ToOffset> RangeToAnchorExt for Range<T> {
17006    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
17007        let start_offset = self.start.to_offset(snapshot);
17008        let end_offset = self.end.to_offset(snapshot);
17009        if start_offset == end_offset {
17010            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
17011        } else {
17012            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
17013        }
17014    }
17015}
17016
17017pub trait RowExt {
17018    fn as_f32(&self) -> f32;
17019
17020    fn next_row(&self) -> Self;
17021
17022    fn previous_row(&self) -> Self;
17023
17024    fn minus(&self, other: Self) -> u32;
17025}
17026
17027impl RowExt for DisplayRow {
17028    fn as_f32(&self) -> f32 {
17029        self.0 as f32
17030    }
17031
17032    fn next_row(&self) -> Self {
17033        Self(self.0 + 1)
17034    }
17035
17036    fn previous_row(&self) -> Self {
17037        Self(self.0.saturating_sub(1))
17038    }
17039
17040    fn minus(&self, other: Self) -> u32 {
17041        self.0 - other.0
17042    }
17043}
17044
17045impl RowExt for MultiBufferRow {
17046    fn as_f32(&self) -> f32 {
17047        self.0 as f32
17048    }
17049
17050    fn next_row(&self) -> Self {
17051        Self(self.0 + 1)
17052    }
17053
17054    fn previous_row(&self) -> Self {
17055        Self(self.0.saturating_sub(1))
17056    }
17057
17058    fn minus(&self, other: Self) -> u32 {
17059        self.0 - other.0
17060    }
17061}
17062
17063trait RowRangeExt {
17064    type Row;
17065
17066    fn len(&self) -> usize;
17067
17068    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
17069}
17070
17071impl RowRangeExt for Range<MultiBufferRow> {
17072    type Row = MultiBufferRow;
17073
17074    fn len(&self) -> usize {
17075        (self.end.0 - self.start.0) as usize
17076    }
17077
17078    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
17079        (self.start.0..self.end.0).map(MultiBufferRow)
17080    }
17081}
17082
17083impl RowRangeExt for Range<DisplayRow> {
17084    type Row = DisplayRow;
17085
17086    fn len(&self) -> usize {
17087        (self.end.0 - self.start.0) as usize
17088    }
17089
17090    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
17091        (self.start.0..self.end.0).map(DisplayRow)
17092    }
17093}
17094
17095/// If select range has more than one line, we
17096/// just point the cursor to range.start.
17097fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
17098    if range.start.row == range.end.row {
17099        range
17100    } else {
17101        range.start..range.start
17102    }
17103}
17104pub struct KillRing(ClipboardItem);
17105impl Global for KillRing {}
17106
17107const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
17108
17109fn all_edits_insertions_or_deletions(
17110    edits: &Vec<(Range<Anchor>, String)>,
17111    snapshot: &MultiBufferSnapshot,
17112) -> bool {
17113    let mut all_insertions = true;
17114    let mut all_deletions = true;
17115
17116    for (range, new_text) in edits.iter() {
17117        let range_is_empty = range.to_offset(&snapshot).is_empty();
17118        let text_is_empty = new_text.is_empty();
17119
17120        if range_is_empty != text_is_empty {
17121            if range_is_empty {
17122                all_deletions = false;
17123            } else {
17124                all_insertions = false;
17125            }
17126        } else {
17127            return false;
17128        }
17129
17130        if !all_insertions && !all_deletions {
17131            return false;
17132        }
17133    }
17134    all_insertions || all_deletions
17135}