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