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 blame_entry_tooltip;
   17mod blink_manager;
   18mod clangd_ext;
   19mod code_context_menus;
   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::{OpenExcerpts, OpenExcerptsSplit};
   52use aho_corasick::AhoCorasick;
   53use anyhow::{anyhow, Context as _, Result};
   54use blink_manager::BlinkManager;
   55use client::{Collaborator, ParticipantIndex};
   56use clock::ReplicaId;
   57use collections::{BTreeMap, HashMap, HashSet, VecDeque};
   58use convert_case::{Case, Casing};
   59use display_map::*;
   60pub use display_map::{DisplayPoint, FoldPlaceholder};
   61pub use editor_settings::{
   62    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   63};
   64pub use editor_settings_controls::*;
   65pub use element::{
   66    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   67};
   68use element::{LineWithInvisibles, PositionMap};
   69use futures::{future, FutureExt};
   70use fuzzy::StringMatchCandidate;
   71
   72use code_context_menus::{
   73    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   74    CompletionsMenu, ContextMenuOrigin,
   75};
   76use diff::DiffHunkStatus;
   77use git::blame::GitBlame;
   78use gpui::{
   79    div, impl_actions, linear_color_stop, linear_gradient, point, prelude::*, pulsating_between,
   80    px, relative, size, Action, Animation, AnimationExt, AnyElement, App, AsyncWindowContext,
   81    AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context, DispatchPhase, ElementId,
   82    Entity, EntityInputHandler, EventEmitter, FocusHandle, FocusOutEvent, Focusable, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Modifiers, MouseButton,
   84    MouseDownEvent, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled,
   85    StyledText, Subscription, Task, TextRun, TextStyle, TextStyleRefinement, UTF16Selection,
   86    UnderlineStyle, UniformListScrollHandle, WeakEntity, WeakFocusHandle, Window,
   87};
   88use highlight_matching_bracket::refresh_matching_bracket_highlights;
   89use hover_popover::{hide_hover, HoverState};
   90use indent_guides::ActiveIndentGuidesState;
   91use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   92pub use inline_completion::Direction;
   93use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   94pub use items::MAX_TAB_TITLE_LEN;
   95use itertools::Itertools;
   96use language::{
   97    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
   98    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
   99    CompletionDocumentation, CursorShape, Diagnostic, EditPreview, HighlightedText, IndentKind,
  100    IndentSize, InlineCompletionPreviewMode, Language, OffsetRangeExt, Point, Selection,
  101    SelectionGoal, TextObject, TransactionId, TreeSitterOptions,
  102};
  103use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  104use linked_editing_ranges::refresh_linked_ranges;
  105use mouse_context_menu::MouseContextMenu;
  106pub use proposed_changes_editor::{
  107    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  108};
  109use similar::{ChangeTag, TextDiff};
  110use std::iter::Peekable;
  111use task::{ResolvedTask, TaskTemplate, TaskVariables};
  112
  113use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  114pub use lsp::CompletionContext;
  115use lsp::{
  116    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  117    LanguageServerId, LanguageServerName,
  118};
  119
  120use language::BufferSnapshot;
  121use movement::TextLayoutDetails;
  122pub use multi_buffer::{
  123    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, RowInfo,
  124    ToOffset, ToPoint,
  125};
  126use multi_buffer::{
  127    ExcerptInfo, ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow,
  128    ToOffsetUtf16,
  129};
  130use project::{
  131    lsp_store::{FormatTrigger, LspFormatTarget, OpenLspBufferHandle},
  132    project_settings::{GitGutterSetting, ProjectSettings},
  133    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  134    LspStore, PrepareRenameResponse, Project, ProjectItem, ProjectTransaction, TaskSourceKind,
  135};
  136use rand::prelude::*;
  137use rpc::{proto::*, ErrorExt};
  138use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
  139use selections_collection::{
  140    resolve_selections, MutableSelectionsCollection, SelectionsCollection,
  141};
  142use serde::{Deserialize, Serialize};
  143use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
  144use smallvec::SmallVec;
  145use snippet::Snippet;
  146use std::{
  147    any::TypeId,
  148    borrow::Cow,
  149    cell::RefCell,
  150    cmp::{self, Ordering, Reverse},
  151    mem,
  152    num::NonZeroU32,
  153    ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
  154    path::{Path, PathBuf},
  155    rc::Rc,
  156    sync::Arc,
  157    time::{Duration, Instant},
  158};
  159pub use sum_tree::Bias;
  160use sum_tree::TreeMap;
  161use text::{BufferId, OffsetUtf16, Rope};
  162use theme::{ActiveTheme, PlayerColor, StatusColors, SyntaxTheme, ThemeColors, ThemeSettings};
  163use ui::{
  164    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  165    Tooltip,
  166};
  167use util::{defer, maybe, post_inc, RangeExt, ResultExt, TakeUntilExt, TryFutureExt};
  168use workspace::item::{ItemHandle, PreviewTabsSettings};
  169use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  170use workspace::{
  171    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  172};
  173use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  174
  175use crate::hover_links::{find_url, find_url_from_range};
  176use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  177
  178pub const FILE_HEADER_HEIGHT: u32 = 2;
  179pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  180pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  181pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  182const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  183const MAX_LINE_LEN: usize = 1024;
  184const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  185const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  186pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  187#[doc(hidden)]
  188pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  189
  190pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  191pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  192
  193pub fn render_parsed_markdown(
  194    element_id: impl Into<ElementId>,
  195    parsed: &language::ParsedMarkdown,
  196    editor_style: &EditorStyle,
  197    workspace: Option<WeakEntity<Workspace>>,
  198    cx: &mut App,
  199) -> InteractiveText {
  200    let code_span_background_color = cx
  201        .theme()
  202        .colors()
  203        .editor_document_highlight_read_background;
  204
  205    let highlights = gpui::combine_highlights(
  206        parsed.highlights.iter().filter_map(|(range, highlight)| {
  207            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  208            Some((range.clone(), highlight))
  209        }),
  210        parsed
  211            .regions
  212            .iter()
  213            .zip(&parsed.region_ranges)
  214            .filter_map(|(region, range)| {
  215                if region.code {
  216                    Some((
  217                        range.clone(),
  218                        HighlightStyle {
  219                            background_color: Some(code_span_background_color),
  220                            ..Default::default()
  221                        },
  222                    ))
  223                } else {
  224                    None
  225                }
  226            }),
  227    );
  228
  229    let mut links = Vec::new();
  230    let mut link_ranges = Vec::new();
  231    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  232        if let Some(link) = region.link.clone() {
  233            links.push(link);
  234            link_ranges.push(range.clone());
  235        }
  236    }
  237
  238    InteractiveText::new(
  239        element_id,
  240        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  241    )
  242    .on_click(
  243        link_ranges,
  244        move |clicked_range_ix, window, cx| match &links[clicked_range_ix] {
  245            markdown::Link::Web { url } => cx.open_url(url),
  246            markdown::Link::Path { path } => {
  247                if let Some(workspace) = &workspace {
  248                    _ = workspace.update(cx, |workspace, cx| {
  249                        workspace
  250                            .open_abs_path(path.clone(), false, window, cx)
  251                            .detach();
  252                    });
  253                }
  254            }
  255        },
  256    )
  257}
  258
  259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  260pub enum InlayId {
  261    InlineCompletion(usize),
  262    Hint(usize),
  263}
  264
  265impl InlayId {
  266    fn id(&self) -> usize {
  267        match self {
  268            Self::InlineCompletion(id) => *id,
  269            Self::Hint(id) => *id,
  270        }
  271    }
  272}
  273
  274enum DocumentHighlightRead {}
  275enum DocumentHighlightWrite {}
  276enum InputComposition {}
  277
  278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  279pub enum Navigated {
  280    Yes,
  281    No,
  282}
  283
  284impl Navigated {
  285    pub fn from_bool(yes: bool) -> Navigated {
  286        if yes {
  287            Navigated::Yes
  288        } else {
  289            Navigated::No
  290        }
  291    }
  292}
  293
  294pub fn init_settings(cx: &mut App) {
  295    EditorSettings::register(cx);
  296}
  297
  298pub fn init(cx: &mut App) {
  299    init_settings(cx);
  300
  301    workspace::register_project_item::<Editor>(cx);
  302    workspace::FollowableViewRegistry::register::<Editor>(cx);
  303    workspace::register_serializable_item::<Editor>(cx);
  304
  305    cx.observe_new(
  306        |workspace: &mut Workspace, _: Option<&mut Window>, _cx: &mut Context<Workspace>| {
  307            workspace.register_action(Editor::new_file);
  308            workspace.register_action(Editor::new_file_vertical);
  309            workspace.register_action(Editor::new_file_horizontal);
  310            workspace.register_action(Editor::cancel_language_server_work);
  311        },
  312    )
  313    .detach();
  314
  315    cx.on_action(move |_: &workspace::NewFile, cx| {
  316        let app_state = workspace::AppState::global(cx);
  317        if let Some(app_state) = app_state.upgrade() {
  318            workspace::open_new(
  319                Default::default(),
  320                app_state,
  321                cx,
  322                |workspace, window, cx| {
  323                    Editor::new_file(workspace, &Default::default(), window, cx)
  324                },
  325            )
  326            .detach();
  327        }
  328    });
  329    cx.on_action(move |_: &workspace::NewWindow, cx| {
  330        let app_state = workspace::AppState::global(cx);
  331        if let Some(app_state) = app_state.upgrade() {
  332            workspace::open_new(
  333                Default::default(),
  334                app_state,
  335                cx,
  336                |workspace, window, cx| {
  337                    cx.activate(true);
  338                    Editor::new_file(workspace, &Default::default(), window, cx)
  339                },
  340            )
  341            .detach();
  342        }
  343    });
  344}
  345
  346pub struct SearchWithinRange;
  347
  348trait InvalidationRegion {
  349    fn ranges(&self) -> &[Range<Anchor>];
  350}
  351
  352#[derive(Clone, Debug, PartialEq)]
  353pub enum SelectPhase {
  354    Begin {
  355        position: DisplayPoint,
  356        add: bool,
  357        click_count: usize,
  358    },
  359    BeginColumnar {
  360        position: DisplayPoint,
  361        reset: bool,
  362        goal_column: u32,
  363    },
  364    Extend {
  365        position: DisplayPoint,
  366        click_count: usize,
  367    },
  368    Update {
  369        position: DisplayPoint,
  370        goal_column: u32,
  371        scroll_delta: gpui::Point<f32>,
  372    },
  373    End,
  374}
  375
  376#[derive(Clone, Debug)]
  377pub enum SelectMode {
  378    Character,
  379    Word(Range<Anchor>),
  380    Line(Range<Anchor>),
  381    All,
  382}
  383
  384#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  385pub enum EditorMode {
  386    SingleLine { auto_width: bool },
  387    AutoHeight { max_lines: usize },
  388    Full,
  389}
  390
  391#[derive(Copy, Clone, Debug)]
  392pub enum SoftWrap {
  393    /// Prefer not to wrap at all.
  394    ///
  395    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  396    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  397    GitDiff,
  398    /// Prefer a single line generally, unless an overly long line is encountered.
  399    None,
  400    /// Soft wrap lines that exceed the editor width.
  401    EditorWidth,
  402    /// Soft wrap lines at the preferred line length.
  403    Column(u32),
  404    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  405    Bounded(u32),
  406}
  407
  408#[derive(Clone)]
  409pub struct EditorStyle {
  410    pub background: Hsla,
  411    pub local_player: PlayerColor,
  412    pub text: TextStyle,
  413    pub scrollbar_width: Pixels,
  414    pub syntax: Arc<SyntaxTheme>,
  415    pub status: StatusColors,
  416    pub inlay_hints_style: HighlightStyle,
  417    pub inline_completion_styles: InlineCompletionStyles,
  418    pub unnecessary_code_fade: f32,
  419}
  420
  421impl Default for EditorStyle {
  422    fn default() -> Self {
  423        Self {
  424            background: Hsla::default(),
  425            local_player: PlayerColor::default(),
  426            text: TextStyle::default(),
  427            scrollbar_width: Pixels::default(),
  428            syntax: Default::default(),
  429            // HACK: Status colors don't have a real default.
  430            // We should look into removing the status colors from the editor
  431            // style and retrieve them directly from the theme.
  432            status: StatusColors::dark(),
  433            inlay_hints_style: HighlightStyle::default(),
  434            inline_completion_styles: InlineCompletionStyles {
  435                insertion: HighlightStyle::default(),
  436                whitespace: HighlightStyle::default(),
  437            },
  438            unnecessary_code_fade: Default::default(),
  439        }
  440    }
  441}
  442
  443pub fn make_inlay_hints_style(cx: &mut App) -> HighlightStyle {
  444    let show_background = language_settings::language_settings(None, None, cx)
  445        .inlay_hints
  446        .show_background;
  447
  448    HighlightStyle {
  449        color: Some(cx.theme().status().hint),
  450        background_color: show_background.then(|| cx.theme().status().hint_background),
  451        ..HighlightStyle::default()
  452    }
  453}
  454
  455pub fn make_suggestion_styles(cx: &mut App) -> InlineCompletionStyles {
  456    InlineCompletionStyles {
  457        insertion: HighlightStyle {
  458            color: Some(cx.theme().status().predictive),
  459            ..HighlightStyle::default()
  460        },
  461        whitespace: HighlightStyle {
  462            background_color: Some(cx.theme().status().created_background),
  463            ..HighlightStyle::default()
  464        },
  465    }
  466}
  467
  468type CompletionId = usize;
  469
  470pub(crate) enum EditDisplayMode {
  471    TabAccept,
  472    DiffPopover,
  473    Inline,
  474}
  475
  476enum InlineCompletion {
  477    Edit {
  478        edits: Vec<(Range<Anchor>, String)>,
  479        edit_preview: Option<EditPreview>,
  480        display_mode: EditDisplayMode,
  481        snapshot: BufferSnapshot,
  482    },
  483    Move {
  484        target: Anchor,
  485        range_around_target: Range<text::Anchor>,
  486        snapshot: BufferSnapshot,
  487    },
  488}
  489
  490struct InlineCompletionState {
  491    inlay_ids: Vec<InlayId>,
  492    completion: InlineCompletion,
  493    invalidation_range: Range<Anchor>,
  494}
  495
  496enum InlineCompletionHighlight {}
  497
  498pub enum MenuInlineCompletionsPolicy {
  499    Never,
  500    ByProvider,
  501}
  502
  503#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  504struct EditorActionId(usize);
  505
  506impl EditorActionId {
  507    pub fn post_inc(&mut self) -> Self {
  508        let answer = self.0;
  509
  510        *self = Self(answer + 1);
  511
  512        Self(answer)
  513    }
  514}
  515
  516// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  517// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  518
  519type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  520type GutterHighlight = (fn(&App) -> Hsla, Arc<[Range<Anchor>]>);
  521
  522#[derive(Default)]
  523struct ScrollbarMarkerState {
  524    scrollbar_size: Size<Pixels>,
  525    dirty: bool,
  526    markers: Arc<[PaintQuad]>,
  527    pending_refresh: Option<Task<Result<()>>>,
  528}
  529
  530impl ScrollbarMarkerState {
  531    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  532        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  533    }
  534}
  535
  536#[derive(Clone, Debug)]
  537struct RunnableTasks {
  538    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  539    offset: MultiBufferOffset,
  540    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  541    column: u32,
  542    // Values of all named captures, including those starting with '_'
  543    extra_variables: HashMap<String, String>,
  544    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  545    context_range: Range<BufferOffset>,
  546}
  547
  548impl RunnableTasks {
  549    fn resolve<'a>(
  550        &'a self,
  551        cx: &'a task::TaskContext,
  552    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  553        self.templates.iter().filter_map(|(kind, template)| {
  554            template
  555                .resolve_task(&kind.to_id_base(), cx)
  556                .map(|task| (kind.clone(), task))
  557        })
  558    }
  559}
  560
  561#[derive(Clone)]
  562struct ResolvedTasks {
  563    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  564    position: Anchor,
  565}
  566#[derive(Copy, Clone, Debug)]
  567struct MultiBufferOffset(usize);
  568#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  569struct BufferOffset(usize);
  570
  571// Addons allow storing per-editor state in other crates (e.g. Vim)
  572pub trait Addon: 'static {
  573    fn extend_key_context(&self, _: &mut KeyContext, _: &App) {}
  574
  575    fn render_buffer_header_controls(
  576        &self,
  577        _: &ExcerptInfo,
  578        _: &Window,
  579        _: &App,
  580    ) -> Option<AnyElement> {
  581        None
  582    }
  583
  584    fn to_any(&self) -> &dyn std::any::Any;
  585}
  586
  587#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  588pub enum IsVimMode {
  589    Yes,
  590    No,
  591}
  592
  593/// Zed's primary implementation of text input, allowing users to edit a [`MultiBuffer`].
  594///
  595/// See the [module level documentation](self) for more information.
  596pub struct Editor {
  597    focus_handle: FocusHandle,
  598    last_focused_descendant: Option<WeakFocusHandle>,
  599    /// The text buffer being edited
  600    buffer: Entity<MultiBuffer>,
  601    /// Map of how text in the buffer should be displayed.
  602    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  603    pub display_map: Entity<DisplayMap>,
  604    pub selections: SelectionsCollection,
  605    pub scroll_manager: ScrollManager,
  606    /// When inline assist editors are linked, they all render cursors because
  607    /// typing enters text into each of them, even the ones that aren't focused.
  608    pub(crate) show_cursor_when_unfocused: bool,
  609    columnar_selection_tail: Option<Anchor>,
  610    add_selections_state: Option<AddSelectionsState>,
  611    select_next_state: Option<SelectNextState>,
  612    select_prev_state: Option<SelectNextState>,
  613    selection_history: SelectionHistory,
  614    autoclose_regions: Vec<AutocloseRegion>,
  615    snippet_stack: InvalidationStack<SnippetState>,
  616    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  617    ime_transaction: Option<TransactionId>,
  618    active_diagnostics: Option<ActiveDiagnosticGroup>,
  619    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  620
  621    // TODO: make this a access method
  622    pub project: Option<Entity<Project>>,
  623    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  624    completion_provider: Option<Box<dyn CompletionProvider>>,
  625    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  626    blink_manager: Entity<BlinkManager>,
  627    show_cursor_names: bool,
  628    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  629    pub show_local_selections: bool,
  630    mode: EditorMode,
  631    show_breadcrumbs: bool,
  632    show_gutter: bool,
  633    show_scrollbars: bool,
  634    show_line_numbers: Option<bool>,
  635    use_relative_line_numbers: Option<bool>,
  636    show_git_diff_gutter: Option<bool>,
  637    show_code_actions: Option<bool>,
  638    show_runnables: Option<bool>,
  639    show_wrap_guides: Option<bool>,
  640    show_indent_guides: Option<bool>,
  641    placeholder_text: Option<Arc<str>>,
  642    highlight_order: usize,
  643    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  644    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  645    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  646    scrollbar_marker_state: ScrollbarMarkerState,
  647    active_indent_guides_state: ActiveIndentGuidesState,
  648    nav_history: Option<ItemNavHistory>,
  649    context_menu: RefCell<Option<CodeContextMenu>>,
  650    mouse_context_menu: Option<MouseContextMenu>,
  651    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  652    signature_help_state: SignatureHelpState,
  653    auto_signature_help: Option<bool>,
  654    find_all_references_task_sources: Vec<Anchor>,
  655    next_completion_id: CompletionId,
  656    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  657    code_actions_task: Option<Task<Result<()>>>,
  658    document_highlights_task: Option<Task<()>>,
  659    linked_editing_range_task: Option<Task<Option<()>>>,
  660    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  661    pending_rename: Option<RenameState>,
  662    searchable: bool,
  663    cursor_shape: CursorShape,
  664    current_line_highlight: Option<CurrentLineHighlight>,
  665    collapse_matches: bool,
  666    autoindent_mode: Option<AutoindentMode>,
  667    workspace: Option<(WeakEntity<Workspace>, Option<WorkspaceId>)>,
  668    input_enabled: bool,
  669    use_modal_editing: bool,
  670    read_only: bool,
  671    leader_peer_id: Option<PeerId>,
  672    remote_id: Option<ViewId>,
  673    hover_state: HoverState,
  674    pending_mouse_down: Option<Rc<RefCell<Option<MouseDownEvent>>>>,
  675    gutter_hovered: bool,
  676    hovered_link_state: Option<HoveredLinkState>,
  677    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  678    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  679    active_inline_completion: Option<InlineCompletionState>,
  680    /// Used to prevent flickering as the user types while the menu is open
  681    stale_inline_completion_in_menu: Option<InlineCompletionState>,
  682    // enable_inline_completions is a switch that Vim can use to disable
  683    // edit predictions based on its mode.
  684    show_inline_completions: bool,
  685    show_inline_completions_override: Option<bool>,
  686    menu_inline_completions_policy: MenuInlineCompletionsPolicy,
  687    previewing_inline_completion: bool,
  688    inlay_hint_cache: InlayHintCache,
  689    next_inlay_id: usize,
  690    _subscriptions: Vec<Subscription>,
  691    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  692    gutter_dimensions: GutterDimensions,
  693    style: Option<EditorStyle>,
  694    text_style_refinement: Option<TextStyleRefinement>,
  695    next_editor_action_id: EditorActionId,
  696    editor_actions:
  697        Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut Window, &mut Context<Self>)>>>>,
  698    use_autoclose: bool,
  699    use_auto_surround: bool,
  700    auto_replace_emoji_shortcode: bool,
  701    show_git_blame_gutter: bool,
  702    show_git_blame_inline: bool,
  703    show_git_blame_inline_delay_task: Option<Task<()>>,
  704    git_blame_inline_enabled: bool,
  705    serialize_dirty_buffers: bool,
  706    show_selection_menu: Option<bool>,
  707    blame: Option<Entity<GitBlame>>,
  708    blame_subscription: Option<Subscription>,
  709    custom_context_menu: Option<
  710        Box<
  711            dyn 'static
  712                + Fn(
  713                    &mut Self,
  714                    DisplayPoint,
  715                    &mut Window,
  716                    &mut Context<Self>,
  717                ) -> Option<Entity<ui::ContextMenu>>,
  718        >,
  719    >,
  720    last_bounds: Option<Bounds<Pixels>>,
  721    last_position_map: Option<Rc<PositionMap>>,
  722    expect_bounds_change: Option<Bounds<Pixels>>,
  723    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  724    tasks_update_task: Option<Task<()>>,
  725    in_project_search: bool,
  726    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  727    breadcrumb_header: Option<String>,
  728    focused_block: Option<FocusedBlock>,
  729    next_scroll_position: NextScrollCursorCenterTopBottom,
  730    addons: HashMap<TypeId, Box<dyn Addon>>,
  731    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  732    selection_mark_mode: bool,
  733    toggle_fold_multiple_buffers: Task<()>,
  734    _scroll_cursor_center_top_bottom_task: Task<()>,
  735}
  736
  737#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  738enum NextScrollCursorCenterTopBottom {
  739    #[default]
  740    Center,
  741    Top,
  742    Bottom,
  743}
  744
  745impl NextScrollCursorCenterTopBottom {
  746    fn next(&self) -> Self {
  747        match self {
  748            Self::Center => Self::Top,
  749            Self::Top => Self::Bottom,
  750            Self::Bottom => Self::Center,
  751        }
  752    }
  753}
  754
  755#[derive(Clone)]
  756pub struct EditorSnapshot {
  757    pub mode: EditorMode,
  758    show_gutter: bool,
  759    show_line_numbers: Option<bool>,
  760    show_git_diff_gutter: Option<bool>,
  761    show_code_actions: Option<bool>,
  762    show_runnables: Option<bool>,
  763    git_blame_gutter_max_author_length: Option<usize>,
  764    pub display_snapshot: DisplaySnapshot,
  765    pub placeholder_text: Option<Arc<str>>,
  766    is_focused: bool,
  767    scroll_anchor: ScrollAnchor,
  768    ongoing_scroll: OngoingScroll,
  769    current_line_highlight: CurrentLineHighlight,
  770    gutter_hovered: bool,
  771}
  772
  773const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  774
  775#[derive(Default, Debug, Clone, Copy)]
  776pub struct GutterDimensions {
  777    pub left_padding: Pixels,
  778    pub right_padding: Pixels,
  779    pub width: Pixels,
  780    pub margin: Pixels,
  781    pub git_blame_entries_width: Option<Pixels>,
  782}
  783
  784impl GutterDimensions {
  785    /// The full width of the space taken up by the gutter.
  786    pub fn full_width(&self) -> Pixels {
  787        self.margin + self.width
  788    }
  789
  790    /// The width of the space reserved for the fold indicators,
  791    /// use alongside 'justify_end' and `gutter_width` to
  792    /// right align content with the line numbers
  793    pub fn fold_area_width(&self) -> Pixels {
  794        self.margin + self.right_padding
  795    }
  796}
  797
  798#[derive(Debug)]
  799pub struct RemoteSelection {
  800    pub replica_id: ReplicaId,
  801    pub selection: Selection<Anchor>,
  802    pub cursor_shape: CursorShape,
  803    pub peer_id: PeerId,
  804    pub line_mode: bool,
  805    pub participant_index: Option<ParticipantIndex>,
  806    pub user_name: Option<SharedString>,
  807}
  808
  809#[derive(Clone, Debug)]
  810struct SelectionHistoryEntry {
  811    selections: Arc<[Selection<Anchor>]>,
  812    select_next_state: Option<SelectNextState>,
  813    select_prev_state: Option<SelectNextState>,
  814    add_selections_state: Option<AddSelectionsState>,
  815}
  816
  817enum SelectionHistoryMode {
  818    Normal,
  819    Undoing,
  820    Redoing,
  821}
  822
  823#[derive(Clone, PartialEq, Eq, Hash)]
  824struct HoveredCursor {
  825    replica_id: u16,
  826    selection_id: usize,
  827}
  828
  829impl Default for SelectionHistoryMode {
  830    fn default() -> Self {
  831        Self::Normal
  832    }
  833}
  834
  835#[derive(Default)]
  836struct SelectionHistory {
  837    #[allow(clippy::type_complexity)]
  838    selections_by_transaction:
  839        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  840    mode: SelectionHistoryMode,
  841    undo_stack: VecDeque<SelectionHistoryEntry>,
  842    redo_stack: VecDeque<SelectionHistoryEntry>,
  843}
  844
  845impl SelectionHistory {
  846    fn insert_transaction(
  847        &mut self,
  848        transaction_id: TransactionId,
  849        selections: Arc<[Selection<Anchor>]>,
  850    ) {
  851        self.selections_by_transaction
  852            .insert(transaction_id, (selections, None));
  853    }
  854
  855    #[allow(clippy::type_complexity)]
  856    fn transaction(
  857        &self,
  858        transaction_id: TransactionId,
  859    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  860        self.selections_by_transaction.get(&transaction_id)
  861    }
  862
  863    #[allow(clippy::type_complexity)]
  864    fn transaction_mut(
  865        &mut self,
  866        transaction_id: TransactionId,
  867    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  868        self.selections_by_transaction.get_mut(&transaction_id)
  869    }
  870
  871    fn push(&mut self, entry: SelectionHistoryEntry) {
  872        if !entry.selections.is_empty() {
  873            match self.mode {
  874                SelectionHistoryMode::Normal => {
  875                    self.push_undo(entry);
  876                    self.redo_stack.clear();
  877                }
  878                SelectionHistoryMode::Undoing => self.push_redo(entry),
  879                SelectionHistoryMode::Redoing => self.push_undo(entry),
  880            }
  881        }
  882    }
  883
  884    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  885        if self
  886            .undo_stack
  887            .back()
  888            .map_or(true, |e| e.selections != entry.selections)
  889        {
  890            self.undo_stack.push_back(entry);
  891            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  892                self.undo_stack.pop_front();
  893            }
  894        }
  895    }
  896
  897    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  898        if self
  899            .redo_stack
  900            .back()
  901            .map_or(true, |e| e.selections != entry.selections)
  902        {
  903            self.redo_stack.push_back(entry);
  904            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  905                self.redo_stack.pop_front();
  906            }
  907        }
  908    }
  909}
  910
  911struct RowHighlight {
  912    index: usize,
  913    range: Range<Anchor>,
  914    color: Hsla,
  915    should_autoscroll: bool,
  916}
  917
  918#[derive(Clone, Debug)]
  919struct AddSelectionsState {
  920    above: bool,
  921    stack: Vec<usize>,
  922}
  923
  924#[derive(Clone)]
  925struct SelectNextState {
  926    query: AhoCorasick,
  927    wordwise: bool,
  928    done: bool,
  929}
  930
  931impl std::fmt::Debug for SelectNextState {
  932    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  933        f.debug_struct(std::any::type_name::<Self>())
  934            .field("wordwise", &self.wordwise)
  935            .field("done", &self.done)
  936            .finish()
  937    }
  938}
  939
  940#[derive(Debug)]
  941struct AutocloseRegion {
  942    selection_id: usize,
  943    range: Range<Anchor>,
  944    pair: BracketPair,
  945}
  946
  947#[derive(Debug)]
  948struct SnippetState {
  949    ranges: Vec<Vec<Range<Anchor>>>,
  950    active_index: usize,
  951    choices: Vec<Option<Vec<String>>>,
  952}
  953
  954#[doc(hidden)]
  955pub struct RenameState {
  956    pub range: Range<Anchor>,
  957    pub old_name: Arc<str>,
  958    pub editor: Entity<Editor>,
  959    block_id: CustomBlockId,
  960}
  961
  962struct InvalidationStack<T>(Vec<T>);
  963
  964struct RegisteredInlineCompletionProvider {
  965    provider: Arc<dyn InlineCompletionProviderHandle>,
  966    _subscription: Subscription,
  967}
  968
  969#[derive(Debug)]
  970struct ActiveDiagnosticGroup {
  971    primary_range: Range<Anchor>,
  972    primary_message: String,
  973    group_id: usize,
  974    blocks: HashMap<CustomBlockId, Diagnostic>,
  975    is_valid: bool,
  976}
  977
  978#[derive(Serialize, Deserialize, Clone, Debug)]
  979pub struct ClipboardSelection {
  980    pub len: usize,
  981    pub is_entire_line: bool,
  982    pub first_line_indent: u32,
  983}
  984
  985#[derive(Debug)]
  986pub(crate) struct NavigationData {
  987    cursor_anchor: Anchor,
  988    cursor_position: Point,
  989    scroll_anchor: ScrollAnchor,
  990    scroll_top_row: u32,
  991}
  992
  993#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  994pub enum GotoDefinitionKind {
  995    Symbol,
  996    Declaration,
  997    Type,
  998    Implementation,
  999}
 1000
 1001#[derive(Debug, Clone)]
 1002enum InlayHintRefreshReason {
 1003    Toggle(bool),
 1004    SettingsChange(InlayHintSettings),
 1005    NewLinesShown,
 1006    BufferEdited(HashSet<Arc<Language>>),
 1007    RefreshRequested,
 1008    ExcerptsRemoved(Vec<ExcerptId>),
 1009}
 1010
 1011impl InlayHintRefreshReason {
 1012    fn description(&self) -> &'static str {
 1013        match self {
 1014            Self::Toggle(_) => "toggle",
 1015            Self::SettingsChange(_) => "settings change",
 1016            Self::NewLinesShown => "new lines shown",
 1017            Self::BufferEdited(_) => "buffer edited",
 1018            Self::RefreshRequested => "refresh requested",
 1019            Self::ExcerptsRemoved(_) => "excerpts removed",
 1020        }
 1021    }
 1022}
 1023
 1024pub enum FormatTarget {
 1025    Buffers,
 1026    Ranges(Vec<Range<MultiBufferPoint>>),
 1027}
 1028
 1029pub(crate) struct FocusedBlock {
 1030    id: BlockId,
 1031    focus_handle: WeakFocusHandle,
 1032}
 1033
 1034#[derive(Clone)]
 1035enum JumpData {
 1036    MultiBufferRow {
 1037        row: MultiBufferRow,
 1038        line_offset_from_top: u32,
 1039    },
 1040    MultiBufferPoint {
 1041        excerpt_id: ExcerptId,
 1042        position: Point,
 1043        anchor: text::Anchor,
 1044        line_offset_from_top: u32,
 1045    },
 1046}
 1047
 1048pub enum MultibufferSelectionMode {
 1049    First,
 1050    All,
 1051}
 1052
 1053impl Editor {
 1054    pub fn single_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1055        let buffer = cx.new(|cx| Buffer::local("", cx));
 1056        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1057        Self::new(
 1058            EditorMode::SingleLine { auto_width: false },
 1059            buffer,
 1060            None,
 1061            false,
 1062            window,
 1063            cx,
 1064        )
 1065    }
 1066
 1067    pub fn multi_line(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1068        let buffer = cx.new(|cx| Buffer::local("", cx));
 1069        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1070        Self::new(EditorMode::Full, buffer, None, false, window, cx)
 1071    }
 1072
 1073    pub fn auto_width(window: &mut Window, cx: &mut Context<Self>) -> Self {
 1074        let buffer = cx.new(|cx| Buffer::local("", cx));
 1075        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1076        Self::new(
 1077            EditorMode::SingleLine { auto_width: true },
 1078            buffer,
 1079            None,
 1080            false,
 1081            window,
 1082            cx,
 1083        )
 1084    }
 1085
 1086    pub fn auto_height(max_lines: usize, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1087        let buffer = cx.new(|cx| Buffer::local("", cx));
 1088        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1089        Self::new(
 1090            EditorMode::AutoHeight { max_lines },
 1091            buffer,
 1092            None,
 1093            false,
 1094            window,
 1095            cx,
 1096        )
 1097    }
 1098
 1099    pub fn for_buffer(
 1100        buffer: Entity<Buffer>,
 1101        project: Option<Entity<Project>>,
 1102        window: &mut Window,
 1103        cx: &mut Context<Self>,
 1104    ) -> Self {
 1105        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 1106        Self::new(EditorMode::Full, buffer, project, false, window, cx)
 1107    }
 1108
 1109    pub fn for_multibuffer(
 1110        buffer: Entity<MultiBuffer>,
 1111        project: Option<Entity<Project>>,
 1112        show_excerpt_controls: bool,
 1113        window: &mut Window,
 1114        cx: &mut Context<Self>,
 1115    ) -> Self {
 1116        Self::new(
 1117            EditorMode::Full,
 1118            buffer,
 1119            project,
 1120            show_excerpt_controls,
 1121            window,
 1122            cx,
 1123        )
 1124    }
 1125
 1126    pub fn clone(&self, window: &mut Window, cx: &mut Context<Self>) -> Self {
 1127        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1128        let mut clone = Self::new(
 1129            self.mode,
 1130            self.buffer.clone(),
 1131            self.project.clone(),
 1132            show_excerpt_controls,
 1133            window,
 1134            cx,
 1135        );
 1136        self.display_map.update(cx, |display_map, cx| {
 1137            let snapshot = display_map.snapshot(cx);
 1138            clone.display_map.update(cx, |display_map, cx| {
 1139                display_map.set_state(&snapshot, cx);
 1140            });
 1141        });
 1142        clone.selections.clone_state(&self.selections);
 1143        clone.scroll_manager.clone_state(&self.scroll_manager);
 1144        clone.searchable = self.searchable;
 1145        clone
 1146    }
 1147
 1148    pub fn new(
 1149        mode: EditorMode,
 1150        buffer: Entity<MultiBuffer>,
 1151        project: Option<Entity<Project>>,
 1152        show_excerpt_controls: bool,
 1153        window: &mut Window,
 1154        cx: &mut Context<Self>,
 1155    ) -> Self {
 1156        let style = window.text_style();
 1157        let font_size = style.font_size.to_pixels(window.rem_size());
 1158        let editor = cx.entity().downgrade();
 1159        let fold_placeholder = FoldPlaceholder {
 1160            constrain_width: true,
 1161            render: Arc::new(move |fold_id, fold_range, _, cx| {
 1162                let editor = editor.clone();
 1163                div()
 1164                    .id(fold_id)
 1165                    .bg(cx.theme().colors().ghost_element_background)
 1166                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1167                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1168                    .rounded_sm()
 1169                    .size_full()
 1170                    .cursor_pointer()
 1171                    .child("")
 1172                    .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
 1173                    .on_click(move |_, _window, cx| {
 1174                        editor
 1175                            .update(cx, |editor, cx| {
 1176                                editor.unfold_ranges(
 1177                                    &[fold_range.start..fold_range.end],
 1178                                    true,
 1179                                    false,
 1180                                    cx,
 1181                                );
 1182                                cx.stop_propagation();
 1183                            })
 1184                            .ok();
 1185                    })
 1186                    .into_any()
 1187            }),
 1188            merge_adjacent: true,
 1189            ..Default::default()
 1190        };
 1191        let display_map = cx.new(|cx| {
 1192            DisplayMap::new(
 1193                buffer.clone(),
 1194                style.font(),
 1195                font_size,
 1196                None,
 1197                show_excerpt_controls,
 1198                FILE_HEADER_HEIGHT,
 1199                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1200                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1201                fold_placeholder,
 1202                cx,
 1203            )
 1204        });
 1205
 1206        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1207
 1208        let blink_manager = cx.new(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1209
 1210        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1211            .then(|| language_settings::SoftWrap::None);
 1212
 1213        let mut project_subscriptions = Vec::new();
 1214        if mode == EditorMode::Full {
 1215            if let Some(project) = project.as_ref() {
 1216                if buffer.read(cx).is_singleton() {
 1217                    project_subscriptions.push(cx.observe_in(project, window, |_, _, _, cx| {
 1218                        cx.emit(EditorEvent::TitleChanged);
 1219                    }));
 1220                }
 1221                project_subscriptions.push(cx.subscribe_in(
 1222                    project,
 1223                    window,
 1224                    |editor, _, event, window, cx| {
 1225                        if let project::Event::RefreshInlayHints = event {
 1226                            editor
 1227                                .refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1228                        } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1229                            if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1230                                let focus_handle = editor.focus_handle(cx);
 1231                                if focus_handle.is_focused(window) {
 1232                                    let snapshot = buffer.read(cx).snapshot();
 1233                                    for (range, snippet) in snippet_edits {
 1234                                        let editor_range =
 1235                                            language::range_from_lsp(*range).to_offset(&snapshot);
 1236                                        editor
 1237                                            .insert_snippet(
 1238                                                &[editor_range],
 1239                                                snippet.clone(),
 1240                                                window,
 1241                                                cx,
 1242                                            )
 1243                                            .ok();
 1244                                    }
 1245                                }
 1246                            }
 1247                        }
 1248                    },
 1249                ));
 1250                if let Some(task_inventory) = project
 1251                    .read(cx)
 1252                    .task_store()
 1253                    .read(cx)
 1254                    .task_inventory()
 1255                    .cloned()
 1256                {
 1257                    project_subscriptions.push(cx.observe_in(
 1258                        &task_inventory,
 1259                        window,
 1260                        |editor, _, window, cx| {
 1261                            editor.tasks_update_task = Some(editor.refresh_runnables(window, cx));
 1262                        },
 1263                    ));
 1264                }
 1265            }
 1266        }
 1267
 1268        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1269
 1270        let inlay_hint_settings =
 1271            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1272        let focus_handle = cx.focus_handle();
 1273        cx.on_focus(&focus_handle, window, Self::handle_focus)
 1274            .detach();
 1275        cx.on_focus_in(&focus_handle, window, Self::handle_focus_in)
 1276            .detach();
 1277        cx.on_focus_out(&focus_handle, window, Self::handle_focus_out)
 1278            .detach();
 1279        cx.on_blur(&focus_handle, window, Self::handle_blur)
 1280            .detach();
 1281
 1282        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1283            Some(false)
 1284        } else {
 1285            None
 1286        };
 1287
 1288        let mut code_action_providers = Vec::new();
 1289        if let Some(project) = project.clone() {
 1290            get_uncommitted_diff_for_buffer(
 1291                &project,
 1292                buffer.read(cx).all_buffers(),
 1293                buffer.clone(),
 1294                cx,
 1295            );
 1296            code_action_providers.push(Rc::new(project) as Rc<_>);
 1297        }
 1298
 1299        let mut this = Self {
 1300            focus_handle,
 1301            show_cursor_when_unfocused: false,
 1302            last_focused_descendant: None,
 1303            buffer: buffer.clone(),
 1304            display_map: display_map.clone(),
 1305            selections,
 1306            scroll_manager: ScrollManager::new(cx),
 1307            columnar_selection_tail: None,
 1308            add_selections_state: None,
 1309            select_next_state: None,
 1310            select_prev_state: None,
 1311            selection_history: Default::default(),
 1312            autoclose_regions: Default::default(),
 1313            snippet_stack: Default::default(),
 1314            select_larger_syntax_node_stack: Vec::new(),
 1315            ime_transaction: Default::default(),
 1316            active_diagnostics: None,
 1317            soft_wrap_mode_override,
 1318            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1319            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1320            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1321            project,
 1322            blink_manager: blink_manager.clone(),
 1323            show_local_selections: true,
 1324            show_scrollbars: true,
 1325            mode,
 1326            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1327            show_gutter: mode == EditorMode::Full,
 1328            show_line_numbers: None,
 1329            use_relative_line_numbers: None,
 1330            show_git_diff_gutter: None,
 1331            show_code_actions: None,
 1332            show_runnables: None,
 1333            show_wrap_guides: None,
 1334            show_indent_guides,
 1335            placeholder_text: None,
 1336            highlight_order: 0,
 1337            highlighted_rows: HashMap::default(),
 1338            background_highlights: Default::default(),
 1339            gutter_highlights: TreeMap::default(),
 1340            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1341            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1342            nav_history: None,
 1343            context_menu: RefCell::new(None),
 1344            mouse_context_menu: None,
 1345            completion_tasks: Default::default(),
 1346            signature_help_state: SignatureHelpState::default(),
 1347            auto_signature_help: None,
 1348            find_all_references_task_sources: Vec::new(),
 1349            next_completion_id: 0,
 1350            next_inlay_id: 0,
 1351            code_action_providers,
 1352            available_code_actions: Default::default(),
 1353            code_actions_task: Default::default(),
 1354            document_highlights_task: Default::default(),
 1355            linked_editing_range_task: Default::default(),
 1356            pending_rename: Default::default(),
 1357            searchable: true,
 1358            cursor_shape: EditorSettings::get_global(cx)
 1359                .cursor_shape
 1360                .unwrap_or_default(),
 1361            current_line_highlight: None,
 1362            autoindent_mode: Some(AutoindentMode::EachLine),
 1363            collapse_matches: false,
 1364            workspace: None,
 1365            input_enabled: true,
 1366            use_modal_editing: mode == EditorMode::Full,
 1367            read_only: false,
 1368            use_autoclose: true,
 1369            use_auto_surround: true,
 1370            auto_replace_emoji_shortcode: false,
 1371            leader_peer_id: None,
 1372            remote_id: None,
 1373            hover_state: Default::default(),
 1374            pending_mouse_down: None,
 1375            hovered_link_state: Default::default(),
 1376            inline_completion_provider: None,
 1377            active_inline_completion: None,
 1378            stale_inline_completion_in_menu: None,
 1379            previewing_inline_completion: false,
 1380            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1381
 1382            gutter_hovered: false,
 1383            pixel_position_of_newest_cursor: None,
 1384            last_bounds: None,
 1385            last_position_map: None,
 1386            expect_bounds_change: None,
 1387            gutter_dimensions: GutterDimensions::default(),
 1388            style: None,
 1389            show_cursor_names: false,
 1390            hovered_cursors: Default::default(),
 1391            next_editor_action_id: EditorActionId::default(),
 1392            editor_actions: Rc::default(),
 1393            show_inline_completions_override: None,
 1394            show_inline_completions: true,
 1395            menu_inline_completions_policy: MenuInlineCompletionsPolicy::ByProvider,
 1396            custom_context_menu: None,
 1397            show_git_blame_gutter: false,
 1398            show_git_blame_inline: false,
 1399            show_selection_menu: None,
 1400            show_git_blame_inline_delay_task: None,
 1401            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1402            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1403                .session
 1404                .restore_unsaved_buffers,
 1405            blame: None,
 1406            blame_subscription: None,
 1407            tasks: Default::default(),
 1408            _subscriptions: vec![
 1409                cx.observe(&buffer, Self::on_buffer_changed),
 1410                cx.subscribe_in(&buffer, window, Self::on_buffer_event),
 1411                cx.observe_in(&display_map, window, Self::on_display_map_changed),
 1412                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1413                cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
 1414                cx.observe_window_activation(window, |editor, window, cx| {
 1415                    let active = window.is_window_active();
 1416                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1417                        if active {
 1418                            blink_manager.enable(cx);
 1419                        } else {
 1420                            blink_manager.disable(cx);
 1421                        }
 1422                    });
 1423                }),
 1424            ],
 1425            tasks_update_task: None,
 1426            linked_edit_ranges: Default::default(),
 1427            in_project_search: false,
 1428            previous_search_ranges: None,
 1429            breadcrumb_header: None,
 1430            focused_block: None,
 1431            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1432            addons: HashMap::default(),
 1433            registered_buffers: HashMap::default(),
 1434            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1435            selection_mark_mode: false,
 1436            toggle_fold_multiple_buffers: Task::ready(()),
 1437            text_style_refinement: None,
 1438        };
 1439        this.tasks_update_task = Some(this.refresh_runnables(window, cx));
 1440        this._subscriptions.extend(project_subscriptions);
 1441
 1442        this.end_selection(window, cx);
 1443        this.scroll_manager.show_scrollbar(window, cx);
 1444
 1445        if mode == EditorMode::Full {
 1446            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1447            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1448
 1449            if this.git_blame_inline_enabled {
 1450                this.git_blame_inline_enabled = true;
 1451                this.start_git_blame_inline(false, window, cx);
 1452            }
 1453
 1454            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1455                if let Some(project) = this.project.as_ref() {
 1456                    let lsp_store = project.read(cx).lsp_store();
 1457                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1458                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1459                    });
 1460                    this.registered_buffers
 1461                        .insert(buffer.read(cx).remote_id(), handle);
 1462                }
 1463            }
 1464        }
 1465
 1466        this.report_editor_event("Editor Opened", None, cx);
 1467        this
 1468    }
 1469
 1470    pub fn mouse_menu_is_focused(&self, window: &mut Window, cx: &mut App) -> bool {
 1471        self.mouse_context_menu
 1472            .as_ref()
 1473            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(window))
 1474    }
 1475
 1476    fn key_context(&self, window: &mut Window, cx: &mut Context<Self>) -> KeyContext {
 1477        let mut key_context = KeyContext::new_with_defaults();
 1478        key_context.add("Editor");
 1479        let mode = match self.mode {
 1480            EditorMode::SingleLine { .. } => "single_line",
 1481            EditorMode::AutoHeight { .. } => "auto_height",
 1482            EditorMode::Full => "full",
 1483        };
 1484
 1485        if EditorSettings::jupyter_enabled(cx) {
 1486            key_context.add("jupyter");
 1487        }
 1488
 1489        key_context.set("mode", mode);
 1490        if self.pending_rename.is_some() {
 1491            key_context.add("renaming");
 1492        }
 1493
 1494        let mut showing_completions = false;
 1495
 1496        match self.context_menu.borrow().as_ref() {
 1497            Some(CodeContextMenu::Completions(_)) => {
 1498                key_context.add("menu");
 1499                key_context.add("showing_completions");
 1500                showing_completions = true;
 1501            }
 1502            Some(CodeContextMenu::CodeActions(_)) => {
 1503                key_context.add("menu");
 1504                key_context.add("showing_code_actions")
 1505            }
 1506            None => {}
 1507        }
 1508
 1509        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1510        if !self.focus_handle(cx).contains_focused(window, cx)
 1511            || (self.is_focused(window) || self.mouse_menu_is_focused(window, cx))
 1512        {
 1513            for addon in self.addons.values() {
 1514                addon.extend_key_context(&mut key_context, cx)
 1515            }
 1516        }
 1517
 1518        if let Some(extension) = self
 1519            .buffer
 1520            .read(cx)
 1521            .as_singleton()
 1522            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1523        {
 1524            key_context.set("extension", extension.to_string());
 1525        }
 1526
 1527        if self.has_active_inline_completion() {
 1528            key_context.add("copilot_suggestion");
 1529            key_context.add("inline_completion");
 1530
 1531            if showing_completions || self.inline_completion_requires_modifier(cx) {
 1532                key_context.add("inline_completion_requires_modifier");
 1533            }
 1534        }
 1535
 1536        if self.selection_mark_mode {
 1537            key_context.add("selection_mode");
 1538        }
 1539
 1540        key_context
 1541    }
 1542
 1543    pub fn new_file(
 1544        workspace: &mut Workspace,
 1545        _: &workspace::NewFile,
 1546        window: &mut Window,
 1547        cx: &mut Context<Workspace>,
 1548    ) {
 1549        Self::new_in_workspace(workspace, window, cx).detach_and_prompt_err(
 1550            "Failed to create buffer",
 1551            window,
 1552            cx,
 1553            |e, _, _| match e.error_code() {
 1554                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1555                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1556                e.error_tag("required").unwrap_or("the latest version")
 1557            )),
 1558                _ => None,
 1559            },
 1560        );
 1561    }
 1562
 1563    pub fn new_in_workspace(
 1564        workspace: &mut Workspace,
 1565        window: &mut Window,
 1566        cx: &mut Context<Workspace>,
 1567    ) -> Task<Result<Entity<Editor>>> {
 1568        let project = workspace.project().clone();
 1569        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1570
 1571        cx.spawn_in(window, |workspace, mut cx| async move {
 1572            let buffer = create.await?;
 1573            workspace.update_in(&mut cx, |workspace, window, cx| {
 1574                let editor =
 1575                    cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx));
 1576                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 1577                editor
 1578            })
 1579        })
 1580    }
 1581
 1582    fn new_file_vertical(
 1583        workspace: &mut Workspace,
 1584        _: &workspace::NewFileSplitVertical,
 1585        window: &mut Window,
 1586        cx: &mut Context<Workspace>,
 1587    ) {
 1588        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), window, cx)
 1589    }
 1590
 1591    fn new_file_horizontal(
 1592        workspace: &mut Workspace,
 1593        _: &workspace::NewFileSplitHorizontal,
 1594        window: &mut Window,
 1595        cx: &mut Context<Workspace>,
 1596    ) {
 1597        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), window, cx)
 1598    }
 1599
 1600    fn new_file_in_direction(
 1601        workspace: &mut Workspace,
 1602        direction: SplitDirection,
 1603        window: &mut Window,
 1604        cx: &mut Context<Workspace>,
 1605    ) {
 1606        let project = workspace.project().clone();
 1607        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1608
 1609        cx.spawn_in(window, |workspace, mut cx| async move {
 1610            let buffer = create.await?;
 1611            workspace.update_in(&mut cx, move |workspace, window, cx| {
 1612                workspace.split_item(
 1613                    direction,
 1614                    Box::new(
 1615                        cx.new(|cx| Editor::for_buffer(buffer, Some(project.clone()), window, cx)),
 1616                    ),
 1617                    window,
 1618                    cx,
 1619                )
 1620            })?;
 1621            anyhow::Ok(())
 1622        })
 1623        .detach_and_prompt_err("Failed to create buffer", window, cx, |e, _, _| {
 1624            match e.error_code() {
 1625                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1626                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1627                e.error_tag("required").unwrap_or("the latest version")
 1628            )),
 1629                _ => None,
 1630            }
 1631        });
 1632    }
 1633
 1634    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1635        self.leader_peer_id
 1636    }
 1637
 1638    pub fn buffer(&self) -> &Entity<MultiBuffer> {
 1639        &self.buffer
 1640    }
 1641
 1642    pub fn workspace(&self) -> Option<Entity<Workspace>> {
 1643        self.workspace.as_ref()?.0.upgrade()
 1644    }
 1645
 1646    pub fn title<'a>(&self, cx: &'a App) -> Cow<'a, str> {
 1647        self.buffer().read(cx).title(cx)
 1648    }
 1649
 1650    pub fn snapshot(&self, window: &mut Window, cx: &mut App) -> EditorSnapshot {
 1651        let git_blame_gutter_max_author_length = self
 1652            .render_git_blame_gutter(cx)
 1653            .then(|| {
 1654                if let Some(blame) = self.blame.as_ref() {
 1655                    let max_author_length =
 1656                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1657                    Some(max_author_length)
 1658                } else {
 1659                    None
 1660                }
 1661            })
 1662            .flatten();
 1663
 1664        EditorSnapshot {
 1665            mode: self.mode,
 1666            show_gutter: self.show_gutter,
 1667            show_line_numbers: self.show_line_numbers,
 1668            show_git_diff_gutter: self.show_git_diff_gutter,
 1669            show_code_actions: self.show_code_actions,
 1670            show_runnables: self.show_runnables,
 1671            git_blame_gutter_max_author_length,
 1672            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1673            scroll_anchor: self.scroll_manager.anchor(),
 1674            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1675            placeholder_text: self.placeholder_text.clone(),
 1676            is_focused: self.focus_handle.is_focused(window),
 1677            current_line_highlight: self
 1678                .current_line_highlight
 1679                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1680            gutter_hovered: self.gutter_hovered,
 1681        }
 1682    }
 1683
 1684    pub fn language_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<Language>> {
 1685        self.buffer.read(cx).language_at(point, cx)
 1686    }
 1687
 1688    pub fn file_at<T: ToOffset>(&self, point: T, cx: &App) -> Option<Arc<dyn language::File>> {
 1689        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1690    }
 1691
 1692    pub fn active_excerpt(
 1693        &self,
 1694        cx: &App,
 1695    ) -> Option<(ExcerptId, Entity<Buffer>, Range<text::Anchor>)> {
 1696        self.buffer
 1697            .read(cx)
 1698            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1699    }
 1700
 1701    pub fn mode(&self) -> EditorMode {
 1702        self.mode
 1703    }
 1704
 1705    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1706        self.collaboration_hub.as_deref()
 1707    }
 1708
 1709    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1710        self.collaboration_hub = Some(hub);
 1711    }
 1712
 1713    pub fn set_in_project_search(&mut self, in_project_search: bool) {
 1714        self.in_project_search = in_project_search;
 1715    }
 1716
 1717    pub fn set_custom_context_menu(
 1718        &mut self,
 1719        f: impl 'static
 1720            + Fn(
 1721                &mut Self,
 1722                DisplayPoint,
 1723                &mut Window,
 1724                &mut Context<Self>,
 1725            ) -> Option<Entity<ui::ContextMenu>>,
 1726    ) {
 1727        self.custom_context_menu = Some(Box::new(f))
 1728    }
 1729
 1730    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1731        self.completion_provider = provider;
 1732    }
 1733
 1734    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1735        self.semantics_provider.clone()
 1736    }
 1737
 1738    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1739        self.semantics_provider = provider;
 1740    }
 1741
 1742    pub fn set_inline_completion_provider<T>(
 1743        &mut self,
 1744        provider: Option<Entity<T>>,
 1745        window: &mut Window,
 1746        cx: &mut Context<Self>,
 1747    ) where
 1748        T: InlineCompletionProvider,
 1749    {
 1750        self.inline_completion_provider =
 1751            provider.map(|provider| RegisteredInlineCompletionProvider {
 1752                _subscription: cx.observe_in(&provider, window, |this, _, window, cx| {
 1753                    if this.focus_handle.is_focused(window) {
 1754                        this.update_visible_inline_completion(window, cx);
 1755                    }
 1756                }),
 1757                provider: Arc::new(provider),
 1758            });
 1759        self.refresh_inline_completion(false, false, window, cx);
 1760    }
 1761
 1762    pub fn placeholder_text(&self) -> Option<&str> {
 1763        self.placeholder_text.as_deref()
 1764    }
 1765
 1766    pub fn set_placeholder_text(
 1767        &mut self,
 1768        placeholder_text: impl Into<Arc<str>>,
 1769        cx: &mut Context<Self>,
 1770    ) {
 1771        let placeholder_text = Some(placeholder_text.into());
 1772        if self.placeholder_text != placeholder_text {
 1773            self.placeholder_text = placeholder_text;
 1774            cx.notify();
 1775        }
 1776    }
 1777
 1778    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut Context<Self>) {
 1779        self.cursor_shape = cursor_shape;
 1780
 1781        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1782        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1783
 1784        cx.notify();
 1785    }
 1786
 1787    pub fn set_current_line_highlight(
 1788        &mut self,
 1789        current_line_highlight: Option<CurrentLineHighlight>,
 1790    ) {
 1791        self.current_line_highlight = current_line_highlight;
 1792    }
 1793
 1794    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1795        self.collapse_matches = collapse_matches;
 1796    }
 1797
 1798    pub fn register_buffers_with_language_servers(&mut self, cx: &mut Context<Self>) {
 1799        let buffers = self.buffer.read(cx).all_buffers();
 1800        let Some(lsp_store) = self.lsp_store(cx) else {
 1801            return;
 1802        };
 1803        lsp_store.update(cx, |lsp_store, cx| {
 1804            for buffer in buffers {
 1805                self.registered_buffers
 1806                    .entry(buffer.read(cx).remote_id())
 1807                    .or_insert_with(|| {
 1808                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1809                    });
 1810            }
 1811        })
 1812    }
 1813
 1814    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1815        if self.collapse_matches {
 1816            return range.start..range.start;
 1817        }
 1818        range.clone()
 1819    }
 1820
 1821    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut Context<Self>) {
 1822        if self.display_map.read(cx).clip_at_line_ends != clip {
 1823            self.display_map
 1824                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1825        }
 1826    }
 1827
 1828    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1829        self.input_enabled = input_enabled;
 1830    }
 1831
 1832    pub fn set_show_inline_completions_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
 1833        self.show_inline_completions = enabled;
 1834        if !self.show_inline_completions {
 1835            self.take_active_inline_completion(cx);
 1836            cx.notify();
 1837        }
 1838    }
 1839
 1840    pub fn set_menu_inline_completions_policy(&mut self, value: MenuInlineCompletionsPolicy) {
 1841        self.menu_inline_completions_policy = value;
 1842    }
 1843
 1844    pub fn set_autoindent(&mut self, autoindent: bool) {
 1845        if autoindent {
 1846            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1847        } else {
 1848            self.autoindent_mode = None;
 1849        }
 1850    }
 1851
 1852    pub fn read_only(&self, cx: &App) -> bool {
 1853        self.read_only || self.buffer.read(cx).read_only()
 1854    }
 1855
 1856    pub fn set_read_only(&mut self, read_only: bool) {
 1857        self.read_only = read_only;
 1858    }
 1859
 1860    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1861        self.use_autoclose = autoclose;
 1862    }
 1863
 1864    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1865        self.use_auto_surround = auto_surround;
 1866    }
 1867
 1868    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1869        self.auto_replace_emoji_shortcode = auto_replace;
 1870    }
 1871
 1872    pub fn toggle_inline_completions(
 1873        &mut self,
 1874        _: &ToggleInlineCompletions,
 1875        window: &mut Window,
 1876        cx: &mut Context<Self>,
 1877    ) {
 1878        if self.show_inline_completions_override.is_some() {
 1879            self.set_show_inline_completions(None, window, cx);
 1880        } else {
 1881            let cursor = self.selections.newest_anchor().head();
 1882            if let Some((buffer, cursor_buffer_position)) =
 1883                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1884            {
 1885                let show_inline_completions = !self.should_show_inline_completions_in_buffer(
 1886                    &buffer,
 1887                    cursor_buffer_position,
 1888                    cx,
 1889                );
 1890                self.set_show_inline_completions(Some(show_inline_completions), window, cx);
 1891            }
 1892        }
 1893    }
 1894
 1895    pub fn set_show_inline_completions(
 1896        &mut self,
 1897        show_inline_completions: Option<bool>,
 1898        window: &mut Window,
 1899        cx: &mut Context<Self>,
 1900    ) {
 1901        self.show_inline_completions_override = show_inline_completions;
 1902        self.refresh_inline_completion(false, true, window, cx);
 1903    }
 1904
 1905    fn inline_completions_disabled_in_scope(
 1906        &self,
 1907        buffer: &Entity<Buffer>,
 1908        buffer_position: language::Anchor,
 1909        cx: &App,
 1910    ) -> bool {
 1911        let snapshot = buffer.read(cx).snapshot();
 1912        let settings = snapshot.settings_at(buffer_position, cx);
 1913
 1914        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1915            return false;
 1916        };
 1917
 1918        scope.override_name().map_or(false, |scope_name| {
 1919            settings
 1920                .inline_completions_disabled_in
 1921                .iter()
 1922                .any(|s| s == scope_name)
 1923        })
 1924    }
 1925
 1926    pub fn set_use_modal_editing(&mut self, to: bool) {
 1927        self.use_modal_editing = to;
 1928    }
 1929
 1930    pub fn use_modal_editing(&self) -> bool {
 1931        self.use_modal_editing
 1932    }
 1933
 1934    fn selections_did_change(
 1935        &mut self,
 1936        local: bool,
 1937        old_cursor_position: &Anchor,
 1938        show_completions: bool,
 1939        window: &mut Window,
 1940        cx: &mut Context<Self>,
 1941    ) {
 1942        window.invalidate_character_coordinates();
 1943
 1944        // Copy selections to primary selection buffer
 1945        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1946        if local {
 1947            let selections = self.selections.all::<usize>(cx);
 1948            let buffer_handle = self.buffer.read(cx).read(cx);
 1949
 1950            let mut text = String::new();
 1951            for (index, selection) in selections.iter().enumerate() {
 1952                let text_for_selection = buffer_handle
 1953                    .text_for_range(selection.start..selection.end)
 1954                    .collect::<String>();
 1955
 1956                text.push_str(&text_for_selection);
 1957                if index != selections.len() - 1 {
 1958                    text.push('\n');
 1959                }
 1960            }
 1961
 1962            if !text.is_empty() {
 1963                cx.write_to_primary(ClipboardItem::new_string(text));
 1964            }
 1965        }
 1966
 1967        if self.focus_handle.is_focused(window) && self.leader_peer_id.is_none() {
 1968            self.buffer.update(cx, |buffer, cx| {
 1969                buffer.set_active_selections(
 1970                    &self.selections.disjoint_anchors(),
 1971                    self.selections.line_mode,
 1972                    self.cursor_shape,
 1973                    cx,
 1974                )
 1975            });
 1976        }
 1977        let display_map = self
 1978            .display_map
 1979            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1980        let buffer = &display_map.buffer_snapshot;
 1981        self.add_selections_state = None;
 1982        self.select_next_state = None;
 1983        self.select_prev_state = None;
 1984        self.select_larger_syntax_node_stack.clear();
 1985        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1986        self.snippet_stack
 1987            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1988        self.take_rename(false, window, cx);
 1989
 1990        let new_cursor_position = self.selections.newest_anchor().head();
 1991
 1992        self.push_to_nav_history(
 1993            *old_cursor_position,
 1994            Some(new_cursor_position.to_point(buffer)),
 1995            cx,
 1996        );
 1997
 1998        if local {
 1999            let new_cursor_position = self.selections.newest_anchor().head();
 2000            let mut context_menu = self.context_menu.borrow_mut();
 2001            let completion_menu = match context_menu.as_ref() {
 2002                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 2003                _ => {
 2004                    *context_menu = None;
 2005                    None
 2006                }
 2007            };
 2008
 2009            if let Some(completion_menu) = completion_menu {
 2010                let cursor_position = new_cursor_position.to_offset(buffer);
 2011                let (word_range, kind) =
 2012                    buffer.surrounding_word(completion_menu.initial_position, true);
 2013                if kind == Some(CharKind::Word)
 2014                    && word_range.to_inclusive().contains(&cursor_position)
 2015                {
 2016                    let mut completion_menu = completion_menu.clone();
 2017                    drop(context_menu);
 2018
 2019                    let query = Self::completion_query(buffer, cursor_position);
 2020                    cx.spawn(move |this, mut cx| async move {
 2021                        completion_menu
 2022                            .filter(query.as_deref(), cx.background_executor().clone())
 2023                            .await;
 2024
 2025                        this.update(&mut cx, |this, cx| {
 2026                            let mut context_menu = this.context_menu.borrow_mut();
 2027                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 2028                            else {
 2029                                return;
 2030                            };
 2031
 2032                            if menu.id > completion_menu.id {
 2033                                return;
 2034                            }
 2035
 2036                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 2037                            drop(context_menu);
 2038                            cx.notify();
 2039                        })
 2040                    })
 2041                    .detach();
 2042
 2043                    if show_completions {
 2044                        self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 2045                    }
 2046                } else {
 2047                    drop(context_menu);
 2048                    self.hide_context_menu(window, cx);
 2049                }
 2050            } else {
 2051                drop(context_menu);
 2052            }
 2053
 2054            hide_hover(self, cx);
 2055
 2056            if old_cursor_position.to_display_point(&display_map).row()
 2057                != new_cursor_position.to_display_point(&display_map).row()
 2058            {
 2059                self.available_code_actions.take();
 2060            }
 2061            self.refresh_code_actions(window, cx);
 2062            self.refresh_document_highlights(cx);
 2063            refresh_matching_bracket_highlights(self, window, cx);
 2064            self.update_visible_inline_completion(window, cx);
 2065            linked_editing_ranges::refresh_linked_ranges(self, window, cx);
 2066            if self.git_blame_inline_enabled {
 2067                self.start_inline_blame_timer(window, cx);
 2068            }
 2069        }
 2070
 2071        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 2072        cx.emit(EditorEvent::SelectionsChanged { local });
 2073
 2074        if self.selections.disjoint_anchors().len() == 1 {
 2075            cx.emit(SearchEvent::ActiveMatchChanged)
 2076        }
 2077        cx.notify();
 2078    }
 2079
 2080    pub fn change_selections<R>(
 2081        &mut self,
 2082        autoscroll: Option<Autoscroll>,
 2083        window: &mut Window,
 2084        cx: &mut Context<Self>,
 2085        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2086    ) -> R {
 2087        self.change_selections_inner(autoscroll, true, window, cx, change)
 2088    }
 2089
 2090    pub fn change_selections_inner<R>(
 2091        &mut self,
 2092        autoscroll: Option<Autoscroll>,
 2093        request_completions: bool,
 2094        window: &mut Window,
 2095        cx: &mut Context<Self>,
 2096        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 2097    ) -> R {
 2098        let old_cursor_position = self.selections.newest_anchor().head();
 2099        self.push_to_selection_history();
 2100
 2101        let (changed, result) = self.selections.change_with(cx, change);
 2102
 2103        if changed {
 2104            if let Some(autoscroll) = autoscroll {
 2105                self.request_autoscroll(autoscroll, cx);
 2106            }
 2107            self.selections_did_change(true, &old_cursor_position, request_completions, window, cx);
 2108
 2109            if self.should_open_signature_help_automatically(
 2110                &old_cursor_position,
 2111                self.signature_help_state.backspace_pressed(),
 2112                cx,
 2113            ) {
 2114                self.show_signature_help(&ShowSignatureHelp, window, cx);
 2115            }
 2116            self.signature_help_state.set_backspace_pressed(false);
 2117        }
 2118
 2119        result
 2120    }
 2121
 2122    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2123    where
 2124        I: IntoIterator<Item = (Range<S>, T)>,
 2125        S: ToOffset,
 2126        T: Into<Arc<str>>,
 2127    {
 2128        if self.read_only(cx) {
 2129            return;
 2130        }
 2131
 2132        self.buffer
 2133            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2134    }
 2135
 2136    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut Context<Self>)
 2137    where
 2138        I: IntoIterator<Item = (Range<S>, T)>,
 2139        S: ToOffset,
 2140        T: Into<Arc<str>>,
 2141    {
 2142        if self.read_only(cx) {
 2143            return;
 2144        }
 2145
 2146        self.buffer.update(cx, |buffer, cx| {
 2147            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2148        });
 2149    }
 2150
 2151    pub fn edit_with_block_indent<I, S, T>(
 2152        &mut self,
 2153        edits: I,
 2154        original_indent_columns: Vec<u32>,
 2155        cx: &mut Context<Self>,
 2156    ) where
 2157        I: IntoIterator<Item = (Range<S>, T)>,
 2158        S: ToOffset,
 2159        T: Into<Arc<str>>,
 2160    {
 2161        if self.read_only(cx) {
 2162            return;
 2163        }
 2164
 2165        self.buffer.update(cx, |buffer, cx| {
 2166            buffer.edit(
 2167                edits,
 2168                Some(AutoindentMode::Block {
 2169                    original_indent_columns,
 2170                }),
 2171                cx,
 2172            )
 2173        });
 2174    }
 2175
 2176    fn select(&mut self, phase: SelectPhase, window: &mut Window, cx: &mut Context<Self>) {
 2177        self.hide_context_menu(window, cx);
 2178
 2179        match phase {
 2180            SelectPhase::Begin {
 2181                position,
 2182                add,
 2183                click_count,
 2184            } => self.begin_selection(position, add, click_count, window, cx),
 2185            SelectPhase::BeginColumnar {
 2186                position,
 2187                goal_column,
 2188                reset,
 2189            } => self.begin_columnar_selection(position, goal_column, reset, window, cx),
 2190            SelectPhase::Extend {
 2191                position,
 2192                click_count,
 2193            } => self.extend_selection(position, click_count, window, cx),
 2194            SelectPhase::Update {
 2195                position,
 2196                goal_column,
 2197                scroll_delta,
 2198            } => self.update_selection(position, goal_column, scroll_delta, window, cx),
 2199            SelectPhase::End => self.end_selection(window, cx),
 2200        }
 2201    }
 2202
 2203    fn extend_selection(
 2204        &mut self,
 2205        position: DisplayPoint,
 2206        click_count: usize,
 2207        window: &mut Window,
 2208        cx: &mut Context<Self>,
 2209    ) {
 2210        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2211        let tail = self.selections.newest::<usize>(cx).tail();
 2212        self.begin_selection(position, false, click_count, window, cx);
 2213
 2214        let position = position.to_offset(&display_map, Bias::Left);
 2215        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2216
 2217        let mut pending_selection = self
 2218            .selections
 2219            .pending_anchor()
 2220            .expect("extend_selection not called with pending selection");
 2221        if position >= tail {
 2222            pending_selection.start = tail_anchor;
 2223        } else {
 2224            pending_selection.end = tail_anchor;
 2225            pending_selection.reversed = true;
 2226        }
 2227
 2228        let mut pending_mode = self.selections.pending_mode().unwrap();
 2229        match &mut pending_mode {
 2230            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2231            _ => {}
 2232        }
 2233
 2234        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 2235            s.set_pending(pending_selection, pending_mode)
 2236        });
 2237    }
 2238
 2239    fn begin_selection(
 2240        &mut self,
 2241        position: DisplayPoint,
 2242        add: bool,
 2243        click_count: usize,
 2244        window: &mut Window,
 2245        cx: &mut Context<Self>,
 2246    ) {
 2247        if !self.focus_handle.is_focused(window) {
 2248            self.last_focused_descendant = None;
 2249            window.focus(&self.focus_handle);
 2250        }
 2251
 2252        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2253        let buffer = &display_map.buffer_snapshot;
 2254        let newest_selection = self.selections.newest_anchor().clone();
 2255        let position = display_map.clip_point(position, Bias::Left);
 2256
 2257        let start;
 2258        let end;
 2259        let mode;
 2260        let mut auto_scroll;
 2261        match click_count {
 2262            1 => {
 2263                start = buffer.anchor_before(position.to_point(&display_map));
 2264                end = start;
 2265                mode = SelectMode::Character;
 2266                auto_scroll = true;
 2267            }
 2268            2 => {
 2269                let range = movement::surrounding_word(&display_map, position);
 2270                start = buffer.anchor_before(range.start.to_point(&display_map));
 2271                end = buffer.anchor_before(range.end.to_point(&display_map));
 2272                mode = SelectMode::Word(start..end);
 2273                auto_scroll = true;
 2274            }
 2275            3 => {
 2276                let position = display_map
 2277                    .clip_point(position, Bias::Left)
 2278                    .to_point(&display_map);
 2279                let line_start = display_map.prev_line_boundary(position).0;
 2280                let next_line_start = buffer.clip_point(
 2281                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2282                    Bias::Left,
 2283                );
 2284                start = buffer.anchor_before(line_start);
 2285                end = buffer.anchor_before(next_line_start);
 2286                mode = SelectMode::Line(start..end);
 2287                auto_scroll = true;
 2288            }
 2289            _ => {
 2290                start = buffer.anchor_before(0);
 2291                end = buffer.anchor_before(buffer.len());
 2292                mode = SelectMode::All;
 2293                auto_scroll = false;
 2294            }
 2295        }
 2296        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2297
 2298        let point_to_delete: Option<usize> = {
 2299            let selected_points: Vec<Selection<Point>> =
 2300                self.selections.disjoint_in_range(start..end, cx);
 2301
 2302            if !add || click_count > 1 {
 2303                None
 2304            } else if !selected_points.is_empty() {
 2305                Some(selected_points[0].id)
 2306            } else {
 2307                let clicked_point_already_selected =
 2308                    self.selections.disjoint.iter().find(|selection| {
 2309                        selection.start.to_point(buffer) == start.to_point(buffer)
 2310                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2311                    });
 2312
 2313                clicked_point_already_selected.map(|selection| selection.id)
 2314            }
 2315        };
 2316
 2317        let selections_count = self.selections.count();
 2318
 2319        self.change_selections(auto_scroll.then(Autoscroll::newest), window, cx, |s| {
 2320            if let Some(point_to_delete) = point_to_delete {
 2321                s.delete(point_to_delete);
 2322
 2323                if selections_count == 1 {
 2324                    s.set_pending_anchor_range(start..end, mode);
 2325                }
 2326            } else {
 2327                if !add {
 2328                    s.clear_disjoint();
 2329                } else if click_count > 1 {
 2330                    s.delete(newest_selection.id)
 2331                }
 2332
 2333                s.set_pending_anchor_range(start..end, mode);
 2334            }
 2335        });
 2336    }
 2337
 2338    fn begin_columnar_selection(
 2339        &mut self,
 2340        position: DisplayPoint,
 2341        goal_column: u32,
 2342        reset: bool,
 2343        window: &mut Window,
 2344        cx: &mut Context<Self>,
 2345    ) {
 2346        if !self.focus_handle.is_focused(window) {
 2347            self.last_focused_descendant = None;
 2348            window.focus(&self.focus_handle);
 2349        }
 2350
 2351        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2352
 2353        if reset {
 2354            let pointer_position = display_map
 2355                .buffer_snapshot
 2356                .anchor_before(position.to_point(&display_map));
 2357
 2358            self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 2359                s.clear_disjoint();
 2360                s.set_pending_anchor_range(
 2361                    pointer_position..pointer_position,
 2362                    SelectMode::Character,
 2363                );
 2364            });
 2365        }
 2366
 2367        let tail = self.selections.newest::<Point>(cx).tail();
 2368        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2369
 2370        if !reset {
 2371            self.select_columns(
 2372                tail.to_display_point(&display_map),
 2373                position,
 2374                goal_column,
 2375                &display_map,
 2376                window,
 2377                cx,
 2378            );
 2379        }
 2380    }
 2381
 2382    fn update_selection(
 2383        &mut self,
 2384        position: DisplayPoint,
 2385        goal_column: u32,
 2386        scroll_delta: gpui::Point<f32>,
 2387        window: &mut Window,
 2388        cx: &mut Context<Self>,
 2389    ) {
 2390        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2391
 2392        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2393            let tail = tail.to_display_point(&display_map);
 2394            self.select_columns(tail, position, goal_column, &display_map, window, cx);
 2395        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2396            let buffer = self.buffer.read(cx).snapshot(cx);
 2397            let head;
 2398            let tail;
 2399            let mode = self.selections.pending_mode().unwrap();
 2400            match &mode {
 2401                SelectMode::Character => {
 2402                    head = position.to_point(&display_map);
 2403                    tail = pending.tail().to_point(&buffer);
 2404                }
 2405                SelectMode::Word(original_range) => {
 2406                    let original_display_range = original_range.start.to_display_point(&display_map)
 2407                        ..original_range.end.to_display_point(&display_map);
 2408                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2409                        ..original_display_range.end.to_point(&display_map);
 2410                    if movement::is_inside_word(&display_map, position)
 2411                        || original_display_range.contains(&position)
 2412                    {
 2413                        let word_range = movement::surrounding_word(&display_map, position);
 2414                        if word_range.start < original_display_range.start {
 2415                            head = word_range.start.to_point(&display_map);
 2416                        } else {
 2417                            head = word_range.end.to_point(&display_map);
 2418                        }
 2419                    } else {
 2420                        head = position.to_point(&display_map);
 2421                    }
 2422
 2423                    if head <= original_buffer_range.start {
 2424                        tail = original_buffer_range.end;
 2425                    } else {
 2426                        tail = original_buffer_range.start;
 2427                    }
 2428                }
 2429                SelectMode::Line(original_range) => {
 2430                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2431
 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
 2441                    if line_start < original_range.start {
 2442                        head = line_start
 2443                    } else {
 2444                        head = next_line_start
 2445                    }
 2446
 2447                    if head <= original_range.start {
 2448                        tail = original_range.end;
 2449                    } else {
 2450                        tail = original_range.start;
 2451                    }
 2452                }
 2453                SelectMode::All => {
 2454                    return;
 2455                }
 2456            };
 2457
 2458            if head < tail {
 2459                pending.start = buffer.anchor_before(head);
 2460                pending.end = buffer.anchor_before(tail);
 2461                pending.reversed = true;
 2462            } else {
 2463                pending.start = buffer.anchor_before(tail);
 2464                pending.end = buffer.anchor_before(head);
 2465                pending.reversed = false;
 2466            }
 2467
 2468            self.change_selections(None, window, cx, |s| {
 2469                s.set_pending(pending, mode);
 2470            });
 2471        } else {
 2472            log::error!("update_selection dispatched with no pending selection");
 2473            return;
 2474        }
 2475
 2476        self.apply_scroll_delta(scroll_delta, window, cx);
 2477        cx.notify();
 2478    }
 2479
 2480    fn end_selection(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 2481        self.columnar_selection_tail.take();
 2482        if self.selections.pending_anchor().is_some() {
 2483            let selections = self.selections.all::<usize>(cx);
 2484            self.change_selections(None, window, cx, |s| {
 2485                s.select(selections);
 2486                s.clear_pending();
 2487            });
 2488        }
 2489    }
 2490
 2491    fn select_columns(
 2492        &mut self,
 2493        tail: DisplayPoint,
 2494        head: DisplayPoint,
 2495        goal_column: u32,
 2496        display_map: &DisplaySnapshot,
 2497        window: &mut Window,
 2498        cx: &mut Context<Self>,
 2499    ) {
 2500        let start_row = cmp::min(tail.row(), head.row());
 2501        let end_row = cmp::max(tail.row(), head.row());
 2502        let start_column = cmp::min(tail.column(), goal_column);
 2503        let end_column = cmp::max(tail.column(), goal_column);
 2504        let reversed = start_column < tail.column();
 2505
 2506        let selection_ranges = (start_row.0..=end_row.0)
 2507            .map(DisplayRow)
 2508            .filter_map(|row| {
 2509                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2510                    let start = display_map
 2511                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2512                        .to_point(display_map);
 2513                    let end = display_map
 2514                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2515                        .to_point(display_map);
 2516                    if reversed {
 2517                        Some(end..start)
 2518                    } else {
 2519                        Some(start..end)
 2520                    }
 2521                } else {
 2522                    None
 2523                }
 2524            })
 2525            .collect::<Vec<_>>();
 2526
 2527        self.change_selections(None, window, cx, |s| {
 2528            s.select_ranges(selection_ranges);
 2529        });
 2530        cx.notify();
 2531    }
 2532
 2533    pub fn has_pending_nonempty_selection(&self) -> bool {
 2534        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2535            Some(Selection { start, end, .. }) => start != end,
 2536            None => false,
 2537        };
 2538
 2539        pending_nonempty_selection
 2540            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2541    }
 2542
 2543    pub fn has_pending_selection(&self) -> bool {
 2544        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2545    }
 2546
 2547    pub fn cancel(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
 2548        self.selection_mark_mode = false;
 2549
 2550        if self.clear_expanded_diff_hunks(cx) {
 2551            cx.notify();
 2552            return;
 2553        }
 2554        if self.dismiss_menus_and_popups(true, window, cx) {
 2555            return;
 2556        }
 2557
 2558        if self.mode == EditorMode::Full
 2559            && self.change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel())
 2560        {
 2561            return;
 2562        }
 2563
 2564        cx.propagate();
 2565    }
 2566
 2567    pub fn dismiss_menus_and_popups(
 2568        &mut self,
 2569        should_report_inline_completion_event: bool,
 2570        window: &mut Window,
 2571        cx: &mut Context<Self>,
 2572    ) -> bool {
 2573        if self.take_rename(false, window, cx).is_some() {
 2574            return true;
 2575        }
 2576
 2577        if hide_hover(self, cx) {
 2578            return true;
 2579        }
 2580
 2581        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2582            return true;
 2583        }
 2584
 2585        if self.hide_context_menu(window, cx).is_some() {
 2586            return true;
 2587        }
 2588
 2589        if self.mouse_context_menu.take().is_some() {
 2590            return true;
 2591        }
 2592
 2593        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2594            return true;
 2595        }
 2596
 2597        if self.snippet_stack.pop().is_some() {
 2598            return true;
 2599        }
 2600
 2601        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2602            self.dismiss_diagnostics(cx);
 2603            return true;
 2604        }
 2605
 2606        false
 2607    }
 2608
 2609    fn linked_editing_ranges_for(
 2610        &self,
 2611        selection: Range<text::Anchor>,
 2612        cx: &App,
 2613    ) -> Option<HashMap<Entity<Buffer>, Vec<Range<text::Anchor>>>> {
 2614        if self.linked_edit_ranges.is_empty() {
 2615            return None;
 2616        }
 2617        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2618            selection.end.buffer_id.and_then(|end_buffer_id| {
 2619                if selection.start.buffer_id != Some(end_buffer_id) {
 2620                    return None;
 2621                }
 2622                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2623                let snapshot = buffer.read(cx).snapshot();
 2624                self.linked_edit_ranges
 2625                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2626                    .map(|ranges| (ranges, snapshot, buffer))
 2627            })?;
 2628        use text::ToOffset as TO;
 2629        // find offset from the start of current range to current cursor position
 2630        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2631
 2632        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2633        let start_difference = start_offset - start_byte_offset;
 2634        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2635        let end_difference = end_offset - start_byte_offset;
 2636        // Current range has associated linked ranges.
 2637        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2638        for range in linked_ranges.iter() {
 2639            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2640            let end_offset = start_offset + end_difference;
 2641            let start_offset = start_offset + start_difference;
 2642            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2643                continue;
 2644            }
 2645            if self.selections.disjoint_anchor_ranges().any(|s| {
 2646                if s.start.buffer_id != selection.start.buffer_id
 2647                    || s.end.buffer_id != selection.end.buffer_id
 2648                {
 2649                    return false;
 2650                }
 2651                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2652                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2653            }) {
 2654                continue;
 2655            }
 2656            let start = buffer_snapshot.anchor_after(start_offset);
 2657            let end = buffer_snapshot.anchor_after(end_offset);
 2658            linked_edits
 2659                .entry(buffer.clone())
 2660                .or_default()
 2661                .push(start..end);
 2662        }
 2663        Some(linked_edits)
 2664    }
 2665
 2666    pub fn handle_input(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 2667        let text: Arc<str> = text.into();
 2668
 2669        if self.read_only(cx) {
 2670            return;
 2671        }
 2672
 2673        let selections = self.selections.all_adjusted(cx);
 2674        let mut bracket_inserted = false;
 2675        let mut edits = Vec::new();
 2676        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2677        let mut new_selections = Vec::with_capacity(selections.len());
 2678        let mut new_autoclose_regions = Vec::new();
 2679        let snapshot = self.buffer.read(cx).read(cx);
 2680
 2681        for (selection, autoclose_region) in
 2682            self.selections_with_autoclose_regions(selections, &snapshot)
 2683        {
 2684            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2685                // Determine if the inserted text matches the opening or closing
 2686                // bracket of any of this language's bracket pairs.
 2687                let mut bracket_pair = None;
 2688                let mut is_bracket_pair_start = false;
 2689                let mut is_bracket_pair_end = false;
 2690                if !text.is_empty() {
 2691                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2692                    //  and they are removing the character that triggered IME popup.
 2693                    for (pair, enabled) in scope.brackets() {
 2694                        if !pair.close && !pair.surround {
 2695                            continue;
 2696                        }
 2697
 2698                        if enabled && pair.start.ends_with(text.as_ref()) {
 2699                            let prefix_len = pair.start.len() - text.len();
 2700                            let preceding_text_matches_prefix = prefix_len == 0
 2701                                || (selection.start.column >= (prefix_len as u32)
 2702                                    && snapshot.contains_str_at(
 2703                                        Point::new(
 2704                                            selection.start.row,
 2705                                            selection.start.column - (prefix_len as u32),
 2706                                        ),
 2707                                        &pair.start[..prefix_len],
 2708                                    ));
 2709                            if preceding_text_matches_prefix {
 2710                                bracket_pair = Some(pair.clone());
 2711                                is_bracket_pair_start = true;
 2712                                break;
 2713                            }
 2714                        }
 2715                        if pair.end.as_str() == text.as_ref() {
 2716                            bracket_pair = Some(pair.clone());
 2717                            is_bracket_pair_end = true;
 2718                            break;
 2719                        }
 2720                    }
 2721                }
 2722
 2723                if let Some(bracket_pair) = bracket_pair {
 2724                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2725                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2726                    let auto_surround =
 2727                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2728                    if selection.is_empty() {
 2729                        if is_bracket_pair_start {
 2730                            // If the inserted text is a suffix of an opening bracket and the
 2731                            // selection is preceded by the rest of the opening bracket, then
 2732                            // insert the closing bracket.
 2733                            let following_text_allows_autoclose = snapshot
 2734                                .chars_at(selection.start)
 2735                                .next()
 2736                                .map_or(true, |c| scope.should_autoclose_before(c));
 2737
 2738                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2739                                && bracket_pair.start.len() == 1
 2740                            {
 2741                                let target = bracket_pair.start.chars().next().unwrap();
 2742                                let current_line_count = snapshot
 2743                                    .reversed_chars_at(selection.start)
 2744                                    .take_while(|&c| c != '\n')
 2745                                    .filter(|&c| c == target)
 2746                                    .count();
 2747                                current_line_count % 2 == 1
 2748                            } else {
 2749                                false
 2750                            };
 2751
 2752                            if autoclose
 2753                                && bracket_pair.close
 2754                                && following_text_allows_autoclose
 2755                                && !is_closing_quote
 2756                            {
 2757                                let anchor = snapshot.anchor_before(selection.end);
 2758                                new_selections.push((selection.map(|_| anchor), text.len()));
 2759                                new_autoclose_regions.push((
 2760                                    anchor,
 2761                                    text.len(),
 2762                                    selection.id,
 2763                                    bracket_pair.clone(),
 2764                                ));
 2765                                edits.push((
 2766                                    selection.range(),
 2767                                    format!("{}{}", text, bracket_pair.end).into(),
 2768                                ));
 2769                                bracket_inserted = true;
 2770                                continue;
 2771                            }
 2772                        }
 2773
 2774                        if let Some(region) = autoclose_region {
 2775                            // If the selection is followed by an auto-inserted closing bracket,
 2776                            // then don't insert that closing bracket again; just move the selection
 2777                            // past the closing bracket.
 2778                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2779                                && text.as_ref() == region.pair.end.as_str();
 2780                            if should_skip {
 2781                                let anchor = snapshot.anchor_after(selection.end);
 2782                                new_selections
 2783                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2784                                continue;
 2785                            }
 2786                        }
 2787
 2788                        let always_treat_brackets_as_autoclosed = snapshot
 2789                            .settings_at(selection.start, cx)
 2790                            .always_treat_brackets_as_autoclosed;
 2791                        if always_treat_brackets_as_autoclosed
 2792                            && is_bracket_pair_end
 2793                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2794                        {
 2795                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2796                            // and the inserted text is a closing bracket and the selection is followed
 2797                            // by the closing bracket then move the selection past the closing bracket.
 2798                            let anchor = snapshot.anchor_after(selection.end);
 2799                            new_selections.push((selection.map(|_| anchor), text.len()));
 2800                            continue;
 2801                        }
 2802                    }
 2803                    // If an opening bracket is 1 character long and is typed while
 2804                    // text is selected, then surround that text with the bracket pair.
 2805                    else if auto_surround
 2806                        && bracket_pair.surround
 2807                        && is_bracket_pair_start
 2808                        && bracket_pair.start.chars().count() == 1
 2809                    {
 2810                        edits.push((selection.start..selection.start, text.clone()));
 2811                        edits.push((
 2812                            selection.end..selection.end,
 2813                            bracket_pair.end.as_str().into(),
 2814                        ));
 2815                        bracket_inserted = true;
 2816                        new_selections.push((
 2817                            Selection {
 2818                                id: selection.id,
 2819                                start: snapshot.anchor_after(selection.start),
 2820                                end: snapshot.anchor_before(selection.end),
 2821                                reversed: selection.reversed,
 2822                                goal: selection.goal,
 2823                            },
 2824                            0,
 2825                        ));
 2826                        continue;
 2827                    }
 2828                }
 2829            }
 2830
 2831            if self.auto_replace_emoji_shortcode
 2832                && selection.is_empty()
 2833                && text.as_ref().ends_with(':')
 2834            {
 2835                if let Some(possible_emoji_short_code) =
 2836                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2837                {
 2838                    if !possible_emoji_short_code.is_empty() {
 2839                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2840                            let emoji_shortcode_start = Point::new(
 2841                                selection.start.row,
 2842                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2843                            );
 2844
 2845                            // Remove shortcode from buffer
 2846                            edits.push((
 2847                                emoji_shortcode_start..selection.start,
 2848                                "".to_string().into(),
 2849                            ));
 2850                            new_selections.push((
 2851                                Selection {
 2852                                    id: selection.id,
 2853                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2854                                    end: snapshot.anchor_before(selection.start),
 2855                                    reversed: selection.reversed,
 2856                                    goal: selection.goal,
 2857                                },
 2858                                0,
 2859                            ));
 2860
 2861                            // Insert emoji
 2862                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2863                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2864                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2865
 2866                            continue;
 2867                        }
 2868                    }
 2869                }
 2870            }
 2871
 2872            // If not handling any auto-close operation, then just replace the selected
 2873            // text with the given input and move the selection to the end of the
 2874            // newly inserted text.
 2875            let anchor = snapshot.anchor_after(selection.end);
 2876            if !self.linked_edit_ranges.is_empty() {
 2877                let start_anchor = snapshot.anchor_before(selection.start);
 2878
 2879                let is_word_char = text.chars().next().map_or(true, |char| {
 2880                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2881                    classifier.is_word(char)
 2882                });
 2883
 2884                if is_word_char {
 2885                    if let Some(ranges) = self
 2886                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2887                    {
 2888                        for (buffer, edits) in ranges {
 2889                            linked_edits
 2890                                .entry(buffer.clone())
 2891                                .or_default()
 2892                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2893                        }
 2894                    }
 2895                }
 2896            }
 2897
 2898            new_selections.push((selection.map(|_| anchor), 0));
 2899            edits.push((selection.start..selection.end, text.clone()));
 2900        }
 2901
 2902        drop(snapshot);
 2903
 2904        self.transact(window, cx, |this, window, cx| {
 2905            this.buffer.update(cx, |buffer, cx| {
 2906                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2907            });
 2908            for (buffer, edits) in linked_edits {
 2909                buffer.update(cx, |buffer, cx| {
 2910                    let snapshot = buffer.snapshot();
 2911                    let edits = edits
 2912                        .into_iter()
 2913                        .map(|(range, text)| {
 2914                            use text::ToPoint as TP;
 2915                            let end_point = TP::to_point(&range.end, &snapshot);
 2916                            let start_point = TP::to_point(&range.start, &snapshot);
 2917                            (start_point..end_point, text)
 2918                        })
 2919                        .sorted_by_key(|(range, _)| range.start)
 2920                        .collect::<Vec<_>>();
 2921                    buffer.edit(edits, None, cx);
 2922                })
 2923            }
 2924            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2925            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2926            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2927            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2928                .zip(new_selection_deltas)
 2929                .map(|(selection, delta)| Selection {
 2930                    id: selection.id,
 2931                    start: selection.start + delta,
 2932                    end: selection.end + delta,
 2933                    reversed: selection.reversed,
 2934                    goal: SelectionGoal::None,
 2935                })
 2936                .collect::<Vec<_>>();
 2937
 2938            let mut i = 0;
 2939            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2940                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2941                let start = map.buffer_snapshot.anchor_before(position);
 2942                let end = map.buffer_snapshot.anchor_after(position);
 2943                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2944                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2945                        Ordering::Less => i += 1,
 2946                        Ordering::Greater => break,
 2947                        Ordering::Equal => {
 2948                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2949                                Ordering::Less => i += 1,
 2950                                Ordering::Equal => break,
 2951                                Ordering::Greater => break,
 2952                            }
 2953                        }
 2954                    }
 2955                }
 2956                this.autoclose_regions.insert(
 2957                    i,
 2958                    AutocloseRegion {
 2959                        selection_id,
 2960                        range: start..end,
 2961                        pair,
 2962                    },
 2963                );
 2964            }
 2965
 2966            let had_active_inline_completion = this.has_active_inline_completion();
 2967            this.change_selections_inner(Some(Autoscroll::fit()), false, window, cx, |s| {
 2968                s.select(new_selections)
 2969            });
 2970
 2971            if !bracket_inserted {
 2972                if let Some(on_type_format_task) =
 2973                    this.trigger_on_type_formatting(text.to_string(), window, cx)
 2974                {
 2975                    on_type_format_task.detach_and_log_err(cx);
 2976                }
 2977            }
 2978
 2979            let editor_settings = EditorSettings::get_global(cx);
 2980            if bracket_inserted
 2981                && (editor_settings.auto_signature_help
 2982                    || editor_settings.show_signature_help_after_edits)
 2983            {
 2984                this.show_signature_help(&ShowSignatureHelp, window, cx);
 2985            }
 2986
 2987            let trigger_in_words =
 2988                this.show_inline_completions_in_menu(cx) || !had_active_inline_completion;
 2989            this.trigger_completion_on_input(&text, trigger_in_words, window, cx);
 2990            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 2991            this.refresh_inline_completion(true, false, window, cx);
 2992        });
 2993    }
 2994
 2995    fn find_possible_emoji_shortcode_at_position(
 2996        snapshot: &MultiBufferSnapshot,
 2997        position: Point,
 2998    ) -> Option<String> {
 2999        let mut chars = Vec::new();
 3000        let mut found_colon = false;
 3001        for char in snapshot.reversed_chars_at(position).take(100) {
 3002            // Found a possible emoji shortcode in the middle of the buffer
 3003            if found_colon {
 3004                if char.is_whitespace() {
 3005                    chars.reverse();
 3006                    return Some(chars.iter().collect());
 3007                }
 3008                // If the previous character is not a whitespace, we are in the middle of a word
 3009                // and we only want to complete the shortcode if the word is made up of other emojis
 3010                let mut containing_word = String::new();
 3011                for ch in snapshot
 3012                    .reversed_chars_at(position)
 3013                    .skip(chars.len() + 1)
 3014                    .take(100)
 3015                {
 3016                    if ch.is_whitespace() {
 3017                        break;
 3018                    }
 3019                    containing_word.push(ch);
 3020                }
 3021                let containing_word = containing_word.chars().rev().collect::<String>();
 3022                if util::word_consists_of_emojis(containing_word.as_str()) {
 3023                    chars.reverse();
 3024                    return Some(chars.iter().collect());
 3025                }
 3026            }
 3027
 3028            if char.is_whitespace() || !char.is_ascii() {
 3029                return None;
 3030            }
 3031            if char == ':' {
 3032                found_colon = true;
 3033            } else {
 3034                chars.push(char);
 3035            }
 3036        }
 3037        // Found a possible emoji shortcode at the beginning of the buffer
 3038        chars.reverse();
 3039        Some(chars.iter().collect())
 3040    }
 3041
 3042    pub fn newline(&mut self, _: &Newline, window: &mut Window, cx: &mut Context<Self>) {
 3043        self.transact(window, cx, |this, window, cx| {
 3044            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 3045                let selections = this.selections.all::<usize>(cx);
 3046                let multi_buffer = this.buffer.read(cx);
 3047                let buffer = multi_buffer.snapshot(cx);
 3048                selections
 3049                    .iter()
 3050                    .map(|selection| {
 3051                        let start_point = selection.start.to_point(&buffer);
 3052                        let mut indent =
 3053                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 3054                        indent.len = cmp::min(indent.len, start_point.column);
 3055                        let start = selection.start;
 3056                        let end = selection.end;
 3057                        let selection_is_empty = start == end;
 3058                        let language_scope = buffer.language_scope_at(start);
 3059                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 3060                            &language_scope
 3061                        {
 3062                            let leading_whitespace_len = buffer
 3063                                .reversed_chars_at(start)
 3064                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3065                                .map(|c| c.len_utf8())
 3066                                .sum::<usize>();
 3067
 3068                            let trailing_whitespace_len = buffer
 3069                                .chars_at(end)
 3070                                .take_while(|c| c.is_whitespace() && *c != '\n')
 3071                                .map(|c| c.len_utf8())
 3072                                .sum::<usize>();
 3073
 3074                            let insert_extra_newline =
 3075                                language.brackets().any(|(pair, enabled)| {
 3076                                    let pair_start = pair.start.trim_end();
 3077                                    let pair_end = pair.end.trim_start();
 3078
 3079                                    enabled
 3080                                        && pair.newline
 3081                                        && buffer.contains_str_at(
 3082                                            end + trailing_whitespace_len,
 3083                                            pair_end,
 3084                                        )
 3085                                        && buffer.contains_str_at(
 3086                                            (start - leading_whitespace_len)
 3087                                                .saturating_sub(pair_start.len()),
 3088                                            pair_start,
 3089                                        )
 3090                                });
 3091
 3092                            // Comment extension on newline is allowed only for cursor selections
 3093                            let comment_delimiter = maybe!({
 3094                                if !selection_is_empty {
 3095                                    return None;
 3096                                }
 3097
 3098                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 3099                                    return None;
 3100                                }
 3101
 3102                                let delimiters = language.line_comment_prefixes();
 3103                                let max_len_of_delimiter =
 3104                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 3105                                let (snapshot, range) =
 3106                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 3107
 3108                                let mut index_of_first_non_whitespace = 0;
 3109                                let comment_candidate = snapshot
 3110                                    .chars_for_range(range)
 3111                                    .skip_while(|c| {
 3112                                        let should_skip = c.is_whitespace();
 3113                                        if should_skip {
 3114                                            index_of_first_non_whitespace += 1;
 3115                                        }
 3116                                        should_skip
 3117                                    })
 3118                                    .take(max_len_of_delimiter)
 3119                                    .collect::<String>();
 3120                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3121                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3122                                })?;
 3123                                let cursor_is_placed_after_comment_marker =
 3124                                    index_of_first_non_whitespace + comment_prefix.len()
 3125                                        <= start_point.column as usize;
 3126                                if cursor_is_placed_after_comment_marker {
 3127                                    Some(comment_prefix.clone())
 3128                                } else {
 3129                                    None
 3130                                }
 3131                            });
 3132                            (comment_delimiter, insert_extra_newline)
 3133                        } else {
 3134                            (None, false)
 3135                        };
 3136
 3137                        let capacity_for_delimiter = comment_delimiter
 3138                            .as_deref()
 3139                            .map(str::len)
 3140                            .unwrap_or_default();
 3141                        let mut new_text =
 3142                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3143                        new_text.push('\n');
 3144                        new_text.extend(indent.chars());
 3145                        if let Some(delimiter) = &comment_delimiter {
 3146                            new_text.push_str(delimiter);
 3147                        }
 3148                        if insert_extra_newline {
 3149                            new_text = new_text.repeat(2);
 3150                        }
 3151
 3152                        let anchor = buffer.anchor_after(end);
 3153                        let new_selection = selection.map(|_| anchor);
 3154                        (
 3155                            (start..end, new_text),
 3156                            (insert_extra_newline, new_selection),
 3157                        )
 3158                    })
 3159                    .unzip()
 3160            };
 3161
 3162            this.edit_with_autoindent(edits, cx);
 3163            let buffer = this.buffer.read(cx).snapshot(cx);
 3164            let new_selections = selection_fixup_info
 3165                .into_iter()
 3166                .map(|(extra_newline_inserted, new_selection)| {
 3167                    let mut cursor = new_selection.end.to_point(&buffer);
 3168                    if extra_newline_inserted {
 3169                        cursor.row -= 1;
 3170                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3171                    }
 3172                    new_selection.map(|_| cursor)
 3173                })
 3174                .collect();
 3175
 3176            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3177                s.select(new_selections)
 3178            });
 3179            this.refresh_inline_completion(true, false, window, cx);
 3180        });
 3181    }
 3182
 3183    pub fn newline_above(&mut self, _: &NewlineAbove, window: &mut Window, cx: &mut Context<Self>) {
 3184        let buffer = self.buffer.read(cx);
 3185        let snapshot = buffer.snapshot(cx);
 3186
 3187        let mut edits = Vec::new();
 3188        let mut rows = Vec::new();
 3189
 3190        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3191            let cursor = selection.head();
 3192            let row = cursor.row;
 3193
 3194            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3195
 3196            let newline = "\n".to_string();
 3197            edits.push((start_of_line..start_of_line, newline));
 3198
 3199            rows.push(row + rows_inserted as u32);
 3200        }
 3201
 3202        self.transact(window, cx, |editor, window, cx| {
 3203            editor.edit(edits, cx);
 3204
 3205            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3206                let mut index = 0;
 3207                s.move_cursors_with(|map, _, _| {
 3208                    let row = rows[index];
 3209                    index += 1;
 3210
 3211                    let point = Point::new(row, 0);
 3212                    let boundary = map.next_line_boundary(point).1;
 3213                    let clipped = map.clip_point(boundary, Bias::Left);
 3214
 3215                    (clipped, SelectionGoal::None)
 3216                });
 3217            });
 3218
 3219            let mut indent_edits = Vec::new();
 3220            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3221            for row in rows {
 3222                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3223                for (row, indent) in indents {
 3224                    if indent.len == 0 {
 3225                        continue;
 3226                    }
 3227
 3228                    let text = match indent.kind {
 3229                        IndentKind::Space => " ".repeat(indent.len as usize),
 3230                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3231                    };
 3232                    let point = Point::new(row.0, 0);
 3233                    indent_edits.push((point..point, text));
 3234                }
 3235            }
 3236            editor.edit(indent_edits, cx);
 3237        });
 3238    }
 3239
 3240    pub fn newline_below(&mut self, _: &NewlineBelow, window: &mut Window, cx: &mut Context<Self>) {
 3241        let buffer = self.buffer.read(cx);
 3242        let snapshot = buffer.snapshot(cx);
 3243
 3244        let mut edits = Vec::new();
 3245        let mut rows = Vec::new();
 3246        let mut rows_inserted = 0;
 3247
 3248        for selection in self.selections.all_adjusted(cx) {
 3249            let cursor = selection.head();
 3250            let row = cursor.row;
 3251
 3252            let point = Point::new(row + 1, 0);
 3253            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3254
 3255            let newline = "\n".to_string();
 3256            edits.push((start_of_line..start_of_line, newline));
 3257
 3258            rows_inserted += 1;
 3259            rows.push(row + rows_inserted);
 3260        }
 3261
 3262        self.transact(window, cx, |editor, window, cx| {
 3263            editor.edit(edits, cx);
 3264
 3265            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3266                let mut index = 0;
 3267                s.move_cursors_with(|map, _, _| {
 3268                    let row = rows[index];
 3269                    index += 1;
 3270
 3271                    let point = Point::new(row, 0);
 3272                    let boundary = map.next_line_boundary(point).1;
 3273                    let clipped = map.clip_point(boundary, Bias::Left);
 3274
 3275                    (clipped, SelectionGoal::None)
 3276                });
 3277            });
 3278
 3279            let mut indent_edits = Vec::new();
 3280            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3281            for row in rows {
 3282                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3283                for (row, indent) in indents {
 3284                    if indent.len == 0 {
 3285                        continue;
 3286                    }
 3287
 3288                    let text = match indent.kind {
 3289                        IndentKind::Space => " ".repeat(indent.len as usize),
 3290                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3291                    };
 3292                    let point = Point::new(row.0, 0);
 3293                    indent_edits.push((point..point, text));
 3294                }
 3295            }
 3296            editor.edit(indent_edits, cx);
 3297        });
 3298    }
 3299
 3300    pub fn insert(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
 3301        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3302            original_indent_columns: Vec::new(),
 3303        });
 3304        self.insert_with_autoindent_mode(text, autoindent, window, cx);
 3305    }
 3306
 3307    fn insert_with_autoindent_mode(
 3308        &mut self,
 3309        text: &str,
 3310        autoindent_mode: Option<AutoindentMode>,
 3311        window: &mut Window,
 3312        cx: &mut Context<Self>,
 3313    ) {
 3314        if self.read_only(cx) {
 3315            return;
 3316        }
 3317
 3318        let text: Arc<str> = text.into();
 3319        self.transact(window, cx, |this, window, cx| {
 3320            let old_selections = this.selections.all_adjusted(cx);
 3321            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3322                let anchors = {
 3323                    let snapshot = buffer.read(cx);
 3324                    old_selections
 3325                        .iter()
 3326                        .map(|s| {
 3327                            let anchor = snapshot.anchor_after(s.head());
 3328                            s.map(|_| anchor)
 3329                        })
 3330                        .collect::<Vec<_>>()
 3331                };
 3332                buffer.edit(
 3333                    old_selections
 3334                        .iter()
 3335                        .map(|s| (s.start..s.end, text.clone())),
 3336                    autoindent_mode,
 3337                    cx,
 3338                );
 3339                anchors
 3340            });
 3341
 3342            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 3343                s.select_anchors(selection_anchors);
 3344            });
 3345
 3346            cx.notify();
 3347        });
 3348    }
 3349
 3350    fn trigger_completion_on_input(
 3351        &mut self,
 3352        text: &str,
 3353        trigger_in_words: bool,
 3354        window: &mut Window,
 3355        cx: &mut Context<Self>,
 3356    ) {
 3357        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3358            self.show_completions(
 3359                &ShowCompletions {
 3360                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3361                },
 3362                window,
 3363                cx,
 3364            );
 3365        } else {
 3366            self.hide_context_menu(window, cx);
 3367        }
 3368    }
 3369
 3370    fn is_completion_trigger(
 3371        &self,
 3372        text: &str,
 3373        trigger_in_words: bool,
 3374        cx: &mut Context<Self>,
 3375    ) -> bool {
 3376        let position = self.selections.newest_anchor().head();
 3377        let multibuffer = self.buffer.read(cx);
 3378        let Some(buffer) = position
 3379            .buffer_id
 3380            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3381        else {
 3382            return false;
 3383        };
 3384
 3385        if let Some(completion_provider) = &self.completion_provider {
 3386            completion_provider.is_completion_trigger(
 3387                &buffer,
 3388                position.text_anchor,
 3389                text,
 3390                trigger_in_words,
 3391                cx,
 3392            )
 3393        } else {
 3394            false
 3395        }
 3396    }
 3397
 3398    /// If any empty selections is touching the start of its innermost containing autoclose
 3399    /// region, expand it to select the brackets.
 3400    fn select_autoclose_pair(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 3401        let selections = self.selections.all::<usize>(cx);
 3402        let buffer = self.buffer.read(cx).read(cx);
 3403        let new_selections = self
 3404            .selections_with_autoclose_regions(selections, &buffer)
 3405            .map(|(mut selection, region)| {
 3406                if !selection.is_empty() {
 3407                    return selection;
 3408                }
 3409
 3410                if let Some(region) = region {
 3411                    let mut range = region.range.to_offset(&buffer);
 3412                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3413                        range.start -= region.pair.start.len();
 3414                        if buffer.contains_str_at(range.start, &region.pair.start)
 3415                            && buffer.contains_str_at(range.end, &region.pair.end)
 3416                        {
 3417                            range.end += region.pair.end.len();
 3418                            selection.start = range.start;
 3419                            selection.end = range.end;
 3420
 3421                            return selection;
 3422                        }
 3423                    }
 3424                }
 3425
 3426                let always_treat_brackets_as_autoclosed = buffer
 3427                    .settings_at(selection.start, cx)
 3428                    .always_treat_brackets_as_autoclosed;
 3429
 3430                if !always_treat_brackets_as_autoclosed {
 3431                    return selection;
 3432                }
 3433
 3434                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3435                    for (pair, enabled) in scope.brackets() {
 3436                        if !enabled || !pair.close {
 3437                            continue;
 3438                        }
 3439
 3440                        if buffer.contains_str_at(selection.start, &pair.end) {
 3441                            let pair_start_len = pair.start.len();
 3442                            if buffer.contains_str_at(
 3443                                selection.start.saturating_sub(pair_start_len),
 3444                                &pair.start,
 3445                            ) {
 3446                                selection.start -= pair_start_len;
 3447                                selection.end += pair.end.len();
 3448
 3449                                return selection;
 3450                            }
 3451                        }
 3452                    }
 3453                }
 3454
 3455                selection
 3456            })
 3457            .collect();
 3458
 3459        drop(buffer);
 3460        self.change_selections(None, window, cx, |selections| {
 3461            selections.select(new_selections)
 3462        });
 3463    }
 3464
 3465    /// Iterate the given selections, and for each one, find the smallest surrounding
 3466    /// autoclose region. This uses the ordering of the selections and the autoclose
 3467    /// regions to avoid repeated comparisons.
 3468    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3469        &'a self,
 3470        selections: impl IntoIterator<Item = Selection<D>>,
 3471        buffer: &'a MultiBufferSnapshot,
 3472    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3473        let mut i = 0;
 3474        let mut regions = self.autoclose_regions.as_slice();
 3475        selections.into_iter().map(move |selection| {
 3476            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3477
 3478            let mut enclosing = None;
 3479            while let Some(pair_state) = regions.get(i) {
 3480                if pair_state.range.end.to_offset(buffer) < range.start {
 3481                    regions = &regions[i + 1..];
 3482                    i = 0;
 3483                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3484                    break;
 3485                } else {
 3486                    if pair_state.selection_id == selection.id {
 3487                        enclosing = Some(pair_state);
 3488                    }
 3489                    i += 1;
 3490                }
 3491            }
 3492
 3493            (selection, enclosing)
 3494        })
 3495    }
 3496
 3497    /// Remove any autoclose regions that no longer contain their selection.
 3498    fn invalidate_autoclose_regions(
 3499        &mut self,
 3500        mut selections: &[Selection<Anchor>],
 3501        buffer: &MultiBufferSnapshot,
 3502    ) {
 3503        self.autoclose_regions.retain(|state| {
 3504            let mut i = 0;
 3505            while let Some(selection) = selections.get(i) {
 3506                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3507                    selections = &selections[1..];
 3508                    continue;
 3509                }
 3510                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3511                    break;
 3512                }
 3513                if selection.id == state.selection_id {
 3514                    return true;
 3515                } else {
 3516                    i += 1;
 3517                }
 3518            }
 3519            false
 3520        });
 3521    }
 3522
 3523    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3524        let offset = position.to_offset(buffer);
 3525        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3526        if offset > word_range.start && kind == Some(CharKind::Word) {
 3527            Some(
 3528                buffer
 3529                    .text_for_range(word_range.start..offset)
 3530                    .collect::<String>(),
 3531            )
 3532        } else {
 3533            None
 3534        }
 3535    }
 3536
 3537    pub fn toggle_inlay_hints(
 3538        &mut self,
 3539        _: &ToggleInlayHints,
 3540        _: &mut Window,
 3541        cx: &mut Context<Self>,
 3542    ) {
 3543        self.refresh_inlay_hints(
 3544            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3545            cx,
 3546        );
 3547    }
 3548
 3549    pub fn inlay_hints_enabled(&self) -> bool {
 3550        self.inlay_hint_cache.enabled
 3551    }
 3552
 3553    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut Context<Self>) {
 3554        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3555            return;
 3556        }
 3557
 3558        let reason_description = reason.description();
 3559        let ignore_debounce = matches!(
 3560            reason,
 3561            InlayHintRefreshReason::SettingsChange(_)
 3562                | InlayHintRefreshReason::Toggle(_)
 3563                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3564        );
 3565        let (invalidate_cache, required_languages) = match reason {
 3566            InlayHintRefreshReason::Toggle(enabled) => {
 3567                self.inlay_hint_cache.enabled = enabled;
 3568                if enabled {
 3569                    (InvalidationStrategy::RefreshRequested, None)
 3570                } else {
 3571                    self.inlay_hint_cache.clear();
 3572                    self.splice_inlays(
 3573                        &self
 3574                            .visible_inlay_hints(cx)
 3575                            .iter()
 3576                            .map(|inlay| inlay.id)
 3577                            .collect::<Vec<InlayId>>(),
 3578                        Vec::new(),
 3579                        cx,
 3580                    );
 3581                    return;
 3582                }
 3583            }
 3584            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3585                match self.inlay_hint_cache.update_settings(
 3586                    &self.buffer,
 3587                    new_settings,
 3588                    self.visible_inlay_hints(cx),
 3589                    cx,
 3590                ) {
 3591                    ControlFlow::Break(Some(InlaySplice {
 3592                        to_remove,
 3593                        to_insert,
 3594                    })) => {
 3595                        self.splice_inlays(&to_remove, to_insert, cx);
 3596                        return;
 3597                    }
 3598                    ControlFlow::Break(None) => return,
 3599                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3600                }
 3601            }
 3602            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3603                if let Some(InlaySplice {
 3604                    to_remove,
 3605                    to_insert,
 3606                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3607                {
 3608                    self.splice_inlays(&to_remove, to_insert, cx);
 3609                }
 3610                return;
 3611            }
 3612            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3613            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3614                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3615            }
 3616            InlayHintRefreshReason::RefreshRequested => {
 3617                (InvalidationStrategy::RefreshRequested, None)
 3618            }
 3619        };
 3620
 3621        if let Some(InlaySplice {
 3622            to_remove,
 3623            to_insert,
 3624        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3625            reason_description,
 3626            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3627            invalidate_cache,
 3628            ignore_debounce,
 3629            cx,
 3630        ) {
 3631            self.splice_inlays(&to_remove, to_insert, cx);
 3632        }
 3633    }
 3634
 3635    fn visible_inlay_hints(&self, cx: &Context<Editor>) -> Vec<Inlay> {
 3636        self.display_map
 3637            .read(cx)
 3638            .current_inlays()
 3639            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3640            .cloned()
 3641            .collect()
 3642    }
 3643
 3644    pub fn excerpts_for_inlay_hints_query(
 3645        &self,
 3646        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3647        cx: &mut Context<Editor>,
 3648    ) -> HashMap<ExcerptId, (Entity<Buffer>, clock::Global, Range<usize>)> {
 3649        let Some(project) = self.project.as_ref() else {
 3650            return HashMap::default();
 3651        };
 3652        let project = project.read(cx);
 3653        let multi_buffer = self.buffer().read(cx);
 3654        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3655        let multi_buffer_visible_start = self
 3656            .scroll_manager
 3657            .anchor()
 3658            .anchor
 3659            .to_point(&multi_buffer_snapshot);
 3660        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3661            multi_buffer_visible_start
 3662                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3663            Bias::Left,
 3664        );
 3665        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3666        multi_buffer_snapshot
 3667            .range_to_buffer_ranges(multi_buffer_visible_range)
 3668            .into_iter()
 3669            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3670            .filter_map(|(buffer, excerpt_visible_range, excerpt_id)| {
 3671                let buffer_file = project::File::from_dyn(buffer.file())?;
 3672                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3673                let worktree_entry = buffer_worktree
 3674                    .read(cx)
 3675                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3676                if worktree_entry.is_ignored {
 3677                    return None;
 3678                }
 3679
 3680                let language = buffer.language()?;
 3681                if let Some(restrict_to_languages) = restrict_to_languages {
 3682                    if !restrict_to_languages.contains(language) {
 3683                        return None;
 3684                    }
 3685                }
 3686                Some((
 3687                    excerpt_id,
 3688                    (
 3689                        multi_buffer.buffer(buffer.remote_id()).unwrap(),
 3690                        buffer.version().clone(),
 3691                        excerpt_visible_range,
 3692                    ),
 3693                ))
 3694            })
 3695            .collect()
 3696    }
 3697
 3698    pub fn text_layout_details(&self, window: &mut Window) -> TextLayoutDetails {
 3699        TextLayoutDetails {
 3700            text_system: window.text_system().clone(),
 3701            editor_style: self.style.clone().unwrap(),
 3702            rem_size: window.rem_size(),
 3703            scroll_anchor: self.scroll_manager.anchor(),
 3704            visible_rows: self.visible_line_count(),
 3705            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3706        }
 3707    }
 3708
 3709    pub fn splice_inlays(
 3710        &self,
 3711        to_remove: &[InlayId],
 3712        to_insert: Vec<Inlay>,
 3713        cx: &mut Context<Self>,
 3714    ) {
 3715        self.display_map.update(cx, |display_map, cx| {
 3716            display_map.splice_inlays(to_remove, to_insert, cx)
 3717        });
 3718        cx.notify();
 3719    }
 3720
 3721    fn trigger_on_type_formatting(
 3722        &self,
 3723        input: String,
 3724        window: &mut Window,
 3725        cx: &mut Context<Self>,
 3726    ) -> Option<Task<Result<()>>> {
 3727        if input.len() != 1 {
 3728            return None;
 3729        }
 3730
 3731        let project = self.project.as_ref()?;
 3732        let position = self.selections.newest_anchor().head();
 3733        let (buffer, buffer_position) = self
 3734            .buffer
 3735            .read(cx)
 3736            .text_anchor_for_position(position, cx)?;
 3737
 3738        let settings = language_settings::language_settings(
 3739            buffer
 3740                .read(cx)
 3741                .language_at(buffer_position)
 3742                .map(|l| l.name()),
 3743            buffer.read(cx).file(),
 3744            cx,
 3745        );
 3746        if !settings.use_on_type_format {
 3747            return None;
 3748        }
 3749
 3750        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3751        // hence we do LSP request & edit on host side only — add formats to host's history.
 3752        let push_to_lsp_host_history = true;
 3753        // If this is not the host, append its history with new edits.
 3754        let push_to_client_history = project.read(cx).is_via_collab();
 3755
 3756        let on_type_formatting = project.update(cx, |project, cx| {
 3757            project.on_type_format(
 3758                buffer.clone(),
 3759                buffer_position,
 3760                input,
 3761                push_to_lsp_host_history,
 3762                cx,
 3763            )
 3764        });
 3765        Some(cx.spawn_in(window, |editor, mut cx| async move {
 3766            if let Some(transaction) = on_type_formatting.await? {
 3767                if push_to_client_history {
 3768                    buffer
 3769                        .update(&mut cx, |buffer, _| {
 3770                            buffer.push_transaction(transaction, Instant::now());
 3771                        })
 3772                        .ok();
 3773                }
 3774                editor.update(&mut cx, |editor, cx| {
 3775                    editor.refresh_document_highlights(cx);
 3776                })?;
 3777            }
 3778            Ok(())
 3779        }))
 3780    }
 3781
 3782    pub fn show_completions(
 3783        &mut self,
 3784        options: &ShowCompletions,
 3785        window: &mut Window,
 3786        cx: &mut Context<Self>,
 3787    ) {
 3788        if self.pending_rename.is_some() {
 3789            return;
 3790        }
 3791
 3792        let Some(provider) = self.completion_provider.as_ref() else {
 3793            return;
 3794        };
 3795
 3796        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3797            return;
 3798        }
 3799
 3800        let position = self.selections.newest_anchor().head();
 3801        if position.diff_base_anchor.is_some() {
 3802            return;
 3803        }
 3804        let (buffer, buffer_position) =
 3805            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3806                output
 3807            } else {
 3808                return;
 3809            };
 3810        let show_completion_documentation = buffer
 3811            .read(cx)
 3812            .snapshot()
 3813            .settings_at(buffer_position, cx)
 3814            .show_completion_documentation;
 3815
 3816        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3817
 3818        let trigger_kind = match &options.trigger {
 3819            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3820                CompletionTriggerKind::TRIGGER_CHARACTER
 3821            }
 3822            _ => CompletionTriggerKind::INVOKED,
 3823        };
 3824        let completion_context = CompletionContext {
 3825            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3826                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3827                    Some(String::from(trigger))
 3828                } else {
 3829                    None
 3830                }
 3831            }),
 3832            trigger_kind,
 3833        };
 3834        let completions =
 3835            provider.completions(&buffer, buffer_position, completion_context, window, cx);
 3836        let sort_completions = provider.sort_completions();
 3837
 3838        let id = post_inc(&mut self.next_completion_id);
 3839        let task = cx.spawn_in(window, |editor, mut cx| {
 3840            async move {
 3841                editor.update(&mut cx, |this, _| {
 3842                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3843                })?;
 3844                let completions = completions.await.log_err();
 3845                let menu = if let Some(completions) = completions {
 3846                    let mut menu = CompletionsMenu::new(
 3847                        id,
 3848                        sort_completions,
 3849                        show_completion_documentation,
 3850                        position,
 3851                        buffer.clone(),
 3852                        completions.into(),
 3853                    );
 3854
 3855                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3856                        .await;
 3857
 3858                    menu.visible().then_some(menu)
 3859                } else {
 3860                    None
 3861                };
 3862
 3863                editor.update_in(&mut cx, |editor, window, cx| {
 3864                    match editor.context_menu.borrow().as_ref() {
 3865                        None => {}
 3866                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3867                            if prev_menu.id > id {
 3868                                return;
 3869                            }
 3870                        }
 3871                        _ => return,
 3872                    }
 3873
 3874                    if editor.focus_handle.is_focused(window) && menu.is_some() {
 3875                        let mut menu = menu.unwrap();
 3876                        menu.resolve_visible_completions(editor.completion_provider.as_deref(), cx);
 3877
 3878                        *editor.context_menu.borrow_mut() =
 3879                            Some(CodeContextMenu::Completions(menu));
 3880
 3881                        if editor.show_inline_completions_in_menu(cx) {
 3882                            editor.update_visible_inline_completion(window, cx);
 3883                        } else {
 3884                            editor.discard_inline_completion(false, cx);
 3885                        }
 3886
 3887                        cx.notify();
 3888                    } else if editor.completion_tasks.len() <= 1 {
 3889                        // If there are no more completion tasks and the last menu was
 3890                        // empty, we should hide it.
 3891                        let was_hidden = editor.hide_context_menu(window, cx).is_none();
 3892                        // If it was already hidden and we don't show inline
 3893                        // completions in the menu, we should also show the
 3894                        // inline-completion when available.
 3895                        if was_hidden && editor.show_inline_completions_in_menu(cx) {
 3896                            editor.update_visible_inline_completion(window, cx);
 3897                        }
 3898                    }
 3899                })?;
 3900
 3901                Ok::<_, anyhow::Error>(())
 3902            }
 3903            .log_err()
 3904        });
 3905
 3906        self.completion_tasks.push((id, task));
 3907    }
 3908
 3909    pub fn confirm_completion(
 3910        &mut self,
 3911        action: &ConfirmCompletion,
 3912        window: &mut Window,
 3913        cx: &mut Context<Self>,
 3914    ) -> Option<Task<Result<()>>> {
 3915        self.do_completion(action.item_ix, CompletionIntent::Complete, window, cx)
 3916    }
 3917
 3918    pub fn compose_completion(
 3919        &mut self,
 3920        action: &ComposeCompletion,
 3921        window: &mut Window,
 3922        cx: &mut Context<Self>,
 3923    ) -> Option<Task<Result<()>>> {
 3924        self.do_completion(action.item_ix, CompletionIntent::Compose, window, cx)
 3925    }
 3926
 3927    fn do_completion(
 3928        &mut self,
 3929        item_ix: Option<usize>,
 3930        intent: CompletionIntent,
 3931        window: &mut Window,
 3932        cx: &mut Context<Editor>,
 3933    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3934        use language::ToOffset as _;
 3935
 3936        let completions_menu =
 3937            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(window, cx)? {
 3938                menu
 3939            } else {
 3940                return None;
 3941            };
 3942
 3943        let entries = completions_menu.entries.borrow();
 3944        let mat = entries.get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3945        if self.show_inline_completions_in_menu(cx) {
 3946            self.discard_inline_completion(true, cx);
 3947        }
 3948        let candidate_id = mat.candidate_id;
 3949        drop(entries);
 3950
 3951        let buffer_handle = completions_menu.buffer;
 3952        let completion = completions_menu
 3953            .completions
 3954            .borrow()
 3955            .get(candidate_id)?
 3956            .clone();
 3957        cx.stop_propagation();
 3958
 3959        let snippet;
 3960        let text;
 3961
 3962        if completion.is_snippet() {
 3963            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3964            text = snippet.as_ref().unwrap().text.clone();
 3965        } else {
 3966            snippet = None;
 3967            text = completion.new_text.clone();
 3968        };
 3969        let selections = self.selections.all::<usize>(cx);
 3970        let buffer = buffer_handle.read(cx);
 3971        let old_range = completion.old_range.to_offset(buffer);
 3972        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3973
 3974        let newest_selection = self.selections.newest_anchor();
 3975        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3976            return None;
 3977        }
 3978
 3979        let lookbehind = newest_selection
 3980            .start
 3981            .text_anchor
 3982            .to_offset(buffer)
 3983            .saturating_sub(old_range.start);
 3984        let lookahead = old_range
 3985            .end
 3986            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3987        let mut common_prefix_len = old_text
 3988            .bytes()
 3989            .zip(text.bytes())
 3990            .take_while(|(a, b)| a == b)
 3991            .count();
 3992
 3993        let snapshot = self.buffer.read(cx).snapshot(cx);
 3994        let mut range_to_replace: Option<Range<isize>> = None;
 3995        let mut ranges = Vec::new();
 3996        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3997        for selection in &selections {
 3998            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3999                let start = selection.start.saturating_sub(lookbehind);
 4000                let end = selection.end + lookahead;
 4001                if selection.id == newest_selection.id {
 4002                    range_to_replace = Some(
 4003                        ((start + common_prefix_len) as isize - selection.start as isize)
 4004                            ..(end as isize - selection.start as isize),
 4005                    );
 4006                }
 4007                ranges.push(start + common_prefix_len..end);
 4008            } else {
 4009                common_prefix_len = 0;
 4010                ranges.clear();
 4011                ranges.extend(selections.iter().map(|s| {
 4012                    if s.id == newest_selection.id {
 4013                        range_to_replace = Some(
 4014                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 4015                                - selection.start as isize
 4016                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 4017                                    - selection.start as isize,
 4018                        );
 4019                        old_range.clone()
 4020                    } else {
 4021                        s.start..s.end
 4022                    }
 4023                }));
 4024                break;
 4025            }
 4026            if !self.linked_edit_ranges.is_empty() {
 4027                let start_anchor = snapshot.anchor_before(selection.head());
 4028                let end_anchor = snapshot.anchor_after(selection.tail());
 4029                if let Some(ranges) = self
 4030                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 4031                {
 4032                    for (buffer, edits) in ranges {
 4033                        linked_edits.entry(buffer.clone()).or_default().extend(
 4034                            edits
 4035                                .into_iter()
 4036                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 4037                        );
 4038                    }
 4039                }
 4040            }
 4041        }
 4042        let text = &text[common_prefix_len..];
 4043
 4044        cx.emit(EditorEvent::InputHandled {
 4045            utf16_range_to_replace: range_to_replace,
 4046            text: text.into(),
 4047        });
 4048
 4049        self.transact(window, cx, |this, window, cx| {
 4050            if let Some(mut snippet) = snippet {
 4051                snippet.text = text.to_string();
 4052                for tabstop in snippet
 4053                    .tabstops
 4054                    .iter_mut()
 4055                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 4056                {
 4057                    tabstop.start -= common_prefix_len as isize;
 4058                    tabstop.end -= common_prefix_len as isize;
 4059                }
 4060
 4061                this.insert_snippet(&ranges, snippet, window, cx).log_err();
 4062            } else {
 4063                this.buffer.update(cx, |buffer, cx| {
 4064                    buffer.edit(
 4065                        ranges.iter().map(|range| (range.clone(), text)),
 4066                        this.autoindent_mode.clone(),
 4067                        cx,
 4068                    );
 4069                });
 4070            }
 4071            for (buffer, edits) in linked_edits {
 4072                buffer.update(cx, |buffer, cx| {
 4073                    let snapshot = buffer.snapshot();
 4074                    let edits = edits
 4075                        .into_iter()
 4076                        .map(|(range, text)| {
 4077                            use text::ToPoint as TP;
 4078                            let end_point = TP::to_point(&range.end, &snapshot);
 4079                            let start_point = TP::to_point(&range.start, &snapshot);
 4080                            (start_point..end_point, text)
 4081                        })
 4082                        .sorted_by_key(|(range, _)| range.start)
 4083                        .collect::<Vec<_>>();
 4084                    buffer.edit(edits, None, cx);
 4085                })
 4086            }
 4087
 4088            this.refresh_inline_completion(true, false, window, cx);
 4089        });
 4090
 4091        let show_new_completions_on_confirm = completion
 4092            .confirm
 4093            .as_ref()
 4094            .map_or(false, |confirm| confirm(intent, window, cx));
 4095        if show_new_completions_on_confirm {
 4096            self.show_completions(&ShowCompletions { trigger: None }, window, cx);
 4097        }
 4098
 4099        let provider = self.completion_provider.as_ref()?;
 4100        drop(completion);
 4101        let apply_edits = provider.apply_additional_edits_for_completion(
 4102            buffer_handle,
 4103            completions_menu.completions.clone(),
 4104            candidate_id,
 4105            true,
 4106            cx,
 4107        );
 4108
 4109        let editor_settings = EditorSettings::get_global(cx);
 4110        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 4111            // After the code completion is finished, users often want to know what signatures are needed.
 4112            // so we should automatically call signature_help
 4113            self.show_signature_help(&ShowSignatureHelp, window, cx);
 4114        }
 4115
 4116        Some(cx.foreground_executor().spawn(async move {
 4117            apply_edits.await?;
 4118            Ok(())
 4119        }))
 4120    }
 4121
 4122    pub fn toggle_code_actions(
 4123        &mut self,
 4124        action: &ToggleCodeActions,
 4125        window: &mut Window,
 4126        cx: &mut Context<Self>,
 4127    ) {
 4128        let mut context_menu = self.context_menu.borrow_mut();
 4129        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 4130            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 4131                // Toggle if we're selecting the same one
 4132                *context_menu = None;
 4133                cx.notify();
 4134                return;
 4135            } else {
 4136                // Otherwise, clear it and start a new one
 4137                *context_menu = None;
 4138                cx.notify();
 4139            }
 4140        }
 4141        drop(context_menu);
 4142        let snapshot = self.snapshot(window, cx);
 4143        let deployed_from_indicator = action.deployed_from_indicator;
 4144        let mut task = self.code_actions_task.take();
 4145        let action = action.clone();
 4146        cx.spawn_in(window, |editor, mut cx| async move {
 4147            while let Some(prev_task) = task {
 4148                prev_task.await.log_err();
 4149                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4150            }
 4151
 4152            let spawned_test_task = editor.update_in(&mut cx, |editor, window, cx| {
 4153                if editor.focus_handle.is_focused(window) {
 4154                    let multibuffer_point = action
 4155                        .deployed_from_indicator
 4156                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4157                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4158                    let (buffer, buffer_row) = snapshot
 4159                        .buffer_snapshot
 4160                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4161                        .and_then(|(buffer_snapshot, range)| {
 4162                            editor
 4163                                .buffer
 4164                                .read(cx)
 4165                                .buffer(buffer_snapshot.remote_id())
 4166                                .map(|buffer| (buffer, range.start.row))
 4167                        })?;
 4168                    let (_, code_actions) = editor
 4169                        .available_code_actions
 4170                        .clone()
 4171                        .and_then(|(location, code_actions)| {
 4172                            let snapshot = location.buffer.read(cx).snapshot();
 4173                            let point_range = location.range.to_point(&snapshot);
 4174                            let point_range = point_range.start.row..=point_range.end.row;
 4175                            if point_range.contains(&buffer_row) {
 4176                                Some((location, code_actions))
 4177                            } else {
 4178                                None
 4179                            }
 4180                        })
 4181                        .unzip();
 4182                    let buffer_id = buffer.read(cx).remote_id();
 4183                    let tasks = editor
 4184                        .tasks
 4185                        .get(&(buffer_id, buffer_row))
 4186                        .map(|t| Arc::new(t.to_owned()));
 4187                    if tasks.is_none() && code_actions.is_none() {
 4188                        return None;
 4189                    }
 4190
 4191                    editor.completion_tasks.clear();
 4192                    editor.discard_inline_completion(false, cx);
 4193                    let task_context =
 4194                        tasks
 4195                            .as_ref()
 4196                            .zip(editor.project.clone())
 4197                            .map(|(tasks, project)| {
 4198                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4199                            });
 4200
 4201                    Some(cx.spawn_in(window, |editor, mut cx| async move {
 4202                        let task_context = match task_context {
 4203                            Some(task_context) => task_context.await,
 4204                            None => None,
 4205                        };
 4206                        let resolved_tasks =
 4207                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4208                                Rc::new(ResolvedTasks {
 4209                                    templates: tasks.resolve(&task_context).collect(),
 4210                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4211                                        multibuffer_point.row,
 4212                                        tasks.column,
 4213                                    )),
 4214                                })
 4215                            });
 4216                        let spawn_straight_away = resolved_tasks
 4217                            .as_ref()
 4218                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4219                            && code_actions
 4220                                .as_ref()
 4221                                .map_or(true, |actions| actions.is_empty());
 4222                        if let Ok(task) = editor.update_in(&mut cx, |editor, window, cx| {
 4223                            *editor.context_menu.borrow_mut() =
 4224                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4225                                    buffer,
 4226                                    actions: CodeActionContents {
 4227                                        tasks: resolved_tasks,
 4228                                        actions: code_actions,
 4229                                    },
 4230                                    selected_item: Default::default(),
 4231                                    scroll_handle: UniformListScrollHandle::default(),
 4232                                    deployed_from_indicator,
 4233                                }));
 4234                            if spawn_straight_away {
 4235                                if let Some(task) = editor.confirm_code_action(
 4236                                    &ConfirmCodeAction { item_ix: Some(0) },
 4237                                    window,
 4238                                    cx,
 4239                                ) {
 4240                                    cx.notify();
 4241                                    return task;
 4242                                }
 4243                            }
 4244                            cx.notify();
 4245                            Task::ready(Ok(()))
 4246                        }) {
 4247                            task.await
 4248                        } else {
 4249                            Ok(())
 4250                        }
 4251                    }))
 4252                } else {
 4253                    Some(Task::ready(Ok(())))
 4254                }
 4255            })?;
 4256            if let Some(task) = spawned_test_task {
 4257                task.await?;
 4258            }
 4259
 4260            Ok::<_, anyhow::Error>(())
 4261        })
 4262        .detach_and_log_err(cx);
 4263    }
 4264
 4265    pub fn confirm_code_action(
 4266        &mut self,
 4267        action: &ConfirmCodeAction,
 4268        window: &mut Window,
 4269        cx: &mut Context<Self>,
 4270    ) -> Option<Task<Result<()>>> {
 4271        let actions_menu =
 4272            if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(window, cx)? {
 4273                menu
 4274            } else {
 4275                return None;
 4276            };
 4277        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4278        let action = actions_menu.actions.get(action_ix)?;
 4279        let title = action.label();
 4280        let buffer = actions_menu.buffer;
 4281        let workspace = self.workspace()?;
 4282
 4283        match action {
 4284            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4285                workspace.update(cx, |workspace, cx| {
 4286                    workspace::tasks::schedule_resolved_task(
 4287                        workspace,
 4288                        task_source_kind,
 4289                        resolved_task,
 4290                        false,
 4291                        cx,
 4292                    );
 4293
 4294                    Some(Task::ready(Ok(())))
 4295                })
 4296            }
 4297            CodeActionsItem::CodeAction {
 4298                excerpt_id,
 4299                action,
 4300                provider,
 4301            } => {
 4302                let apply_code_action =
 4303                    provider.apply_code_action(buffer, action, excerpt_id, true, window, cx);
 4304                let workspace = workspace.downgrade();
 4305                Some(cx.spawn_in(window, |editor, cx| async move {
 4306                    let project_transaction = apply_code_action.await?;
 4307                    Self::open_project_transaction(
 4308                        &editor,
 4309                        workspace,
 4310                        project_transaction,
 4311                        title,
 4312                        cx,
 4313                    )
 4314                    .await
 4315                }))
 4316            }
 4317        }
 4318    }
 4319
 4320    pub async fn open_project_transaction(
 4321        this: &WeakEntity<Editor>,
 4322        workspace: WeakEntity<Workspace>,
 4323        transaction: ProjectTransaction,
 4324        title: String,
 4325        mut cx: AsyncWindowContext,
 4326    ) -> Result<()> {
 4327        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4328        cx.update(|_, cx| {
 4329            entries.sort_unstable_by_key(|(buffer, _)| {
 4330                buffer.read(cx).file().map(|f| f.path().clone())
 4331            });
 4332        })?;
 4333
 4334        // If the project transaction's edits are all contained within this editor, then
 4335        // avoid opening a new editor to display them.
 4336
 4337        if let Some((buffer, transaction)) = entries.first() {
 4338            if entries.len() == 1 {
 4339                let excerpt = this.update(&mut cx, |editor, cx| {
 4340                    editor
 4341                        .buffer()
 4342                        .read(cx)
 4343                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4344                })?;
 4345                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4346                    if excerpted_buffer == *buffer {
 4347                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4348                            let excerpt_range = excerpt_range.to_offset(buffer);
 4349                            buffer
 4350                                .edited_ranges_for_transaction::<usize>(transaction)
 4351                                .all(|range| {
 4352                                    excerpt_range.start <= range.start
 4353                                        && excerpt_range.end >= range.end
 4354                                })
 4355                        })?;
 4356
 4357                        if all_edits_within_excerpt {
 4358                            return Ok(());
 4359                        }
 4360                    }
 4361                }
 4362            }
 4363        } else {
 4364            return Ok(());
 4365        }
 4366
 4367        let mut ranges_to_highlight = Vec::new();
 4368        let excerpt_buffer = cx.new(|cx| {
 4369            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4370            for (buffer_handle, transaction) in &entries {
 4371                let buffer = buffer_handle.read(cx);
 4372                ranges_to_highlight.extend(
 4373                    multibuffer.push_excerpts_with_context_lines(
 4374                        buffer_handle.clone(),
 4375                        buffer
 4376                            .edited_ranges_for_transaction::<usize>(transaction)
 4377                            .collect(),
 4378                        DEFAULT_MULTIBUFFER_CONTEXT,
 4379                        cx,
 4380                    ),
 4381                );
 4382            }
 4383            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4384            multibuffer
 4385        })?;
 4386
 4387        workspace.update_in(&mut cx, |workspace, window, cx| {
 4388            let project = workspace.project().clone();
 4389            let editor = cx
 4390                .new(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, window, cx));
 4391            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, window, cx);
 4392            editor.update(cx, |editor, cx| {
 4393                editor.highlight_background::<Self>(
 4394                    &ranges_to_highlight,
 4395                    |theme| theme.editor_highlighted_line_background,
 4396                    cx,
 4397                );
 4398            });
 4399        })?;
 4400
 4401        Ok(())
 4402    }
 4403
 4404    pub fn clear_code_action_providers(&mut self) {
 4405        self.code_action_providers.clear();
 4406        self.available_code_actions.take();
 4407    }
 4408
 4409    pub fn add_code_action_provider(
 4410        &mut self,
 4411        provider: Rc<dyn CodeActionProvider>,
 4412        window: &mut Window,
 4413        cx: &mut Context<Self>,
 4414    ) {
 4415        if self
 4416            .code_action_providers
 4417            .iter()
 4418            .any(|existing_provider| existing_provider.id() == provider.id())
 4419        {
 4420            return;
 4421        }
 4422
 4423        self.code_action_providers.push(provider);
 4424        self.refresh_code_actions(window, cx);
 4425    }
 4426
 4427    pub fn remove_code_action_provider(
 4428        &mut self,
 4429        id: Arc<str>,
 4430        window: &mut Window,
 4431        cx: &mut Context<Self>,
 4432    ) {
 4433        self.code_action_providers
 4434            .retain(|provider| provider.id() != id);
 4435        self.refresh_code_actions(window, cx);
 4436    }
 4437
 4438    fn refresh_code_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Option<()> {
 4439        let buffer = self.buffer.read(cx);
 4440        let newest_selection = self.selections.newest_anchor().clone();
 4441        if newest_selection.head().diff_base_anchor.is_some() {
 4442            return None;
 4443        }
 4444        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4445        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4446        if start_buffer != end_buffer {
 4447            return None;
 4448        }
 4449
 4450        self.code_actions_task = Some(cx.spawn_in(window, |this, mut cx| async move {
 4451            cx.background_executor()
 4452                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4453                .await;
 4454
 4455            let (providers, tasks) = this.update_in(&mut cx, |this, window, cx| {
 4456                let providers = this.code_action_providers.clone();
 4457                let tasks = this
 4458                    .code_action_providers
 4459                    .iter()
 4460                    .map(|provider| provider.code_actions(&start_buffer, start..end, window, cx))
 4461                    .collect::<Vec<_>>();
 4462                (providers, tasks)
 4463            })?;
 4464
 4465            let mut actions = Vec::new();
 4466            for (provider, provider_actions) in
 4467                providers.into_iter().zip(future::join_all(tasks).await)
 4468            {
 4469                if let Some(provider_actions) = provider_actions.log_err() {
 4470                    actions.extend(provider_actions.into_iter().map(|action| {
 4471                        AvailableCodeAction {
 4472                            excerpt_id: newest_selection.start.excerpt_id,
 4473                            action,
 4474                            provider: provider.clone(),
 4475                        }
 4476                    }));
 4477                }
 4478            }
 4479
 4480            this.update(&mut cx, |this, cx| {
 4481                this.available_code_actions = if actions.is_empty() {
 4482                    None
 4483                } else {
 4484                    Some((
 4485                        Location {
 4486                            buffer: start_buffer,
 4487                            range: start..end,
 4488                        },
 4489                        actions.into(),
 4490                    ))
 4491                };
 4492                cx.notify();
 4493            })
 4494        }));
 4495        None
 4496    }
 4497
 4498    fn start_inline_blame_timer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4499        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4500            self.show_git_blame_inline = false;
 4501
 4502            self.show_git_blame_inline_delay_task =
 4503                Some(cx.spawn_in(window, |this, mut cx| async move {
 4504                    cx.background_executor().timer(delay).await;
 4505
 4506                    this.update(&mut cx, |this, cx| {
 4507                        this.show_git_blame_inline = true;
 4508                        cx.notify();
 4509                    })
 4510                    .log_err();
 4511                }));
 4512        }
 4513    }
 4514
 4515    fn refresh_document_highlights(&mut self, cx: &mut Context<Self>) -> Option<()> {
 4516        if self.pending_rename.is_some() {
 4517            return None;
 4518        }
 4519
 4520        let provider = self.semantics_provider.clone()?;
 4521        let buffer = self.buffer.read(cx);
 4522        let newest_selection = self.selections.newest_anchor().clone();
 4523        let cursor_position = newest_selection.head();
 4524        let (cursor_buffer, cursor_buffer_position) =
 4525            buffer.text_anchor_for_position(cursor_position, cx)?;
 4526        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4527        if cursor_buffer != tail_buffer {
 4528            return None;
 4529        }
 4530        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4531        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4532            cx.background_executor()
 4533                .timer(Duration::from_millis(debounce))
 4534                .await;
 4535
 4536            let highlights = if let Some(highlights) = cx
 4537                .update(|cx| {
 4538                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4539                })
 4540                .ok()
 4541                .flatten()
 4542            {
 4543                highlights.await.log_err()
 4544            } else {
 4545                None
 4546            };
 4547
 4548            if let Some(highlights) = highlights {
 4549                this.update(&mut cx, |this, cx| {
 4550                    if this.pending_rename.is_some() {
 4551                        return;
 4552                    }
 4553
 4554                    let buffer_id = cursor_position.buffer_id;
 4555                    let buffer = this.buffer.read(cx);
 4556                    if !buffer
 4557                        .text_anchor_for_position(cursor_position, cx)
 4558                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4559                    {
 4560                        return;
 4561                    }
 4562
 4563                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4564                    let mut write_ranges = Vec::new();
 4565                    let mut read_ranges = Vec::new();
 4566                    for highlight in highlights {
 4567                        for (excerpt_id, excerpt_range) in
 4568                            buffer.excerpts_for_buffer(cursor_buffer.read(cx).remote_id(), cx)
 4569                        {
 4570                            let start = highlight
 4571                                .range
 4572                                .start
 4573                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4574                            let end = highlight
 4575                                .range
 4576                                .end
 4577                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4578                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4579                                continue;
 4580                            }
 4581
 4582                            let range = Anchor {
 4583                                buffer_id,
 4584                                excerpt_id,
 4585                                text_anchor: start,
 4586                                diff_base_anchor: None,
 4587                            }..Anchor {
 4588                                buffer_id,
 4589                                excerpt_id,
 4590                                text_anchor: end,
 4591                                diff_base_anchor: None,
 4592                            };
 4593                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4594                                write_ranges.push(range);
 4595                            } else {
 4596                                read_ranges.push(range);
 4597                            }
 4598                        }
 4599                    }
 4600
 4601                    this.highlight_background::<DocumentHighlightRead>(
 4602                        &read_ranges,
 4603                        |theme| theme.editor_document_highlight_read_background,
 4604                        cx,
 4605                    );
 4606                    this.highlight_background::<DocumentHighlightWrite>(
 4607                        &write_ranges,
 4608                        |theme| theme.editor_document_highlight_write_background,
 4609                        cx,
 4610                    );
 4611                    cx.notify();
 4612                })
 4613                .log_err();
 4614            }
 4615        }));
 4616        None
 4617    }
 4618
 4619    pub fn refresh_inline_completion(
 4620        &mut self,
 4621        debounce: bool,
 4622        user_requested: bool,
 4623        window: &mut Window,
 4624        cx: &mut Context<Self>,
 4625    ) -> Option<()> {
 4626        let provider = self.inline_completion_provider()?;
 4627        let cursor = self.selections.newest_anchor().head();
 4628        let (buffer, cursor_buffer_position) =
 4629            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4630
 4631        if !self.inline_completions_enabled_in_buffer(&buffer, cursor_buffer_position, cx) {
 4632            self.discard_inline_completion(false, cx);
 4633            return None;
 4634        }
 4635
 4636        if !user_requested
 4637            && (!self.show_inline_completions
 4638                || !self.should_show_inline_completions_in_buffer(
 4639                    &buffer,
 4640                    cursor_buffer_position,
 4641                    cx,
 4642                )
 4643                || !self.is_focused(window)
 4644                || buffer.read(cx).is_empty())
 4645        {
 4646            self.discard_inline_completion(false, cx);
 4647            return None;
 4648        }
 4649
 4650        self.update_visible_inline_completion(window, cx);
 4651        provider.refresh(
 4652            self.project.clone(),
 4653            buffer,
 4654            cursor_buffer_position,
 4655            debounce,
 4656            cx,
 4657        );
 4658        Some(())
 4659    }
 4660
 4661    pub fn should_show_inline_completions(&self, cx: &App) -> bool {
 4662        let cursor = self.selections.newest_anchor().head();
 4663        if let Some((buffer, cursor_position)) =
 4664            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4665        {
 4666            self.should_show_inline_completions_in_buffer(&buffer, cursor_position, cx)
 4667        } else {
 4668            false
 4669        }
 4670    }
 4671
 4672    fn inline_completion_requires_modifier(&self, cx: &App) -> bool {
 4673        let cursor = self.selections.newest_anchor().head();
 4674
 4675        self.buffer
 4676            .read(cx)
 4677            .text_anchor_for_position(cursor, cx)
 4678            .map(|(buffer, _)| {
 4679                all_language_settings(buffer.read(cx).file(), cx).inline_completions_preview_mode()
 4680                    == InlineCompletionPreviewMode::WhenHoldingModifier
 4681            })
 4682            .unwrap_or(false)
 4683    }
 4684
 4685    fn should_show_inline_completions_in_buffer(
 4686        &self,
 4687        buffer: &Entity<Buffer>,
 4688        buffer_position: language::Anchor,
 4689        cx: &App,
 4690    ) -> bool {
 4691        if !self.snippet_stack.is_empty() {
 4692            return false;
 4693        }
 4694
 4695        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 4696            return false;
 4697        }
 4698
 4699        if let Some(show_inline_completions) = self.show_inline_completions_override {
 4700            show_inline_completions
 4701        } else {
 4702            let buffer = buffer.read(cx);
 4703            self.mode == EditorMode::Full
 4704                && language_settings(
 4705                    buffer.language_at(buffer_position).map(|l| l.name()),
 4706                    buffer.file(),
 4707                    cx,
 4708                )
 4709                .show_inline_completions
 4710        }
 4711    }
 4712
 4713    pub fn inline_completions_enabled(&self, cx: &App) -> bool {
 4714        let cursor = self.selections.newest_anchor().head();
 4715        if let Some((buffer, cursor_position)) =
 4716            self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 4717        {
 4718            self.inline_completions_enabled_in_buffer(&buffer, cursor_position, cx)
 4719        } else {
 4720            false
 4721        }
 4722    }
 4723
 4724    fn inline_completions_enabled_in_buffer(
 4725        &self,
 4726        buffer: &Entity<Buffer>,
 4727        buffer_position: language::Anchor,
 4728        cx: &App,
 4729    ) -> bool {
 4730        maybe!({
 4731            let provider = self.inline_completion_provider()?;
 4732            if !provider.is_enabled(&buffer, buffer_position, cx) {
 4733                return Some(false);
 4734            }
 4735            let buffer = buffer.read(cx);
 4736            let Some(file) = buffer.file() else {
 4737                return Some(true);
 4738            };
 4739            let settings = all_language_settings(Some(file), cx);
 4740            Some(settings.inline_completions_enabled_for_path(file.path()))
 4741        })
 4742        .unwrap_or(false)
 4743    }
 4744
 4745    fn cycle_inline_completion(
 4746        &mut self,
 4747        direction: Direction,
 4748        window: &mut Window,
 4749        cx: &mut Context<Self>,
 4750    ) -> Option<()> {
 4751        let provider = self.inline_completion_provider()?;
 4752        let cursor = self.selections.newest_anchor().head();
 4753        let (buffer, cursor_buffer_position) =
 4754            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4755        if !self.show_inline_completions
 4756            || !self.should_show_inline_completions_in_buffer(&buffer, cursor_buffer_position, cx)
 4757        {
 4758            return None;
 4759        }
 4760
 4761        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4762        self.update_visible_inline_completion(window, cx);
 4763
 4764        Some(())
 4765    }
 4766
 4767    pub fn show_inline_completion(
 4768        &mut self,
 4769        _: &ShowInlineCompletion,
 4770        window: &mut Window,
 4771        cx: &mut Context<Self>,
 4772    ) {
 4773        if !self.has_active_inline_completion() {
 4774            self.refresh_inline_completion(false, true, window, cx);
 4775            return;
 4776        }
 4777
 4778        self.update_visible_inline_completion(window, cx);
 4779    }
 4780
 4781    pub fn display_cursor_names(
 4782        &mut self,
 4783        _: &DisplayCursorNames,
 4784        window: &mut Window,
 4785        cx: &mut Context<Self>,
 4786    ) {
 4787        self.show_cursor_names(window, cx);
 4788    }
 4789
 4790    fn show_cursor_names(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 4791        self.show_cursor_names = true;
 4792        cx.notify();
 4793        cx.spawn_in(window, |this, mut cx| async move {
 4794            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4795            this.update(&mut cx, |this, cx| {
 4796                this.show_cursor_names = false;
 4797                cx.notify()
 4798            })
 4799            .ok()
 4800        })
 4801        .detach();
 4802    }
 4803
 4804    pub fn next_inline_completion(
 4805        &mut self,
 4806        _: &NextInlineCompletion,
 4807        window: &mut Window,
 4808        cx: &mut Context<Self>,
 4809    ) {
 4810        if self.has_active_inline_completion() {
 4811            self.cycle_inline_completion(Direction::Next, window, cx);
 4812        } else {
 4813            let is_copilot_disabled = self
 4814                .refresh_inline_completion(false, true, window, cx)
 4815                .is_none();
 4816            if is_copilot_disabled {
 4817                cx.propagate();
 4818            }
 4819        }
 4820    }
 4821
 4822    pub fn previous_inline_completion(
 4823        &mut self,
 4824        _: &PreviousInlineCompletion,
 4825        window: &mut Window,
 4826        cx: &mut Context<Self>,
 4827    ) {
 4828        if self.has_active_inline_completion() {
 4829            self.cycle_inline_completion(Direction::Prev, window, cx);
 4830        } else {
 4831            let is_copilot_disabled = self
 4832                .refresh_inline_completion(false, true, window, cx)
 4833                .is_none();
 4834            if is_copilot_disabled {
 4835                cx.propagate();
 4836            }
 4837        }
 4838    }
 4839
 4840    pub fn accept_inline_completion(
 4841        &mut self,
 4842        _: &AcceptInlineCompletion,
 4843        window: &mut Window,
 4844        cx: &mut Context<Self>,
 4845    ) {
 4846        let buffer = self.buffer.read(cx);
 4847        let snapshot = buffer.snapshot(cx);
 4848        let selection = self.selections.newest_adjusted(cx);
 4849        let cursor = selection.head();
 4850        let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 4851        let suggested_indents = snapshot.suggested_indents([cursor.row], cx);
 4852        if let Some(suggested_indent) = suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 4853        {
 4854            if cursor.column < suggested_indent.len
 4855                && cursor.column <= current_indent.len
 4856                && current_indent.len <= suggested_indent.len
 4857            {
 4858                self.tab(&Default::default(), window, cx);
 4859                return;
 4860            }
 4861        }
 4862
 4863        if self.show_inline_completions_in_menu(cx) {
 4864            self.hide_context_menu(window, cx);
 4865        }
 4866
 4867        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4868            return;
 4869        };
 4870
 4871        self.report_inline_completion_event(true, cx);
 4872
 4873        match &active_inline_completion.completion {
 4874            InlineCompletion::Move { target, .. } => {
 4875                let target = *target;
 4876                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4877                    selections.select_anchor_ranges([target..target]);
 4878                });
 4879            }
 4880            InlineCompletion::Edit { edits, .. } => {
 4881                if let Some(provider) = self.inline_completion_provider() {
 4882                    provider.accept(cx);
 4883                }
 4884
 4885                let snapshot = self.buffer.read(cx).snapshot(cx);
 4886                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4887
 4888                self.buffer.update(cx, |buffer, cx| {
 4889                    buffer.edit(edits.iter().cloned(), None, cx)
 4890                });
 4891
 4892                self.change_selections(None, window, cx, |s| {
 4893                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4894                });
 4895
 4896                self.update_visible_inline_completion(window, cx);
 4897                if self.active_inline_completion.is_none() {
 4898                    self.refresh_inline_completion(true, true, window, cx);
 4899                }
 4900
 4901                cx.notify();
 4902            }
 4903        }
 4904    }
 4905
 4906    pub fn accept_partial_inline_completion(
 4907        &mut self,
 4908        _: &AcceptPartialInlineCompletion,
 4909        window: &mut Window,
 4910        cx: &mut Context<Self>,
 4911    ) {
 4912        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4913            return;
 4914        };
 4915        if self.selections.count() != 1 {
 4916            return;
 4917        }
 4918
 4919        self.report_inline_completion_event(true, cx);
 4920
 4921        match &active_inline_completion.completion {
 4922            InlineCompletion::Move { target, .. } => {
 4923                let target = *target;
 4924                self.change_selections(Some(Autoscroll::newest()), window, cx, |selections| {
 4925                    selections.select_anchor_ranges([target..target]);
 4926                });
 4927            }
 4928            InlineCompletion::Edit { edits, .. } => {
 4929                // Find an insertion that starts at the cursor position.
 4930                let snapshot = self.buffer.read(cx).snapshot(cx);
 4931                let cursor_offset = self.selections.newest::<usize>(cx).head();
 4932                let insertion = edits.iter().find_map(|(range, text)| {
 4933                    let range = range.to_offset(&snapshot);
 4934                    if range.is_empty() && range.start == cursor_offset {
 4935                        Some(text)
 4936                    } else {
 4937                        None
 4938                    }
 4939                });
 4940
 4941                if let Some(text) = insertion {
 4942                    let mut partial_completion = text
 4943                        .chars()
 4944                        .by_ref()
 4945                        .take_while(|c| c.is_alphabetic())
 4946                        .collect::<String>();
 4947                    if partial_completion.is_empty() {
 4948                        partial_completion = text
 4949                            .chars()
 4950                            .by_ref()
 4951                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4952                            .collect::<String>();
 4953                    }
 4954
 4955                    cx.emit(EditorEvent::InputHandled {
 4956                        utf16_range_to_replace: None,
 4957                        text: partial_completion.clone().into(),
 4958                    });
 4959
 4960                    self.insert_with_autoindent_mode(&partial_completion, None, window, cx);
 4961
 4962                    self.refresh_inline_completion(true, true, window, cx);
 4963                    cx.notify();
 4964                } else {
 4965                    self.accept_inline_completion(&Default::default(), window, cx);
 4966                }
 4967            }
 4968        }
 4969    }
 4970
 4971    fn discard_inline_completion(
 4972        &mut self,
 4973        should_report_inline_completion_event: bool,
 4974        cx: &mut Context<Self>,
 4975    ) -> bool {
 4976        if should_report_inline_completion_event {
 4977            self.report_inline_completion_event(false, cx);
 4978        }
 4979
 4980        if let Some(provider) = self.inline_completion_provider() {
 4981            provider.discard(cx);
 4982        }
 4983
 4984        self.take_active_inline_completion(cx)
 4985    }
 4986
 4987    fn report_inline_completion_event(&self, accepted: bool, cx: &App) {
 4988        let Some(provider) = self.inline_completion_provider() else {
 4989            return;
 4990        };
 4991
 4992        let Some((_, buffer, _)) = self
 4993            .buffer
 4994            .read(cx)
 4995            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4996        else {
 4997            return;
 4998        };
 4999
 5000        let extension = buffer
 5001            .read(cx)
 5002            .file()
 5003            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 5004
 5005        let event_type = match accepted {
 5006            true => "Edit Prediction Accepted",
 5007            false => "Edit Prediction Discarded",
 5008        };
 5009        telemetry::event!(
 5010            event_type,
 5011            provider = provider.name(),
 5012            suggestion_accepted = accepted,
 5013            file_extension = extension,
 5014        );
 5015    }
 5016
 5017    pub fn has_active_inline_completion(&self) -> bool {
 5018        self.active_inline_completion.is_some()
 5019    }
 5020
 5021    fn take_active_inline_completion(&mut self, cx: &mut Context<Self>) -> bool {
 5022        let Some(active_inline_completion) = self.active_inline_completion.take() else {
 5023            return false;
 5024        };
 5025
 5026        self.splice_inlays(&active_inline_completion.inlay_ids, Default::default(), cx);
 5027        self.clear_highlights::<InlineCompletionHighlight>(cx);
 5028        self.stale_inline_completion_in_menu = Some(active_inline_completion);
 5029        true
 5030    }
 5031
 5032    /// Returns true when we're displaying the inline completion popover below the cursor
 5033    /// like we are not previewing and the LSP autocomplete menu is visible
 5034    /// or we are in `when_holding_modifier` mode.
 5035    pub fn inline_completion_visible_in_cursor_popover(
 5036        &self,
 5037        has_completion: bool,
 5038        cx: &App,
 5039    ) -> bool {
 5040        if self.previewing_inline_completion
 5041            || !self.show_inline_completions_in_menu(cx)
 5042            || !self.should_show_inline_completions(cx)
 5043        {
 5044            return false;
 5045        }
 5046
 5047        if self.has_visible_completions_menu() {
 5048            return true;
 5049        }
 5050
 5051        has_completion && self.inline_completion_requires_modifier(cx)
 5052    }
 5053
 5054    fn update_inline_completion_preview(
 5055        &mut self,
 5056        modifiers: &Modifiers,
 5057        window: &mut Window,
 5058        cx: &mut Context<Self>,
 5059    ) {
 5060        if !self.show_inline_completions_in_menu(cx) {
 5061            return;
 5062        }
 5063
 5064        self.previewing_inline_completion = modifiers.alt;
 5065        self.update_visible_inline_completion(window, cx);
 5066        cx.notify();
 5067    }
 5068
 5069    fn update_visible_inline_completion(
 5070        &mut self,
 5071        _window: &mut Window,
 5072        cx: &mut Context<Self>,
 5073    ) -> Option<()> {
 5074        let selection = self.selections.newest_anchor();
 5075        let cursor = selection.head();
 5076        let multibuffer = self.buffer.read(cx).snapshot(cx);
 5077        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 5078        let excerpt_id = cursor.excerpt_id;
 5079
 5080        let show_in_menu = self.show_inline_completions_in_menu(cx);
 5081        let completions_menu_has_precedence = !show_in_menu
 5082            && (self.context_menu.borrow().is_some()
 5083                || (!self.completion_tasks.is_empty() && !self.has_active_inline_completion()));
 5084        if completions_menu_has_precedence
 5085            || !offset_selection.is_empty()
 5086            || !self.show_inline_completions
 5087            || self
 5088                .active_inline_completion
 5089                .as_ref()
 5090                .map_or(false, |completion| {
 5091                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 5092                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 5093                    !invalidation_range.contains(&offset_selection.head())
 5094                })
 5095        {
 5096            self.discard_inline_completion(false, cx);
 5097            return None;
 5098        }
 5099
 5100        self.take_active_inline_completion(cx);
 5101        let provider = self.inline_completion_provider()?;
 5102
 5103        let (buffer, cursor_buffer_position) =
 5104            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 5105
 5106        let inline_completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 5107        let edits = inline_completion
 5108            .edits
 5109            .into_iter()
 5110            .flat_map(|(range, new_text)| {
 5111                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 5112                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 5113                Some((start..end, new_text))
 5114            })
 5115            .collect::<Vec<_>>();
 5116        if edits.is_empty() {
 5117            return None;
 5118        }
 5119
 5120        let first_edit_start = edits.first().unwrap().0.start;
 5121        let first_edit_start_point = first_edit_start.to_point(&multibuffer);
 5122        let edit_start_row = first_edit_start_point.row.saturating_sub(2);
 5123
 5124        let last_edit_end = edits.last().unwrap().0.end;
 5125        let last_edit_end_point = last_edit_end.to_point(&multibuffer);
 5126        let edit_end_row = cmp::min(multibuffer.max_point().row, last_edit_end_point.row + 2);
 5127
 5128        let cursor_row = cursor.to_point(&multibuffer).row;
 5129
 5130        let snapshot = multibuffer.buffer_for_excerpt(excerpt_id).cloned()?;
 5131
 5132        let mut inlay_ids = Vec::new();
 5133        let invalidation_row_range;
 5134        let move_invalidation_row_range = if cursor_row < edit_start_row {
 5135            Some(cursor_row..edit_end_row)
 5136        } else if cursor_row > edit_end_row {
 5137            Some(edit_start_row..cursor_row)
 5138        } else {
 5139            None
 5140        };
 5141        let completion = if let Some(move_invalidation_row_range) = move_invalidation_row_range {
 5142            invalidation_row_range = move_invalidation_row_range;
 5143            let target = first_edit_start;
 5144            let target_point = text::ToPoint::to_point(&target.text_anchor, &snapshot);
 5145            // TODO: Base this off of TreeSitter or word boundaries?
 5146            let target_excerpt_begin = snapshot.anchor_before(snapshot.clip_point(
 5147                Point::new(target_point.row, target_point.column.saturating_sub(20)),
 5148                Bias::Left,
 5149            ));
 5150            let target_excerpt_end = snapshot.anchor_after(snapshot.clip_point(
 5151                Point::new(target_point.row, target_point.column + 20),
 5152                Bias::Right,
 5153            ));
 5154            let range_around_target = target_excerpt_begin..target_excerpt_end;
 5155            InlineCompletion::Move {
 5156                target,
 5157                range_around_target,
 5158                snapshot,
 5159            }
 5160        } else {
 5161            if !self.inline_completion_visible_in_cursor_popover(true, cx) {
 5162                if edits
 5163                    .iter()
 5164                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 5165                {
 5166                    let mut inlays = Vec::new();
 5167                    for (range, new_text) in &edits {
 5168                        let inlay = Inlay::inline_completion(
 5169                            post_inc(&mut self.next_inlay_id),
 5170                            range.start,
 5171                            new_text.as_str(),
 5172                        );
 5173                        inlay_ids.push(inlay.id);
 5174                        inlays.push(inlay);
 5175                    }
 5176
 5177                    self.splice_inlays(&[], inlays, cx);
 5178                } else {
 5179                    let background_color = cx.theme().status().deleted_background;
 5180                    self.highlight_text::<InlineCompletionHighlight>(
 5181                        edits.iter().map(|(range, _)| range.clone()).collect(),
 5182                        HighlightStyle {
 5183                            background_color: Some(background_color),
 5184                            ..Default::default()
 5185                        },
 5186                        cx,
 5187                    );
 5188                }
 5189            }
 5190
 5191            invalidation_row_range = edit_start_row..edit_end_row;
 5192
 5193            let display_mode = if all_edits_insertions_or_deletions(&edits, &multibuffer) {
 5194                if provider.show_tab_accept_marker() {
 5195                    EditDisplayMode::TabAccept
 5196                } else {
 5197                    EditDisplayMode::Inline
 5198                }
 5199            } else {
 5200                EditDisplayMode::DiffPopover
 5201            };
 5202
 5203            InlineCompletion::Edit {
 5204                edits,
 5205                edit_preview: inline_completion.edit_preview,
 5206                display_mode,
 5207                snapshot,
 5208            }
 5209        };
 5210
 5211        let invalidation_range = multibuffer
 5212            .anchor_before(Point::new(invalidation_row_range.start, 0))
 5213            ..multibuffer.anchor_after(Point::new(
 5214                invalidation_row_range.end,
 5215                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 5216            ));
 5217
 5218        self.stale_inline_completion_in_menu = None;
 5219        self.active_inline_completion = Some(InlineCompletionState {
 5220            inlay_ids,
 5221            completion,
 5222            invalidation_range,
 5223        });
 5224
 5225        cx.notify();
 5226
 5227        Some(())
 5228    }
 5229
 5230    pub fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 5231        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 5232    }
 5233
 5234    fn show_inline_completions_in_menu(&self, cx: &App) -> bool {
 5235        let by_provider = matches!(
 5236            self.menu_inline_completions_policy,
 5237            MenuInlineCompletionsPolicy::ByProvider
 5238        );
 5239
 5240        by_provider
 5241            && EditorSettings::get_global(cx).show_inline_completions_in_menu
 5242            && self
 5243                .inline_completion_provider()
 5244                .map_or(false, |provider| provider.show_completions_in_menu())
 5245    }
 5246
 5247    fn render_code_actions_indicator(
 5248        &self,
 5249        _style: &EditorStyle,
 5250        row: DisplayRow,
 5251        is_active: bool,
 5252        cx: &mut Context<Self>,
 5253    ) -> Option<IconButton> {
 5254        if self.available_code_actions.is_some() {
 5255            Some(
 5256                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 5257                    .shape(ui::IconButtonShape::Square)
 5258                    .icon_size(IconSize::XSmall)
 5259                    .icon_color(Color::Muted)
 5260                    .toggle_state(is_active)
 5261                    .tooltip({
 5262                        let focus_handle = self.focus_handle.clone();
 5263                        move |window, cx| {
 5264                            Tooltip::for_action_in(
 5265                                "Toggle Code Actions",
 5266                                &ToggleCodeActions {
 5267                                    deployed_from_indicator: None,
 5268                                },
 5269                                &focus_handle,
 5270                                window,
 5271                                cx,
 5272                            )
 5273                        }
 5274                    })
 5275                    .on_click(cx.listener(move |editor, _e, window, cx| {
 5276                        window.focus(&editor.focus_handle(cx));
 5277                        editor.toggle_code_actions(
 5278                            &ToggleCodeActions {
 5279                                deployed_from_indicator: Some(row),
 5280                            },
 5281                            window,
 5282                            cx,
 5283                        );
 5284                    })),
 5285            )
 5286        } else {
 5287            None
 5288        }
 5289    }
 5290
 5291    fn clear_tasks(&mut self) {
 5292        self.tasks.clear()
 5293    }
 5294
 5295    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 5296        if self.tasks.insert(key, value).is_some() {
 5297            // This case should hopefully be rare, but just in case...
 5298            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 5299        }
 5300    }
 5301
 5302    fn build_tasks_context(
 5303        project: &Entity<Project>,
 5304        buffer: &Entity<Buffer>,
 5305        buffer_row: u32,
 5306        tasks: &Arc<RunnableTasks>,
 5307        cx: &mut Context<Self>,
 5308    ) -> Task<Option<task::TaskContext>> {
 5309        let position = Point::new(buffer_row, tasks.column);
 5310        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 5311        let location = Location {
 5312            buffer: buffer.clone(),
 5313            range: range_start..range_start,
 5314        };
 5315        // Fill in the environmental variables from the tree-sitter captures
 5316        let mut captured_task_variables = TaskVariables::default();
 5317        for (capture_name, value) in tasks.extra_variables.clone() {
 5318            captured_task_variables.insert(
 5319                task::VariableName::Custom(capture_name.into()),
 5320                value.clone(),
 5321            );
 5322        }
 5323        project.update(cx, |project, cx| {
 5324            project.task_store().update(cx, |task_store, cx| {
 5325                task_store.task_context_for_location(captured_task_variables, location, cx)
 5326            })
 5327        })
 5328    }
 5329
 5330    pub fn spawn_nearest_task(
 5331        &mut self,
 5332        action: &SpawnNearestTask,
 5333        window: &mut Window,
 5334        cx: &mut Context<Self>,
 5335    ) {
 5336        let Some((workspace, _)) = self.workspace.clone() else {
 5337            return;
 5338        };
 5339        let Some(project) = self.project.clone() else {
 5340            return;
 5341        };
 5342
 5343        // Try to find a closest, enclosing node using tree-sitter that has a
 5344        // task
 5345        let Some((buffer, buffer_row, tasks)) = self
 5346            .find_enclosing_node_task(cx)
 5347            // Or find the task that's closest in row-distance.
 5348            .or_else(|| self.find_closest_task(cx))
 5349        else {
 5350            return;
 5351        };
 5352
 5353        let reveal_strategy = action.reveal;
 5354        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 5355        cx.spawn_in(window, |_, mut cx| async move {
 5356            let context = task_context.await?;
 5357            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 5358
 5359            let resolved = resolved_task.resolved.as_mut()?;
 5360            resolved.reveal = reveal_strategy;
 5361
 5362            workspace
 5363                .update(&mut cx, |workspace, cx| {
 5364                    workspace::tasks::schedule_resolved_task(
 5365                        workspace,
 5366                        task_source_kind,
 5367                        resolved_task,
 5368                        false,
 5369                        cx,
 5370                    );
 5371                })
 5372                .ok()
 5373        })
 5374        .detach();
 5375    }
 5376
 5377    fn find_closest_task(
 5378        &mut self,
 5379        cx: &mut Context<Self>,
 5380    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5381        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5382
 5383        let ((buffer_id, row), tasks) = self
 5384            .tasks
 5385            .iter()
 5386            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5387
 5388        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5389        let tasks = Arc::new(tasks.to_owned());
 5390        Some((buffer, *row, tasks))
 5391    }
 5392
 5393    fn find_enclosing_node_task(
 5394        &mut self,
 5395        cx: &mut Context<Self>,
 5396    ) -> Option<(Entity<Buffer>, u32, Arc<RunnableTasks>)> {
 5397        let snapshot = self.buffer.read(cx).snapshot(cx);
 5398        let offset = self.selections.newest::<usize>(cx).head();
 5399        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5400        let buffer_id = excerpt.buffer().remote_id();
 5401
 5402        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5403        let mut cursor = layer.node().walk();
 5404
 5405        while cursor.goto_first_child_for_byte(offset).is_some() {
 5406            if cursor.node().end_byte() == offset {
 5407                cursor.goto_next_sibling();
 5408            }
 5409        }
 5410
 5411        // Ascend to the smallest ancestor that contains the range and has a task.
 5412        loop {
 5413            let node = cursor.node();
 5414            let node_range = node.byte_range();
 5415            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5416
 5417            // Check if this node contains our offset
 5418            if node_range.start <= offset && node_range.end >= offset {
 5419                // If it contains offset, check for task
 5420                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5421                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5422                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5423                }
 5424            }
 5425
 5426            if !cursor.goto_parent() {
 5427                break;
 5428            }
 5429        }
 5430        None
 5431    }
 5432
 5433    fn render_run_indicator(
 5434        &self,
 5435        _style: &EditorStyle,
 5436        is_active: bool,
 5437        row: DisplayRow,
 5438        cx: &mut Context<Self>,
 5439    ) -> IconButton {
 5440        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5441            .shape(ui::IconButtonShape::Square)
 5442            .icon_size(IconSize::XSmall)
 5443            .icon_color(Color::Muted)
 5444            .toggle_state(is_active)
 5445            .on_click(cx.listener(move |editor, _e, window, cx| {
 5446                window.focus(&editor.focus_handle(cx));
 5447                editor.toggle_code_actions(
 5448                    &ToggleCodeActions {
 5449                        deployed_from_indicator: Some(row),
 5450                    },
 5451                    window,
 5452                    cx,
 5453                );
 5454            }))
 5455    }
 5456
 5457    pub fn context_menu_visible(&self) -> bool {
 5458        !self.previewing_inline_completion
 5459            && self
 5460                .context_menu
 5461                .borrow()
 5462                .as_ref()
 5463                .map_or(false, |menu| menu.visible())
 5464    }
 5465
 5466    fn context_menu_origin(&self) -> Option<ContextMenuOrigin> {
 5467        self.context_menu
 5468            .borrow()
 5469            .as_ref()
 5470            .map(|menu| menu.origin())
 5471    }
 5472
 5473    fn edit_prediction_cursor_popover_height(&self) -> Pixels {
 5474        px(30.)
 5475    }
 5476
 5477    fn current_user_player_color(&self, cx: &mut App) -> PlayerColor {
 5478        if self.read_only(cx) {
 5479            cx.theme().players().read_only()
 5480        } else {
 5481            self.style.as_ref().unwrap().local_player
 5482        }
 5483    }
 5484
 5485    #[allow(clippy::too_many_arguments)]
 5486    fn render_edit_prediction_cursor_popover(
 5487        &self,
 5488        min_width: Pixels,
 5489        max_width: Pixels,
 5490        cursor_point: Point,
 5491        style: &EditorStyle,
 5492        accept_keystroke: &gpui::Keystroke,
 5493        window: &Window,
 5494        cx: &mut Context<Editor>,
 5495    ) -> Option<AnyElement> {
 5496        let provider = self.inline_completion_provider.as_ref()?;
 5497
 5498        if provider.provider.needs_terms_acceptance(cx) {
 5499            return Some(
 5500                h_flex()
 5501                    .h(self.edit_prediction_cursor_popover_height())
 5502                    .min_w(min_width)
 5503                    .flex_1()
 5504                    .px_2()
 5505                    .gap_3()
 5506                    .elevation_2(cx)
 5507                    .hover(|style| style.bg(cx.theme().colors().element_hover))
 5508                    .id("accept-terms")
 5509                    .cursor_pointer()
 5510                    .on_mouse_down(MouseButton::Left, |_, window, _| window.prevent_default())
 5511                    .on_click(cx.listener(|this, _event, window, cx| {
 5512                        cx.stop_propagation();
 5513                        this.report_editor_event("Edit Prediction Provider ToS Clicked", None, cx);
 5514                        window.dispatch_action(
 5515                            zed_actions::OpenZedPredictOnboarding.boxed_clone(),
 5516                            cx,
 5517                        );
 5518                    }))
 5519                    .child(
 5520                        h_flex()
 5521                            .w_full()
 5522                            .gap_2()
 5523                            .child(Icon::new(IconName::ZedPredict))
 5524                            .child(Label::new("Accept Terms of Service"))
 5525                            .child(div().w_full())
 5526                            .child(
 5527                                Icon::new(IconName::ArrowUpRight)
 5528                                    .color(Color::Muted)
 5529                                    .size(IconSize::Small),
 5530                            )
 5531                            .into_any_element(),
 5532                    )
 5533                    .into_any(),
 5534            );
 5535        }
 5536
 5537        let is_refreshing = provider.provider.is_refreshing(cx);
 5538
 5539        fn pending_completion_container() -> Div {
 5540            h_flex()
 5541                .h_full()
 5542                .flex_1()
 5543                .gap_2()
 5544                .child(Icon::new(IconName::ZedPredict))
 5545        }
 5546
 5547        let completion = match &self.active_inline_completion {
 5548            Some(completion) => self.render_edit_prediction_cursor_popover_preview(
 5549                completion,
 5550                cursor_point,
 5551                style,
 5552                window,
 5553                cx,
 5554            )?,
 5555
 5556            None if is_refreshing => match &self.stale_inline_completion_in_menu {
 5557                Some(stale_completion) => self.render_edit_prediction_cursor_popover_preview(
 5558                    stale_completion,
 5559                    cursor_point,
 5560                    style,
 5561                    window,
 5562                    cx,
 5563                )?,
 5564
 5565                None => {
 5566                    pending_completion_container().child(Label::new("...").size(LabelSize::Small))
 5567                }
 5568            },
 5569
 5570            None => pending_completion_container().child(Label::new("No Prediction")),
 5571        };
 5572
 5573        let buffer_font = theme::ThemeSettings::get_global(cx).buffer_font.clone();
 5574        let completion = completion.font(buffer_font.clone());
 5575
 5576        let completion = if is_refreshing {
 5577            completion
 5578                .with_animation(
 5579                    "loading-completion",
 5580                    Animation::new(Duration::from_secs(2))
 5581                        .repeat()
 5582                        .with_easing(pulsating_between(0.4, 0.8)),
 5583                    |label, delta| label.opacity(delta),
 5584                )
 5585                .into_any_element()
 5586        } else {
 5587            completion.into_any_element()
 5588        };
 5589
 5590        let has_completion = self.active_inline_completion.is_some();
 5591
 5592        Some(
 5593            h_flex()
 5594                .h(self.edit_prediction_cursor_popover_height())
 5595                .min_w(min_width)
 5596                .max_w(max_width)
 5597                .flex_1()
 5598                .px_2()
 5599                .elevation_2(cx)
 5600                .child(completion)
 5601                .child(ui::Divider::vertical())
 5602                .child(
 5603                    h_flex()
 5604                        .h_full()
 5605                        .gap_1()
 5606                        .pl_2()
 5607                        .child(h_flex().font(buffer_font.clone()).gap_1().children(
 5608                            ui::render_modifiers(
 5609                                &accept_keystroke.modifiers,
 5610                                PlatformStyle::platform(),
 5611                                Some(if !has_completion {
 5612                                    Color::Muted
 5613                                } else {
 5614                                    Color::Default
 5615                                }),
 5616                                None,
 5617                                true,
 5618                            ),
 5619                        ))
 5620                        .child(Label::new("Preview").into_any_element())
 5621                        .opacity(if has_completion { 1.0 } else { 0.4 }),
 5622                )
 5623                .into_any(),
 5624        )
 5625    }
 5626
 5627    fn render_edit_prediction_cursor_popover_preview(
 5628        &self,
 5629        completion: &InlineCompletionState,
 5630        cursor_point: Point,
 5631        style: &EditorStyle,
 5632        window: &Window,
 5633        cx: &mut Context<Editor>,
 5634    ) -> Option<Div> {
 5635        use text::ToPoint as _;
 5636
 5637        fn render_relative_row_jump(
 5638            prefix: impl Into<String>,
 5639            current_row: u32,
 5640            target_row: u32,
 5641        ) -> Div {
 5642            let (row_diff, arrow) = if target_row < current_row {
 5643                (current_row - target_row, IconName::ArrowUp)
 5644            } else {
 5645                (target_row - current_row, IconName::ArrowDown)
 5646            };
 5647
 5648            h_flex()
 5649                .child(
 5650                    Label::new(format!("{}{}", prefix.into(), row_diff))
 5651                        .color(Color::Muted)
 5652                        .size(LabelSize::Small),
 5653                )
 5654                .child(Icon::new(arrow).color(Color::Muted).size(IconSize::Small))
 5655        }
 5656
 5657        match &completion.completion {
 5658            InlineCompletion::Edit {
 5659                edits,
 5660                edit_preview,
 5661                snapshot,
 5662                display_mode: _,
 5663            } => {
 5664                let first_edit_row = edits.first()?.0.start.text_anchor.to_point(&snapshot).row;
 5665
 5666                let highlighted_edits = crate::inline_completion_edit_text(
 5667                    &snapshot,
 5668                    &edits,
 5669                    edit_preview.as_ref()?,
 5670                    true,
 5671                    cx,
 5672                );
 5673
 5674                let len_total = highlighted_edits.text.len();
 5675                let first_line = &highlighted_edits.text
 5676                    [..highlighted_edits.text.find('\n').unwrap_or(len_total)];
 5677                let first_line_len = first_line.len();
 5678
 5679                let first_highlight_start = highlighted_edits
 5680                    .highlights
 5681                    .first()
 5682                    .map_or(0, |(range, _)| range.start);
 5683                let drop_prefix_len = first_line
 5684                    .char_indices()
 5685                    .find(|(_, c)| !c.is_whitespace())
 5686                    .map_or(first_highlight_start, |(ix, _)| {
 5687                        ix.min(first_highlight_start)
 5688                    });
 5689
 5690                let preview_text = &first_line[drop_prefix_len..];
 5691                let preview_len = preview_text.len();
 5692                let highlights = highlighted_edits
 5693                    .highlights
 5694                    .into_iter()
 5695                    .take_until(|(range, _)| range.start > first_line_len)
 5696                    .map(|(range, style)| {
 5697                        (
 5698                            range.start - drop_prefix_len
 5699                                ..(range.end - drop_prefix_len).min(preview_len),
 5700                            style,
 5701                        )
 5702                    });
 5703
 5704                let styled_text = gpui::StyledText::new(SharedString::new(preview_text))
 5705                    .with_highlights(&style.text, highlights);
 5706
 5707                let preview = h_flex()
 5708                    .gap_1()
 5709                    .min_w_16()
 5710                    .child(styled_text)
 5711                    .when(len_total > first_line_len, |parent| parent.child(""));
 5712
 5713                let left = if first_edit_row != cursor_point.row {
 5714                    render_relative_row_jump("", cursor_point.row, first_edit_row)
 5715                        .into_any_element()
 5716                } else {
 5717                    Icon::new(IconName::ZedPredict).into_any_element()
 5718                };
 5719
 5720                Some(
 5721                    h_flex()
 5722                        .h_full()
 5723                        .flex_1()
 5724                        .gap_2()
 5725                        .pr_1()
 5726                        .overflow_x_hidden()
 5727                        .child(left)
 5728                        .child(preview),
 5729                )
 5730            }
 5731
 5732            InlineCompletion::Move {
 5733                target,
 5734                range_around_target,
 5735                snapshot,
 5736            } => {
 5737                let highlighted_text = snapshot.highlighted_text_for_range(
 5738                    range_around_target.clone(),
 5739                    None,
 5740                    &style.syntax,
 5741                );
 5742                let base = h_flex().gap_3().flex_1().child(render_relative_row_jump(
 5743                    "Jump ",
 5744                    cursor_point.row,
 5745                    target.text_anchor.to_point(&snapshot).row,
 5746                ));
 5747
 5748                if highlighted_text.text.is_empty() {
 5749                    return Some(base);
 5750                }
 5751
 5752                let cursor_color = self.current_user_player_color(cx).cursor;
 5753
 5754                let start_point = range_around_target.start.to_point(&snapshot);
 5755                let end_point = range_around_target.end.to_point(&snapshot);
 5756                let target_point = target.text_anchor.to_point(&snapshot);
 5757
 5758                let styled_text = highlighted_text.to_styled_text(&style.text);
 5759                let text_len = highlighted_text.text.len();
 5760
 5761                let cursor_relative_position = window
 5762                    .text_system()
 5763                    .layout_line(
 5764                        highlighted_text.text,
 5765                        style.text.font_size.to_pixels(window.rem_size()),
 5766                        // We don't need to include highlights
 5767                        // because we are only using this for the cursor position
 5768                        &[TextRun {
 5769                            len: text_len,
 5770                            font: style.text.font(),
 5771                            color: style.text.color,
 5772                            background_color: None,
 5773                            underline: None,
 5774                            strikethrough: None,
 5775                        }],
 5776                    )
 5777                    .log_err()
 5778                    .map(|line| {
 5779                        line.x_for_index(
 5780                            target_point.column.saturating_sub(start_point.column) as usize
 5781                        )
 5782                    });
 5783
 5784                let fade_before = start_point.column > 0;
 5785                let fade_after = end_point.column < snapshot.line_len(end_point.row);
 5786
 5787                let background = cx.theme().colors().elevated_surface_background;
 5788
 5789                let preview = h_flex()
 5790                    .relative()
 5791                    .child(styled_text)
 5792                    .when(fade_before, |parent| {
 5793                        parent.child(div().absolute().top_0().left_0().w_4().h_full().bg(
 5794                            linear_gradient(
 5795                                90.,
 5796                                linear_color_stop(background, 0.),
 5797                                linear_color_stop(background.opacity(0.), 1.),
 5798                            ),
 5799                        ))
 5800                    })
 5801                    .when(fade_after, |parent| {
 5802                        parent.child(div().absolute().top_0().right_0().w_4().h_full().bg(
 5803                            linear_gradient(
 5804                                -90.,
 5805                                linear_color_stop(background, 0.),
 5806                                linear_color_stop(background.opacity(0.), 1.),
 5807                            ),
 5808                        ))
 5809                    })
 5810                    .when_some(cursor_relative_position, |parent, position| {
 5811                        parent.child(
 5812                            div()
 5813                                .w(px(2.))
 5814                                .h_full()
 5815                                .bg(cursor_color)
 5816                                .absolute()
 5817                                .top_0()
 5818                                .left(position),
 5819                        )
 5820                    });
 5821
 5822                Some(base.child(preview))
 5823            }
 5824        }
 5825    }
 5826
 5827    fn render_context_menu(
 5828        &self,
 5829        style: &EditorStyle,
 5830        max_height_in_lines: u32,
 5831        y_flipped: bool,
 5832        window: &mut Window,
 5833        cx: &mut Context<Editor>,
 5834    ) -> Option<AnyElement> {
 5835        let menu = self.context_menu.borrow();
 5836        let menu = menu.as_ref()?;
 5837        if !menu.visible() {
 5838            return None;
 5839        };
 5840        Some(menu.render(style, max_height_in_lines, y_flipped, window, cx))
 5841    }
 5842
 5843    fn render_context_menu_aside(
 5844        &self,
 5845        style: &EditorStyle,
 5846        max_size: Size<Pixels>,
 5847        cx: &mut Context<Editor>,
 5848    ) -> Option<AnyElement> {
 5849        self.context_menu.borrow().as_ref().and_then(|menu| {
 5850            if menu.visible() {
 5851                menu.render_aside(
 5852                    style,
 5853                    max_size,
 5854                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5855                    cx,
 5856                )
 5857            } else {
 5858                None
 5859            }
 5860        })
 5861    }
 5862
 5863    fn hide_context_menu(
 5864        &mut self,
 5865        window: &mut Window,
 5866        cx: &mut Context<Self>,
 5867    ) -> Option<CodeContextMenu> {
 5868        cx.notify();
 5869        self.completion_tasks.clear();
 5870        let context_menu = self.context_menu.borrow_mut().take();
 5871        self.stale_inline_completion_in_menu.take();
 5872        self.update_visible_inline_completion(window, cx);
 5873        context_menu
 5874    }
 5875
 5876    fn show_snippet_choices(
 5877        &mut self,
 5878        choices: &Vec<String>,
 5879        selection: Range<Anchor>,
 5880        cx: &mut Context<Self>,
 5881    ) {
 5882        if selection.start.buffer_id.is_none() {
 5883            return;
 5884        }
 5885        let buffer_id = selection.start.buffer_id.unwrap();
 5886        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5887        let id = post_inc(&mut self.next_completion_id);
 5888
 5889        if let Some(buffer) = buffer {
 5890            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5891                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5892            ));
 5893        }
 5894    }
 5895
 5896    pub fn insert_snippet(
 5897        &mut self,
 5898        insertion_ranges: &[Range<usize>],
 5899        snippet: Snippet,
 5900        window: &mut Window,
 5901        cx: &mut Context<Self>,
 5902    ) -> Result<()> {
 5903        struct Tabstop<T> {
 5904            is_end_tabstop: bool,
 5905            ranges: Vec<Range<T>>,
 5906            choices: Option<Vec<String>>,
 5907        }
 5908
 5909        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5910            let snippet_text: Arc<str> = snippet.text.clone().into();
 5911            buffer.edit(
 5912                insertion_ranges
 5913                    .iter()
 5914                    .cloned()
 5915                    .map(|range| (range, snippet_text.clone())),
 5916                Some(AutoindentMode::EachLine),
 5917                cx,
 5918            );
 5919
 5920            let snapshot = &*buffer.read(cx);
 5921            let snippet = &snippet;
 5922            snippet
 5923                .tabstops
 5924                .iter()
 5925                .map(|tabstop| {
 5926                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5927                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5928                    });
 5929                    let mut tabstop_ranges = tabstop
 5930                        .ranges
 5931                        .iter()
 5932                        .flat_map(|tabstop_range| {
 5933                            let mut delta = 0_isize;
 5934                            insertion_ranges.iter().map(move |insertion_range| {
 5935                                let insertion_start = insertion_range.start as isize + delta;
 5936                                delta +=
 5937                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5938
 5939                                let start = ((insertion_start + tabstop_range.start) as usize)
 5940                                    .min(snapshot.len());
 5941                                let end = ((insertion_start + tabstop_range.end) as usize)
 5942                                    .min(snapshot.len());
 5943                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5944                            })
 5945                        })
 5946                        .collect::<Vec<_>>();
 5947                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5948
 5949                    Tabstop {
 5950                        is_end_tabstop,
 5951                        ranges: tabstop_ranges,
 5952                        choices: tabstop.choices.clone(),
 5953                    }
 5954                })
 5955                .collect::<Vec<_>>()
 5956        });
 5957        if let Some(tabstop) = tabstops.first() {
 5958            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 5959                s.select_ranges(tabstop.ranges.iter().cloned());
 5960            });
 5961
 5962            if let Some(choices) = &tabstop.choices {
 5963                if let Some(selection) = tabstop.ranges.first() {
 5964                    self.show_snippet_choices(choices, selection.clone(), cx)
 5965                }
 5966            }
 5967
 5968            // If we're already at the last tabstop and it's at the end of the snippet,
 5969            // we're done, we don't need to keep the state around.
 5970            if !tabstop.is_end_tabstop {
 5971                let choices = tabstops
 5972                    .iter()
 5973                    .map(|tabstop| tabstop.choices.clone())
 5974                    .collect();
 5975
 5976                let ranges = tabstops
 5977                    .into_iter()
 5978                    .map(|tabstop| tabstop.ranges)
 5979                    .collect::<Vec<_>>();
 5980
 5981                self.snippet_stack.push(SnippetState {
 5982                    active_index: 0,
 5983                    ranges,
 5984                    choices,
 5985                });
 5986            }
 5987
 5988            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5989            if self.autoclose_regions.is_empty() {
 5990                let snapshot = self.buffer.read(cx).snapshot(cx);
 5991                for selection in &mut self.selections.all::<Point>(cx) {
 5992                    let selection_head = selection.head();
 5993                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5994                        continue;
 5995                    };
 5996
 5997                    let mut bracket_pair = None;
 5998                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5999                    let prev_chars = snapshot
 6000                        .reversed_chars_at(selection_head)
 6001                        .collect::<String>();
 6002                    for (pair, enabled) in scope.brackets() {
 6003                        if enabled
 6004                            && pair.close
 6005                            && prev_chars.starts_with(pair.start.as_str())
 6006                            && next_chars.starts_with(pair.end.as_str())
 6007                        {
 6008                            bracket_pair = Some(pair.clone());
 6009                            break;
 6010                        }
 6011                    }
 6012                    if let Some(pair) = bracket_pair {
 6013                        let start = snapshot.anchor_after(selection_head);
 6014                        let end = snapshot.anchor_after(selection_head);
 6015                        self.autoclose_regions.push(AutocloseRegion {
 6016                            selection_id: selection.id,
 6017                            range: start..end,
 6018                            pair,
 6019                        });
 6020                    }
 6021                }
 6022            }
 6023        }
 6024        Ok(())
 6025    }
 6026
 6027    pub fn move_to_next_snippet_tabstop(
 6028        &mut self,
 6029        window: &mut Window,
 6030        cx: &mut Context<Self>,
 6031    ) -> bool {
 6032        self.move_to_snippet_tabstop(Bias::Right, window, cx)
 6033    }
 6034
 6035    pub fn move_to_prev_snippet_tabstop(
 6036        &mut self,
 6037        window: &mut Window,
 6038        cx: &mut Context<Self>,
 6039    ) -> bool {
 6040        self.move_to_snippet_tabstop(Bias::Left, window, cx)
 6041    }
 6042
 6043    pub fn move_to_snippet_tabstop(
 6044        &mut self,
 6045        bias: Bias,
 6046        window: &mut Window,
 6047        cx: &mut Context<Self>,
 6048    ) -> bool {
 6049        if let Some(mut snippet) = self.snippet_stack.pop() {
 6050            match bias {
 6051                Bias::Left => {
 6052                    if snippet.active_index > 0 {
 6053                        snippet.active_index -= 1;
 6054                    } else {
 6055                        self.snippet_stack.push(snippet);
 6056                        return false;
 6057                    }
 6058                }
 6059                Bias::Right => {
 6060                    if snippet.active_index + 1 < snippet.ranges.len() {
 6061                        snippet.active_index += 1;
 6062                    } else {
 6063                        self.snippet_stack.push(snippet);
 6064                        return false;
 6065                    }
 6066                }
 6067            }
 6068            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 6069                self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6070                    s.select_anchor_ranges(current_ranges.iter().cloned())
 6071                });
 6072
 6073                if let Some(choices) = &snippet.choices[snippet.active_index] {
 6074                    if let Some(selection) = current_ranges.first() {
 6075                        self.show_snippet_choices(&choices, selection.clone(), cx);
 6076                    }
 6077                }
 6078
 6079                // If snippet state is not at the last tabstop, push it back on the stack
 6080                if snippet.active_index + 1 < snippet.ranges.len() {
 6081                    self.snippet_stack.push(snippet);
 6082                }
 6083                return true;
 6084            }
 6085        }
 6086
 6087        false
 6088    }
 6089
 6090    pub fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 6091        self.transact(window, cx, |this, window, cx| {
 6092            this.select_all(&SelectAll, window, cx);
 6093            this.insert("", window, cx);
 6094        });
 6095    }
 6096
 6097    pub fn backspace(&mut self, _: &Backspace, window: &mut Window, cx: &mut Context<Self>) {
 6098        self.transact(window, cx, |this, window, cx| {
 6099            this.select_autoclose_pair(window, cx);
 6100            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 6101            if !this.linked_edit_ranges.is_empty() {
 6102                let selections = this.selections.all::<MultiBufferPoint>(cx);
 6103                let snapshot = this.buffer.read(cx).snapshot(cx);
 6104
 6105                for selection in selections.iter() {
 6106                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 6107                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 6108                    if selection_start.buffer_id != selection_end.buffer_id {
 6109                        continue;
 6110                    }
 6111                    if let Some(ranges) =
 6112                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 6113                    {
 6114                        for (buffer, entries) in ranges {
 6115                            linked_ranges.entry(buffer).or_default().extend(entries);
 6116                        }
 6117                    }
 6118                }
 6119            }
 6120
 6121            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 6122            if !this.selections.line_mode {
 6123                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 6124                for selection in &mut selections {
 6125                    if selection.is_empty() {
 6126                        let old_head = selection.head();
 6127                        let mut new_head =
 6128                            movement::left(&display_map, old_head.to_display_point(&display_map))
 6129                                .to_point(&display_map);
 6130                        if let Some((buffer, line_buffer_range)) = display_map
 6131                            .buffer_snapshot
 6132                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 6133                        {
 6134                            let indent_size =
 6135                                buffer.indent_size_for_line(line_buffer_range.start.row);
 6136                            let indent_len = match indent_size.kind {
 6137                                IndentKind::Space => {
 6138                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 6139                                }
 6140                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 6141                            };
 6142                            if old_head.column <= indent_size.len && old_head.column > 0 {
 6143                                let indent_len = indent_len.get();
 6144                                new_head = cmp::min(
 6145                                    new_head,
 6146                                    MultiBufferPoint::new(
 6147                                        old_head.row,
 6148                                        ((old_head.column - 1) / indent_len) * indent_len,
 6149                                    ),
 6150                                );
 6151                            }
 6152                        }
 6153
 6154                        selection.set_head(new_head, SelectionGoal::None);
 6155                    }
 6156                }
 6157            }
 6158
 6159            this.signature_help_state.set_backspace_pressed(true);
 6160            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6161                s.select(selections)
 6162            });
 6163            this.insert("", window, cx);
 6164            let empty_str: Arc<str> = Arc::from("");
 6165            for (buffer, edits) in linked_ranges {
 6166                let snapshot = buffer.read(cx).snapshot();
 6167                use text::ToPoint as TP;
 6168
 6169                let edits = edits
 6170                    .into_iter()
 6171                    .map(|range| {
 6172                        let end_point = TP::to_point(&range.end, &snapshot);
 6173                        let mut start_point = TP::to_point(&range.start, &snapshot);
 6174
 6175                        if end_point == start_point {
 6176                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 6177                                .saturating_sub(1);
 6178                            start_point =
 6179                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 6180                        };
 6181
 6182                        (start_point..end_point, empty_str.clone())
 6183                    })
 6184                    .sorted_by_key(|(range, _)| range.start)
 6185                    .collect::<Vec<_>>();
 6186                buffer.update(cx, |this, cx| {
 6187                    this.edit(edits, None, cx);
 6188                })
 6189            }
 6190            this.refresh_inline_completion(true, false, window, cx);
 6191            linked_editing_ranges::refresh_linked_ranges(this, window, cx);
 6192        });
 6193    }
 6194
 6195    pub fn delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
 6196        self.transact(window, cx, |this, window, cx| {
 6197            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6198                let line_mode = s.line_mode;
 6199                s.move_with(|map, selection| {
 6200                    if selection.is_empty() && !line_mode {
 6201                        let cursor = movement::right(map, selection.head());
 6202                        selection.end = cursor;
 6203                        selection.reversed = true;
 6204                        selection.goal = SelectionGoal::None;
 6205                    }
 6206                })
 6207            });
 6208            this.insert("", window, cx);
 6209            this.refresh_inline_completion(true, false, window, cx);
 6210        });
 6211    }
 6212
 6213    pub fn tab_prev(&mut self, _: &TabPrev, window: &mut Window, cx: &mut Context<Self>) {
 6214        if self.move_to_prev_snippet_tabstop(window, cx) {
 6215            return;
 6216        }
 6217
 6218        self.outdent(&Outdent, window, cx);
 6219    }
 6220
 6221    pub fn tab(&mut self, _: &Tab, window: &mut Window, cx: &mut Context<Self>) {
 6222        if self.move_to_next_snippet_tabstop(window, cx) || self.read_only(cx) {
 6223            return;
 6224        }
 6225
 6226        let mut selections = self.selections.all_adjusted(cx);
 6227        let buffer = self.buffer.read(cx);
 6228        let snapshot = buffer.snapshot(cx);
 6229        let rows_iter = selections.iter().map(|s| s.head().row);
 6230        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 6231
 6232        let mut edits = Vec::new();
 6233        let mut prev_edited_row = 0;
 6234        let mut row_delta = 0;
 6235        for selection in &mut selections {
 6236            if selection.start.row != prev_edited_row {
 6237                row_delta = 0;
 6238            }
 6239            prev_edited_row = selection.end.row;
 6240
 6241            // If the selection is non-empty, then increase the indentation of the selected lines.
 6242            if !selection.is_empty() {
 6243                row_delta =
 6244                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6245                continue;
 6246            }
 6247
 6248            // If the selection is empty and the cursor is in the leading whitespace before the
 6249            // suggested indentation, then auto-indent the line.
 6250            let cursor = selection.head();
 6251            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 6252            if let Some(suggested_indent) =
 6253                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 6254            {
 6255                if cursor.column < suggested_indent.len
 6256                    && cursor.column <= current_indent.len
 6257                    && current_indent.len <= suggested_indent.len
 6258                {
 6259                    selection.start = Point::new(cursor.row, suggested_indent.len);
 6260                    selection.end = selection.start;
 6261                    if row_delta == 0 {
 6262                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 6263                            cursor.row,
 6264                            current_indent,
 6265                            suggested_indent,
 6266                        ));
 6267                        row_delta = suggested_indent.len - current_indent.len;
 6268                    }
 6269                    continue;
 6270                }
 6271            }
 6272
 6273            // Otherwise, insert a hard or soft tab.
 6274            let settings = buffer.settings_at(cursor, cx);
 6275            let tab_size = if settings.hard_tabs {
 6276                IndentSize::tab()
 6277            } else {
 6278                let tab_size = settings.tab_size.get();
 6279                let char_column = snapshot
 6280                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 6281                    .flat_map(str::chars)
 6282                    .count()
 6283                    + row_delta as usize;
 6284                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 6285                IndentSize::spaces(chars_to_next_tab_stop)
 6286            };
 6287            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 6288            selection.end = selection.start;
 6289            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 6290            row_delta += tab_size.len;
 6291        }
 6292
 6293        self.transact(window, cx, |this, window, cx| {
 6294            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6295            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6296                s.select(selections)
 6297            });
 6298            this.refresh_inline_completion(true, false, window, cx);
 6299        });
 6300    }
 6301
 6302    pub fn indent(&mut self, _: &Indent, window: &mut Window, cx: &mut Context<Self>) {
 6303        if self.read_only(cx) {
 6304            return;
 6305        }
 6306        let mut selections = self.selections.all::<Point>(cx);
 6307        let mut prev_edited_row = 0;
 6308        let mut row_delta = 0;
 6309        let mut edits = Vec::new();
 6310        let buffer = self.buffer.read(cx);
 6311        let snapshot = buffer.snapshot(cx);
 6312        for selection in &mut selections {
 6313            if selection.start.row != prev_edited_row {
 6314                row_delta = 0;
 6315            }
 6316            prev_edited_row = selection.end.row;
 6317
 6318            row_delta =
 6319                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 6320        }
 6321
 6322        self.transact(window, cx, |this, window, cx| {
 6323            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 6324            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6325                s.select(selections)
 6326            });
 6327        });
 6328    }
 6329
 6330    fn indent_selection(
 6331        buffer: &MultiBuffer,
 6332        snapshot: &MultiBufferSnapshot,
 6333        selection: &mut Selection<Point>,
 6334        edits: &mut Vec<(Range<Point>, String)>,
 6335        delta_for_start_row: u32,
 6336        cx: &App,
 6337    ) -> u32 {
 6338        let settings = buffer.settings_at(selection.start, cx);
 6339        let tab_size = settings.tab_size.get();
 6340        let indent_kind = if settings.hard_tabs {
 6341            IndentKind::Tab
 6342        } else {
 6343            IndentKind::Space
 6344        };
 6345        let mut start_row = selection.start.row;
 6346        let mut end_row = selection.end.row + 1;
 6347
 6348        // If a selection ends at the beginning of a line, don't indent
 6349        // that last line.
 6350        if selection.end.column == 0 && selection.end.row > selection.start.row {
 6351            end_row -= 1;
 6352        }
 6353
 6354        // Avoid re-indenting a row that has already been indented by a
 6355        // previous selection, but still update this selection's column
 6356        // to reflect that indentation.
 6357        if delta_for_start_row > 0 {
 6358            start_row += 1;
 6359            selection.start.column += delta_for_start_row;
 6360            if selection.end.row == selection.start.row {
 6361                selection.end.column += delta_for_start_row;
 6362            }
 6363        }
 6364
 6365        let mut delta_for_end_row = 0;
 6366        let has_multiple_rows = start_row + 1 != end_row;
 6367        for row in start_row..end_row {
 6368            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 6369            let indent_delta = match (current_indent.kind, indent_kind) {
 6370                (IndentKind::Space, IndentKind::Space) => {
 6371                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 6372                    IndentSize::spaces(columns_to_next_tab_stop)
 6373                }
 6374                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 6375                (_, IndentKind::Tab) => IndentSize::tab(),
 6376            };
 6377
 6378            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 6379                0
 6380            } else {
 6381                selection.start.column
 6382            };
 6383            let row_start = Point::new(row, start);
 6384            edits.push((
 6385                row_start..row_start,
 6386                indent_delta.chars().collect::<String>(),
 6387            ));
 6388
 6389            // Update this selection's endpoints to reflect the indentation.
 6390            if row == selection.start.row {
 6391                selection.start.column += indent_delta.len;
 6392            }
 6393            if row == selection.end.row {
 6394                selection.end.column += indent_delta.len;
 6395                delta_for_end_row = indent_delta.len;
 6396            }
 6397        }
 6398
 6399        if selection.start.row == selection.end.row {
 6400            delta_for_start_row + delta_for_end_row
 6401        } else {
 6402            delta_for_end_row
 6403        }
 6404    }
 6405
 6406    pub fn outdent(&mut self, _: &Outdent, window: &mut Window, cx: &mut Context<Self>) {
 6407        if self.read_only(cx) {
 6408            return;
 6409        }
 6410        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6411        let selections = self.selections.all::<Point>(cx);
 6412        let mut deletion_ranges = Vec::new();
 6413        let mut last_outdent = None;
 6414        {
 6415            let buffer = self.buffer.read(cx);
 6416            let snapshot = buffer.snapshot(cx);
 6417            for selection in &selections {
 6418                let settings = buffer.settings_at(selection.start, cx);
 6419                let tab_size = settings.tab_size.get();
 6420                let mut rows = selection.spanned_rows(false, &display_map);
 6421
 6422                // Avoid re-outdenting a row that has already been outdented by a
 6423                // previous selection.
 6424                if let Some(last_row) = last_outdent {
 6425                    if last_row == rows.start {
 6426                        rows.start = rows.start.next_row();
 6427                    }
 6428                }
 6429                let has_multiple_rows = rows.len() > 1;
 6430                for row in rows.iter_rows() {
 6431                    let indent_size = snapshot.indent_size_for_line(row);
 6432                    if indent_size.len > 0 {
 6433                        let deletion_len = match indent_size.kind {
 6434                            IndentKind::Space => {
 6435                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 6436                                if columns_to_prev_tab_stop == 0 {
 6437                                    tab_size
 6438                                } else {
 6439                                    columns_to_prev_tab_stop
 6440                                }
 6441                            }
 6442                            IndentKind::Tab => 1,
 6443                        };
 6444                        let start = if has_multiple_rows
 6445                            || deletion_len > selection.start.column
 6446                            || indent_size.len < selection.start.column
 6447                        {
 6448                            0
 6449                        } else {
 6450                            selection.start.column - deletion_len
 6451                        };
 6452                        deletion_ranges.push(
 6453                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 6454                        );
 6455                        last_outdent = Some(row);
 6456                    }
 6457                }
 6458            }
 6459        }
 6460
 6461        self.transact(window, cx, |this, window, cx| {
 6462            this.buffer.update(cx, |buffer, cx| {
 6463                let empty_str: Arc<str> = Arc::default();
 6464                buffer.edit(
 6465                    deletion_ranges
 6466                        .into_iter()
 6467                        .map(|range| (range, empty_str.clone())),
 6468                    None,
 6469                    cx,
 6470                );
 6471            });
 6472            let selections = this.selections.all::<usize>(cx);
 6473            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6474                s.select(selections)
 6475            });
 6476        });
 6477    }
 6478
 6479    pub fn autoindent(&mut self, _: &AutoIndent, window: &mut Window, cx: &mut Context<Self>) {
 6480        if self.read_only(cx) {
 6481            return;
 6482        }
 6483        let selections = self
 6484            .selections
 6485            .all::<usize>(cx)
 6486            .into_iter()
 6487            .map(|s| s.range());
 6488
 6489        self.transact(window, cx, |this, window, cx| {
 6490            this.buffer.update(cx, |buffer, cx| {
 6491                buffer.autoindent_ranges(selections, cx);
 6492            });
 6493            let selections = this.selections.all::<usize>(cx);
 6494            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6495                s.select(selections)
 6496            });
 6497        });
 6498    }
 6499
 6500    pub fn delete_line(&mut self, _: &DeleteLine, window: &mut Window, cx: &mut Context<Self>) {
 6501        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6502        let selections = self.selections.all::<Point>(cx);
 6503
 6504        let mut new_cursors = Vec::new();
 6505        let mut edit_ranges = Vec::new();
 6506        let mut selections = selections.iter().peekable();
 6507        while let Some(selection) = selections.next() {
 6508            let mut rows = selection.spanned_rows(false, &display_map);
 6509            let goal_display_column = selection.head().to_display_point(&display_map).column();
 6510
 6511            // Accumulate contiguous regions of rows that we want to delete.
 6512            while let Some(next_selection) = selections.peek() {
 6513                let next_rows = next_selection.spanned_rows(false, &display_map);
 6514                if next_rows.start <= rows.end {
 6515                    rows.end = next_rows.end;
 6516                    selections.next().unwrap();
 6517                } else {
 6518                    break;
 6519                }
 6520            }
 6521
 6522            let buffer = &display_map.buffer_snapshot;
 6523            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 6524            let edit_end;
 6525            let cursor_buffer_row;
 6526            if buffer.max_point().row >= rows.end.0 {
 6527                // If there's a line after the range, delete the \n from the end of the row range
 6528                // and position the cursor on the next line.
 6529                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 6530                cursor_buffer_row = rows.end;
 6531            } else {
 6532                // If there isn't a line after the range, delete the \n from the line before the
 6533                // start of the row range and position the cursor there.
 6534                edit_start = edit_start.saturating_sub(1);
 6535                edit_end = buffer.len();
 6536                cursor_buffer_row = rows.start.previous_row();
 6537            }
 6538
 6539            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 6540            *cursor.column_mut() =
 6541                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 6542
 6543            new_cursors.push((
 6544                selection.id,
 6545                buffer.anchor_after(cursor.to_point(&display_map)),
 6546            ));
 6547            edit_ranges.push(edit_start..edit_end);
 6548        }
 6549
 6550        self.transact(window, cx, |this, window, cx| {
 6551            let buffer = this.buffer.update(cx, |buffer, cx| {
 6552                let empty_str: Arc<str> = Arc::default();
 6553                buffer.edit(
 6554                    edit_ranges
 6555                        .into_iter()
 6556                        .map(|range| (range, empty_str.clone())),
 6557                    None,
 6558                    cx,
 6559                );
 6560                buffer.snapshot(cx)
 6561            });
 6562            let new_selections = new_cursors
 6563                .into_iter()
 6564                .map(|(id, cursor)| {
 6565                    let cursor = cursor.to_point(&buffer);
 6566                    Selection {
 6567                        id,
 6568                        start: cursor,
 6569                        end: cursor,
 6570                        reversed: false,
 6571                        goal: SelectionGoal::None,
 6572                    }
 6573                })
 6574                .collect();
 6575
 6576            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6577                s.select(new_selections);
 6578            });
 6579        });
 6580    }
 6581
 6582    pub fn join_lines_impl(
 6583        &mut self,
 6584        insert_whitespace: bool,
 6585        window: &mut Window,
 6586        cx: &mut Context<Self>,
 6587    ) {
 6588        if self.read_only(cx) {
 6589            return;
 6590        }
 6591        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 6592        for selection in self.selections.all::<Point>(cx) {
 6593            let start = MultiBufferRow(selection.start.row);
 6594            // Treat single line selections as if they include the next line. Otherwise this action
 6595            // would do nothing for single line selections individual cursors.
 6596            let end = if selection.start.row == selection.end.row {
 6597                MultiBufferRow(selection.start.row + 1)
 6598            } else {
 6599                MultiBufferRow(selection.end.row)
 6600            };
 6601
 6602            if let Some(last_row_range) = row_ranges.last_mut() {
 6603                if start <= last_row_range.end {
 6604                    last_row_range.end = end;
 6605                    continue;
 6606                }
 6607            }
 6608            row_ranges.push(start..end);
 6609        }
 6610
 6611        let snapshot = self.buffer.read(cx).snapshot(cx);
 6612        let mut cursor_positions = Vec::new();
 6613        for row_range in &row_ranges {
 6614            let anchor = snapshot.anchor_before(Point::new(
 6615                row_range.end.previous_row().0,
 6616                snapshot.line_len(row_range.end.previous_row()),
 6617            ));
 6618            cursor_positions.push(anchor..anchor);
 6619        }
 6620
 6621        self.transact(window, cx, |this, window, cx| {
 6622            for row_range in row_ranges.into_iter().rev() {
 6623                for row in row_range.iter_rows().rev() {
 6624                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 6625                    let next_line_row = row.next_row();
 6626                    let indent = snapshot.indent_size_for_line(next_line_row);
 6627                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 6628
 6629                    let replace =
 6630                        if snapshot.line_len(next_line_row) > indent.len && insert_whitespace {
 6631                            " "
 6632                        } else {
 6633                            ""
 6634                        };
 6635
 6636                    this.buffer.update(cx, |buffer, cx| {
 6637                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 6638                    });
 6639                }
 6640            }
 6641
 6642            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6643                s.select_anchor_ranges(cursor_positions)
 6644            });
 6645        });
 6646    }
 6647
 6648    pub fn join_lines(&mut self, _: &JoinLines, window: &mut Window, cx: &mut Context<Self>) {
 6649        self.join_lines_impl(true, window, cx);
 6650    }
 6651
 6652    pub fn sort_lines_case_sensitive(
 6653        &mut self,
 6654        _: &SortLinesCaseSensitive,
 6655        window: &mut Window,
 6656        cx: &mut Context<Self>,
 6657    ) {
 6658        self.manipulate_lines(window, cx, |lines| lines.sort())
 6659    }
 6660
 6661    pub fn sort_lines_case_insensitive(
 6662        &mut self,
 6663        _: &SortLinesCaseInsensitive,
 6664        window: &mut Window,
 6665        cx: &mut Context<Self>,
 6666    ) {
 6667        self.manipulate_lines(window, cx, |lines| {
 6668            lines.sort_by_key(|line| line.to_lowercase())
 6669        })
 6670    }
 6671
 6672    pub fn unique_lines_case_insensitive(
 6673        &mut self,
 6674        _: &UniqueLinesCaseInsensitive,
 6675        window: &mut Window,
 6676        cx: &mut Context<Self>,
 6677    ) {
 6678        self.manipulate_lines(window, cx, |lines| {
 6679            let mut seen = HashSet::default();
 6680            lines.retain(|line| seen.insert(line.to_lowercase()));
 6681        })
 6682    }
 6683
 6684    pub fn unique_lines_case_sensitive(
 6685        &mut self,
 6686        _: &UniqueLinesCaseSensitive,
 6687        window: &mut Window,
 6688        cx: &mut Context<Self>,
 6689    ) {
 6690        self.manipulate_lines(window, cx, |lines| {
 6691            let mut seen = HashSet::default();
 6692            lines.retain(|line| seen.insert(*line));
 6693        })
 6694    }
 6695
 6696    pub fn revert_file(&mut self, _: &RevertFile, window: &mut Window, cx: &mut Context<Self>) {
 6697        let mut revert_changes = HashMap::default();
 6698        let snapshot = self.snapshot(window, cx);
 6699        for hunk in snapshot
 6700            .hunks_for_ranges(Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter())
 6701        {
 6702            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6703        }
 6704        if !revert_changes.is_empty() {
 6705            self.transact(window, cx, |editor, window, cx| {
 6706                editor.revert(revert_changes, window, cx);
 6707            });
 6708        }
 6709    }
 6710
 6711    pub fn reload_file(&mut self, _: &ReloadFile, window: &mut Window, cx: &mut Context<Self>) {
 6712        let Some(project) = self.project.clone() else {
 6713            return;
 6714        };
 6715        self.reload(project, window, cx)
 6716            .detach_and_notify_err(window, cx);
 6717    }
 6718
 6719    pub fn revert_selected_hunks(
 6720        &mut self,
 6721        _: &RevertSelectedHunks,
 6722        window: &mut Window,
 6723        cx: &mut Context<Self>,
 6724    ) {
 6725        let selections = self.selections.all(cx).into_iter().map(|s| s.range());
 6726        self.revert_hunks_in_ranges(selections, window, cx);
 6727    }
 6728
 6729    fn revert_hunks_in_ranges(
 6730        &mut self,
 6731        ranges: impl Iterator<Item = Range<Point>>,
 6732        window: &mut Window,
 6733        cx: &mut Context<Editor>,
 6734    ) {
 6735        let mut revert_changes = HashMap::default();
 6736        let snapshot = self.snapshot(window, cx);
 6737        for hunk in &snapshot.hunks_for_ranges(ranges) {
 6738            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 6739        }
 6740        if !revert_changes.is_empty() {
 6741            self.transact(window, cx, |editor, window, cx| {
 6742                editor.revert(revert_changes, window, cx);
 6743            });
 6744        }
 6745    }
 6746
 6747    pub fn open_active_item_in_terminal(
 6748        &mut self,
 6749        _: &OpenInTerminal,
 6750        window: &mut Window,
 6751        cx: &mut Context<Self>,
 6752    ) {
 6753        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 6754            let project_path = buffer.read(cx).project_path(cx)?;
 6755            let project = self.project.as_ref()?.read(cx);
 6756            let entry = project.entry_for_path(&project_path, cx)?;
 6757            let parent = match &entry.canonical_path {
 6758                Some(canonical_path) => canonical_path.to_path_buf(),
 6759                None => project.absolute_path(&project_path, cx)?,
 6760            }
 6761            .parent()?
 6762            .to_path_buf();
 6763            Some(parent)
 6764        }) {
 6765            window.dispatch_action(OpenTerminal { working_directory }.boxed_clone(), cx);
 6766        }
 6767    }
 6768
 6769    pub fn prepare_revert_change(
 6770        &self,
 6771        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6772        hunk: &MultiBufferDiffHunk,
 6773        cx: &mut App,
 6774    ) -> Option<()> {
 6775        let buffer = self.buffer.read(cx);
 6776        let diff = buffer.diff_for(hunk.buffer_id)?;
 6777        let buffer = buffer.buffer(hunk.buffer_id)?;
 6778        let buffer = buffer.read(cx);
 6779        let original_text = diff
 6780            .read(cx)
 6781            .snapshot
 6782            .base_text
 6783            .as_ref()?
 6784            .as_rope()
 6785            .slice(hunk.diff_base_byte_range.clone());
 6786        let buffer_snapshot = buffer.snapshot();
 6787        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6788        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6789            probe
 6790                .0
 6791                .start
 6792                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6793                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6794        }) {
 6795            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6796            Some(())
 6797        } else {
 6798            None
 6799        }
 6800    }
 6801
 6802    pub fn reverse_lines(&mut self, _: &ReverseLines, window: &mut Window, cx: &mut Context<Self>) {
 6803        self.manipulate_lines(window, cx, |lines| lines.reverse())
 6804    }
 6805
 6806    pub fn shuffle_lines(&mut self, _: &ShuffleLines, window: &mut Window, cx: &mut Context<Self>) {
 6807        self.manipulate_lines(window, cx, |lines| lines.shuffle(&mut thread_rng()))
 6808    }
 6809
 6810    fn manipulate_lines<Fn>(
 6811        &mut self,
 6812        window: &mut Window,
 6813        cx: &mut Context<Self>,
 6814        mut callback: Fn,
 6815    ) where
 6816        Fn: FnMut(&mut Vec<&str>),
 6817    {
 6818        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6819        let buffer = self.buffer.read(cx).snapshot(cx);
 6820
 6821        let mut edits = Vec::new();
 6822
 6823        let selections = self.selections.all::<Point>(cx);
 6824        let mut selections = selections.iter().peekable();
 6825        let mut contiguous_row_selections = Vec::new();
 6826        let mut new_selections = Vec::new();
 6827        let mut added_lines = 0;
 6828        let mut removed_lines = 0;
 6829
 6830        while let Some(selection) = selections.next() {
 6831            let (start_row, end_row) = consume_contiguous_rows(
 6832                &mut contiguous_row_selections,
 6833                selection,
 6834                &display_map,
 6835                &mut selections,
 6836            );
 6837
 6838            let start_point = Point::new(start_row.0, 0);
 6839            let end_point = Point::new(
 6840                end_row.previous_row().0,
 6841                buffer.line_len(end_row.previous_row()),
 6842            );
 6843            let text = buffer
 6844                .text_for_range(start_point..end_point)
 6845                .collect::<String>();
 6846
 6847            let mut lines = text.split('\n').collect_vec();
 6848
 6849            let lines_before = lines.len();
 6850            callback(&mut lines);
 6851            let lines_after = lines.len();
 6852
 6853            edits.push((start_point..end_point, lines.join("\n")));
 6854
 6855            // Selections must change based on added and removed line count
 6856            let start_row =
 6857                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6858            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6859            new_selections.push(Selection {
 6860                id: selection.id,
 6861                start: start_row,
 6862                end: end_row,
 6863                goal: SelectionGoal::None,
 6864                reversed: selection.reversed,
 6865            });
 6866
 6867            if lines_after > lines_before {
 6868                added_lines += lines_after - lines_before;
 6869            } else if lines_before > lines_after {
 6870                removed_lines += lines_before - lines_after;
 6871            }
 6872        }
 6873
 6874        self.transact(window, cx, |this, window, cx| {
 6875            let buffer = this.buffer.update(cx, |buffer, cx| {
 6876                buffer.edit(edits, None, cx);
 6877                buffer.snapshot(cx)
 6878            });
 6879
 6880            // Recalculate offsets on newly edited buffer
 6881            let new_selections = new_selections
 6882                .iter()
 6883                .map(|s| {
 6884                    let start_point = Point::new(s.start.0, 0);
 6885                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6886                    Selection {
 6887                        id: s.id,
 6888                        start: buffer.point_to_offset(start_point),
 6889                        end: buffer.point_to_offset(end_point),
 6890                        goal: s.goal,
 6891                        reversed: s.reversed,
 6892                    }
 6893                })
 6894                .collect();
 6895
 6896            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 6897                s.select(new_selections);
 6898            });
 6899
 6900            this.request_autoscroll(Autoscroll::fit(), cx);
 6901        });
 6902    }
 6903
 6904    pub fn convert_to_upper_case(
 6905        &mut self,
 6906        _: &ConvertToUpperCase,
 6907        window: &mut Window,
 6908        cx: &mut Context<Self>,
 6909    ) {
 6910        self.manipulate_text(window, cx, |text| text.to_uppercase())
 6911    }
 6912
 6913    pub fn convert_to_lower_case(
 6914        &mut self,
 6915        _: &ConvertToLowerCase,
 6916        window: &mut Window,
 6917        cx: &mut Context<Self>,
 6918    ) {
 6919        self.manipulate_text(window, cx, |text| text.to_lowercase())
 6920    }
 6921
 6922    pub fn convert_to_title_case(
 6923        &mut self,
 6924        _: &ConvertToTitleCase,
 6925        window: &mut Window,
 6926        cx: &mut Context<Self>,
 6927    ) {
 6928        self.manipulate_text(window, cx, |text| {
 6929            text.split('\n')
 6930                .map(|line| line.to_case(Case::Title))
 6931                .join("\n")
 6932        })
 6933    }
 6934
 6935    pub fn convert_to_snake_case(
 6936        &mut self,
 6937        _: &ConvertToSnakeCase,
 6938        window: &mut Window,
 6939        cx: &mut Context<Self>,
 6940    ) {
 6941        self.manipulate_text(window, cx, |text| text.to_case(Case::Snake))
 6942    }
 6943
 6944    pub fn convert_to_kebab_case(
 6945        &mut self,
 6946        _: &ConvertToKebabCase,
 6947        window: &mut Window,
 6948        cx: &mut Context<Self>,
 6949    ) {
 6950        self.manipulate_text(window, cx, |text| text.to_case(Case::Kebab))
 6951    }
 6952
 6953    pub fn convert_to_upper_camel_case(
 6954        &mut self,
 6955        _: &ConvertToUpperCamelCase,
 6956        window: &mut Window,
 6957        cx: &mut Context<Self>,
 6958    ) {
 6959        self.manipulate_text(window, cx, |text| {
 6960            text.split('\n')
 6961                .map(|line| line.to_case(Case::UpperCamel))
 6962                .join("\n")
 6963        })
 6964    }
 6965
 6966    pub fn convert_to_lower_camel_case(
 6967        &mut self,
 6968        _: &ConvertToLowerCamelCase,
 6969        window: &mut Window,
 6970        cx: &mut Context<Self>,
 6971    ) {
 6972        self.manipulate_text(window, cx, |text| text.to_case(Case::Camel))
 6973    }
 6974
 6975    pub fn convert_to_opposite_case(
 6976        &mut self,
 6977        _: &ConvertToOppositeCase,
 6978        window: &mut Window,
 6979        cx: &mut Context<Self>,
 6980    ) {
 6981        self.manipulate_text(window, cx, |text| {
 6982            text.chars()
 6983                .fold(String::with_capacity(text.len()), |mut t, c| {
 6984                    if c.is_uppercase() {
 6985                        t.extend(c.to_lowercase());
 6986                    } else {
 6987                        t.extend(c.to_uppercase());
 6988                    }
 6989                    t
 6990                })
 6991        })
 6992    }
 6993
 6994    fn manipulate_text<Fn>(&mut self, window: &mut Window, cx: &mut Context<Self>, mut callback: Fn)
 6995    where
 6996        Fn: FnMut(&str) -> String,
 6997    {
 6998        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6999        let buffer = self.buffer.read(cx).snapshot(cx);
 7000
 7001        let mut new_selections = Vec::new();
 7002        let mut edits = Vec::new();
 7003        let mut selection_adjustment = 0i32;
 7004
 7005        for selection in self.selections.all::<usize>(cx) {
 7006            let selection_is_empty = selection.is_empty();
 7007
 7008            let (start, end) = if selection_is_empty {
 7009                let word_range = movement::surrounding_word(
 7010                    &display_map,
 7011                    selection.start.to_display_point(&display_map),
 7012                );
 7013                let start = word_range.start.to_offset(&display_map, Bias::Left);
 7014                let end = word_range.end.to_offset(&display_map, Bias::Left);
 7015                (start, end)
 7016            } else {
 7017                (selection.start, selection.end)
 7018            };
 7019
 7020            let text = buffer.text_for_range(start..end).collect::<String>();
 7021            let old_length = text.len() as i32;
 7022            let text = callback(&text);
 7023
 7024            new_selections.push(Selection {
 7025                start: (start as i32 - selection_adjustment) as usize,
 7026                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 7027                goal: SelectionGoal::None,
 7028                ..selection
 7029            });
 7030
 7031            selection_adjustment += old_length - text.len() as i32;
 7032
 7033            edits.push((start..end, text));
 7034        }
 7035
 7036        self.transact(window, cx, |this, window, cx| {
 7037            this.buffer.update(cx, |buffer, cx| {
 7038                buffer.edit(edits, None, cx);
 7039            });
 7040
 7041            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7042                s.select(new_selections);
 7043            });
 7044
 7045            this.request_autoscroll(Autoscroll::fit(), cx);
 7046        });
 7047    }
 7048
 7049    pub fn duplicate(
 7050        &mut self,
 7051        upwards: bool,
 7052        whole_lines: bool,
 7053        window: &mut Window,
 7054        cx: &mut Context<Self>,
 7055    ) {
 7056        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7057        let buffer = &display_map.buffer_snapshot;
 7058        let selections = self.selections.all::<Point>(cx);
 7059
 7060        let mut edits = Vec::new();
 7061        let mut selections_iter = selections.iter().peekable();
 7062        while let Some(selection) = selections_iter.next() {
 7063            let mut rows = selection.spanned_rows(false, &display_map);
 7064            // duplicate line-wise
 7065            if whole_lines || selection.start == selection.end {
 7066                // Avoid duplicating the same lines twice.
 7067                while let Some(next_selection) = selections_iter.peek() {
 7068                    let next_rows = next_selection.spanned_rows(false, &display_map);
 7069                    if next_rows.start < rows.end {
 7070                        rows.end = next_rows.end;
 7071                        selections_iter.next().unwrap();
 7072                    } else {
 7073                        break;
 7074                    }
 7075                }
 7076
 7077                // Copy the text from the selected row region and splice it either at the start
 7078                // or end of the region.
 7079                let start = Point::new(rows.start.0, 0);
 7080                let end = Point::new(
 7081                    rows.end.previous_row().0,
 7082                    buffer.line_len(rows.end.previous_row()),
 7083                );
 7084                let text = buffer
 7085                    .text_for_range(start..end)
 7086                    .chain(Some("\n"))
 7087                    .collect::<String>();
 7088                let insert_location = if upwards {
 7089                    Point::new(rows.end.0, 0)
 7090                } else {
 7091                    start
 7092                };
 7093                edits.push((insert_location..insert_location, text));
 7094            } else {
 7095                // duplicate character-wise
 7096                let start = selection.start;
 7097                let end = selection.end;
 7098                let text = buffer.text_for_range(start..end).collect::<String>();
 7099                edits.push((selection.end..selection.end, text));
 7100            }
 7101        }
 7102
 7103        self.transact(window, cx, |this, _, cx| {
 7104            this.buffer.update(cx, |buffer, cx| {
 7105                buffer.edit(edits, None, cx);
 7106            });
 7107
 7108            this.request_autoscroll(Autoscroll::fit(), cx);
 7109        });
 7110    }
 7111
 7112    pub fn duplicate_line_up(
 7113        &mut self,
 7114        _: &DuplicateLineUp,
 7115        window: &mut Window,
 7116        cx: &mut Context<Self>,
 7117    ) {
 7118        self.duplicate(true, true, window, cx);
 7119    }
 7120
 7121    pub fn duplicate_line_down(
 7122        &mut self,
 7123        _: &DuplicateLineDown,
 7124        window: &mut Window,
 7125        cx: &mut Context<Self>,
 7126    ) {
 7127        self.duplicate(false, true, window, cx);
 7128    }
 7129
 7130    pub fn duplicate_selection(
 7131        &mut self,
 7132        _: &DuplicateSelection,
 7133        window: &mut Window,
 7134        cx: &mut Context<Self>,
 7135    ) {
 7136        self.duplicate(false, false, window, cx);
 7137    }
 7138
 7139    pub fn move_line_up(&mut self, _: &MoveLineUp, window: &mut Window, cx: &mut Context<Self>) {
 7140        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7141        let buffer = self.buffer.read(cx).snapshot(cx);
 7142
 7143        let mut edits = Vec::new();
 7144        let mut unfold_ranges = Vec::new();
 7145        let mut refold_creases = Vec::new();
 7146
 7147        let selections = self.selections.all::<Point>(cx);
 7148        let mut selections = selections.iter().peekable();
 7149        let mut contiguous_row_selections = Vec::new();
 7150        let mut new_selections = Vec::new();
 7151
 7152        while let Some(selection) = selections.next() {
 7153            // Find all the selections that span a contiguous row range
 7154            let (start_row, end_row) = consume_contiguous_rows(
 7155                &mut contiguous_row_selections,
 7156                selection,
 7157                &display_map,
 7158                &mut selections,
 7159            );
 7160
 7161            // Move the text spanned by the row range to be before the line preceding the row range
 7162            if start_row.0 > 0 {
 7163                let range_to_move = Point::new(
 7164                    start_row.previous_row().0,
 7165                    buffer.line_len(start_row.previous_row()),
 7166                )
 7167                    ..Point::new(
 7168                        end_row.previous_row().0,
 7169                        buffer.line_len(end_row.previous_row()),
 7170                    );
 7171                let insertion_point = display_map
 7172                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 7173                    .0;
 7174
 7175                // Don't move lines across excerpts
 7176                if buffer
 7177                    .excerpt_containing(insertion_point..range_to_move.end)
 7178                    .is_some()
 7179                {
 7180                    let text = buffer
 7181                        .text_for_range(range_to_move.clone())
 7182                        .flat_map(|s| s.chars())
 7183                        .skip(1)
 7184                        .chain(['\n'])
 7185                        .collect::<String>();
 7186
 7187                    edits.push((
 7188                        buffer.anchor_after(range_to_move.start)
 7189                            ..buffer.anchor_before(range_to_move.end),
 7190                        String::new(),
 7191                    ));
 7192                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7193                    edits.push((insertion_anchor..insertion_anchor, text));
 7194
 7195                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 7196
 7197                    // Move selections up
 7198                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7199                        |mut selection| {
 7200                            selection.start.row -= row_delta;
 7201                            selection.end.row -= row_delta;
 7202                            selection
 7203                        },
 7204                    ));
 7205
 7206                    // Move folds up
 7207                    unfold_ranges.push(range_to_move.clone());
 7208                    for fold in display_map.folds_in_range(
 7209                        buffer.anchor_before(range_to_move.start)
 7210                            ..buffer.anchor_after(range_to_move.end),
 7211                    ) {
 7212                        let mut start = fold.range.start.to_point(&buffer);
 7213                        let mut end = fold.range.end.to_point(&buffer);
 7214                        start.row -= row_delta;
 7215                        end.row -= row_delta;
 7216                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7217                    }
 7218                }
 7219            }
 7220
 7221            // If we didn't move line(s), preserve the existing selections
 7222            new_selections.append(&mut contiguous_row_selections);
 7223        }
 7224
 7225        self.transact(window, cx, |this, window, cx| {
 7226            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7227            this.buffer.update(cx, |buffer, cx| {
 7228                for (range, text) in edits {
 7229                    buffer.edit([(range, text)], None, cx);
 7230                }
 7231            });
 7232            this.fold_creases(refold_creases, true, window, cx);
 7233            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7234                s.select(new_selections);
 7235            })
 7236        });
 7237    }
 7238
 7239    pub fn move_line_down(
 7240        &mut self,
 7241        _: &MoveLineDown,
 7242        window: &mut Window,
 7243        cx: &mut Context<Self>,
 7244    ) {
 7245        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7246        let buffer = self.buffer.read(cx).snapshot(cx);
 7247
 7248        let mut edits = Vec::new();
 7249        let mut unfold_ranges = Vec::new();
 7250        let mut refold_creases = Vec::new();
 7251
 7252        let selections = self.selections.all::<Point>(cx);
 7253        let mut selections = selections.iter().peekable();
 7254        let mut contiguous_row_selections = Vec::new();
 7255        let mut new_selections = Vec::new();
 7256
 7257        while let Some(selection) = selections.next() {
 7258            // Find all the selections that span a contiguous row range
 7259            let (start_row, end_row) = consume_contiguous_rows(
 7260                &mut contiguous_row_selections,
 7261                selection,
 7262                &display_map,
 7263                &mut selections,
 7264            );
 7265
 7266            // Move the text spanned by the row range to be after the last line of the row range
 7267            if end_row.0 <= buffer.max_point().row {
 7268                let range_to_move =
 7269                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 7270                let insertion_point = display_map
 7271                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 7272                    .0;
 7273
 7274                // Don't move lines across excerpt boundaries
 7275                if buffer
 7276                    .excerpt_containing(range_to_move.start..insertion_point)
 7277                    .is_some()
 7278                {
 7279                    let mut text = String::from("\n");
 7280                    text.extend(buffer.text_for_range(range_to_move.clone()));
 7281                    text.pop(); // Drop trailing newline
 7282                    edits.push((
 7283                        buffer.anchor_after(range_to_move.start)
 7284                            ..buffer.anchor_before(range_to_move.end),
 7285                        String::new(),
 7286                    ));
 7287                    let insertion_anchor = buffer.anchor_after(insertion_point);
 7288                    edits.push((insertion_anchor..insertion_anchor, text));
 7289
 7290                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 7291
 7292                    // Move selections down
 7293                    new_selections.extend(contiguous_row_selections.drain(..).map(
 7294                        |mut selection| {
 7295                            selection.start.row += row_delta;
 7296                            selection.end.row += row_delta;
 7297                            selection
 7298                        },
 7299                    ));
 7300
 7301                    // Move folds down
 7302                    unfold_ranges.push(range_to_move.clone());
 7303                    for fold in display_map.folds_in_range(
 7304                        buffer.anchor_before(range_to_move.start)
 7305                            ..buffer.anchor_after(range_to_move.end),
 7306                    ) {
 7307                        let mut start = fold.range.start.to_point(&buffer);
 7308                        let mut end = fold.range.end.to_point(&buffer);
 7309                        start.row += row_delta;
 7310                        end.row += row_delta;
 7311                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 7312                    }
 7313                }
 7314            }
 7315
 7316            // If we didn't move line(s), preserve the existing selections
 7317            new_selections.append(&mut contiguous_row_selections);
 7318        }
 7319
 7320        self.transact(window, cx, |this, window, cx| {
 7321            this.unfold_ranges(&unfold_ranges, true, true, cx);
 7322            this.buffer.update(cx, |buffer, cx| {
 7323                for (range, text) in edits {
 7324                    buffer.edit([(range, text)], None, cx);
 7325                }
 7326            });
 7327            this.fold_creases(refold_creases, true, window, cx);
 7328            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7329                s.select(new_selections)
 7330            });
 7331        });
 7332    }
 7333
 7334    pub fn transpose(&mut self, _: &Transpose, window: &mut Window, cx: &mut Context<Self>) {
 7335        let text_layout_details = &self.text_layout_details(window);
 7336        self.transact(window, cx, |this, window, cx| {
 7337            let edits = this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7338                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 7339                let line_mode = s.line_mode;
 7340                s.move_with(|display_map, selection| {
 7341                    if !selection.is_empty() || line_mode {
 7342                        return;
 7343                    }
 7344
 7345                    let mut head = selection.head();
 7346                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 7347                    if head.column() == display_map.line_len(head.row()) {
 7348                        transpose_offset = display_map
 7349                            .buffer_snapshot
 7350                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7351                    }
 7352
 7353                    if transpose_offset == 0 {
 7354                        return;
 7355                    }
 7356
 7357                    *head.column_mut() += 1;
 7358                    head = display_map.clip_point(head, Bias::Right);
 7359                    let goal = SelectionGoal::HorizontalPosition(
 7360                        display_map
 7361                            .x_for_display_point(head, text_layout_details)
 7362                            .into(),
 7363                    );
 7364                    selection.collapse_to(head, goal);
 7365
 7366                    let transpose_start = display_map
 7367                        .buffer_snapshot
 7368                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 7369                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 7370                        let transpose_end = display_map
 7371                            .buffer_snapshot
 7372                            .clip_offset(transpose_offset + 1, Bias::Right);
 7373                        if let Some(ch) =
 7374                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 7375                        {
 7376                            edits.push((transpose_start..transpose_offset, String::new()));
 7377                            edits.push((transpose_end..transpose_end, ch.to_string()));
 7378                        }
 7379                    }
 7380                });
 7381                edits
 7382            });
 7383            this.buffer
 7384                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7385            let selections = this.selections.all::<usize>(cx);
 7386            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7387                s.select(selections);
 7388            });
 7389        });
 7390    }
 7391
 7392    pub fn rewrap(&mut self, _: &Rewrap, _: &mut Window, cx: &mut Context<Self>) {
 7393        self.rewrap_impl(IsVimMode::No, cx)
 7394    }
 7395
 7396    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut Context<Self>) {
 7397        let buffer = self.buffer.read(cx).snapshot(cx);
 7398        let selections = self.selections.all::<Point>(cx);
 7399        let mut selections = selections.iter().peekable();
 7400
 7401        let mut edits = Vec::new();
 7402        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 7403
 7404        while let Some(selection) = selections.next() {
 7405            let mut start_row = selection.start.row;
 7406            let mut end_row = selection.end.row;
 7407
 7408            // Skip selections that overlap with a range that has already been rewrapped.
 7409            let selection_range = start_row..end_row;
 7410            if rewrapped_row_ranges
 7411                .iter()
 7412                .any(|range| range.overlaps(&selection_range))
 7413            {
 7414                continue;
 7415            }
 7416
 7417            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 7418
 7419            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 7420                match language_scope.language_name().as_ref() {
 7421                    "Markdown" | "Plain Text" => {
 7422                        should_rewrap = true;
 7423                    }
 7424                    _ => {}
 7425                }
 7426            }
 7427
 7428            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 7429
 7430            // Since not all lines in the selection may be at the same indent
 7431            // level, choose the indent size that is the most common between all
 7432            // of the lines.
 7433            //
 7434            // If there is a tie, we use the deepest indent.
 7435            let (indent_size, indent_end) = {
 7436                let mut indent_size_occurrences = HashMap::default();
 7437                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 7438
 7439                for row in start_row..=end_row {
 7440                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 7441                    rows_by_indent_size.entry(indent).or_default().push(row);
 7442                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 7443                }
 7444
 7445                let indent_size = indent_size_occurrences
 7446                    .into_iter()
 7447                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 7448                    .map(|(indent, _)| indent)
 7449                    .unwrap_or_default();
 7450                let row = rows_by_indent_size[&indent_size][0];
 7451                let indent_end = Point::new(row, indent_size.len);
 7452
 7453                (indent_size, indent_end)
 7454            };
 7455
 7456            let mut line_prefix = indent_size.chars().collect::<String>();
 7457
 7458            if let Some(comment_prefix) =
 7459                buffer
 7460                    .language_scope_at(selection.head())
 7461                    .and_then(|language| {
 7462                        language
 7463                            .line_comment_prefixes()
 7464                            .iter()
 7465                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 7466                            .cloned()
 7467                    })
 7468            {
 7469                line_prefix.push_str(&comment_prefix);
 7470                should_rewrap = true;
 7471            }
 7472
 7473            if !should_rewrap {
 7474                continue;
 7475            }
 7476
 7477            if selection.is_empty() {
 7478                'expand_upwards: while start_row > 0 {
 7479                    let prev_row = start_row - 1;
 7480                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 7481                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 7482                    {
 7483                        start_row = prev_row;
 7484                    } else {
 7485                        break 'expand_upwards;
 7486                    }
 7487                }
 7488
 7489                'expand_downwards: while end_row < buffer.max_point().row {
 7490                    let next_row = end_row + 1;
 7491                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 7492                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 7493                    {
 7494                        end_row = next_row;
 7495                    } else {
 7496                        break 'expand_downwards;
 7497                    }
 7498                }
 7499            }
 7500
 7501            let start = Point::new(start_row, 0);
 7502            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 7503            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 7504            let Some(lines_without_prefixes) = selection_text
 7505                .lines()
 7506                .map(|line| {
 7507                    line.strip_prefix(&line_prefix)
 7508                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 7509                        .ok_or_else(|| {
 7510                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 7511                        })
 7512                })
 7513                .collect::<Result<Vec<_>, _>>()
 7514                .log_err()
 7515            else {
 7516                continue;
 7517            };
 7518
 7519            let wrap_column = buffer
 7520                .settings_at(Point::new(start_row, 0), cx)
 7521                .preferred_line_length as usize;
 7522            let wrapped_text = wrap_with_prefix(
 7523                line_prefix,
 7524                lines_without_prefixes.join(" "),
 7525                wrap_column,
 7526                tab_size,
 7527            );
 7528
 7529            // TODO: should always use char-based diff while still supporting cursor behavior that
 7530            // matches vim.
 7531            let diff = match is_vim_mode {
 7532                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 7533                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 7534            };
 7535            let mut offset = start.to_offset(&buffer);
 7536            let mut moved_since_edit = true;
 7537
 7538            for change in diff.iter_all_changes() {
 7539                let value = change.value();
 7540                match change.tag() {
 7541                    ChangeTag::Equal => {
 7542                        offset += value.len();
 7543                        moved_since_edit = true;
 7544                    }
 7545                    ChangeTag::Delete => {
 7546                        let start = buffer.anchor_after(offset);
 7547                        let end = buffer.anchor_before(offset + value.len());
 7548
 7549                        if moved_since_edit {
 7550                            edits.push((start..end, String::new()));
 7551                        } else {
 7552                            edits.last_mut().unwrap().0.end = end;
 7553                        }
 7554
 7555                        offset += value.len();
 7556                        moved_since_edit = false;
 7557                    }
 7558                    ChangeTag::Insert => {
 7559                        if moved_since_edit {
 7560                            let anchor = buffer.anchor_after(offset);
 7561                            edits.push((anchor..anchor, value.to_string()));
 7562                        } else {
 7563                            edits.last_mut().unwrap().1.push_str(value);
 7564                        }
 7565
 7566                        moved_since_edit = false;
 7567                    }
 7568                }
 7569            }
 7570
 7571            rewrapped_row_ranges.push(start_row..=end_row);
 7572        }
 7573
 7574        self.buffer
 7575            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 7576    }
 7577
 7578    pub fn cut_common(&mut self, window: &mut Window, cx: &mut Context<Self>) -> ClipboardItem {
 7579        let mut text = String::new();
 7580        let buffer = self.buffer.read(cx).snapshot(cx);
 7581        let mut selections = self.selections.all::<Point>(cx);
 7582        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7583        {
 7584            let max_point = buffer.max_point();
 7585            let mut is_first = true;
 7586            for selection in &mut selections {
 7587                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7588                if is_entire_line {
 7589                    selection.start = Point::new(selection.start.row, 0);
 7590                    if !selection.is_empty() && selection.end.column == 0 {
 7591                        selection.end = cmp::min(max_point, selection.end);
 7592                    } else {
 7593                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 7594                    }
 7595                    selection.goal = SelectionGoal::None;
 7596                }
 7597                if is_first {
 7598                    is_first = false;
 7599                } else {
 7600                    text += "\n";
 7601                }
 7602                let mut len = 0;
 7603                for chunk in buffer.text_for_range(selection.start..selection.end) {
 7604                    text.push_str(chunk);
 7605                    len += chunk.len();
 7606                }
 7607                clipboard_selections.push(ClipboardSelection {
 7608                    len,
 7609                    is_entire_line,
 7610                    first_line_indent: buffer
 7611                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 7612                        .len,
 7613                });
 7614            }
 7615        }
 7616
 7617        self.transact(window, cx, |this, window, cx| {
 7618            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7619                s.select(selections);
 7620            });
 7621            this.insert("", window, cx);
 7622        });
 7623        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 7624    }
 7625
 7626    pub fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
 7627        let item = self.cut_common(window, cx);
 7628        cx.write_to_clipboard(item);
 7629    }
 7630
 7631    pub fn kill_ring_cut(&mut self, _: &KillRingCut, window: &mut Window, cx: &mut Context<Self>) {
 7632        self.change_selections(None, window, cx, |s| {
 7633            s.move_with(|snapshot, sel| {
 7634                if sel.is_empty() {
 7635                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 7636                }
 7637            });
 7638        });
 7639        let item = self.cut_common(window, cx);
 7640        cx.set_global(KillRing(item))
 7641    }
 7642
 7643    pub fn kill_ring_yank(
 7644        &mut self,
 7645        _: &KillRingYank,
 7646        window: &mut Window,
 7647        cx: &mut Context<Self>,
 7648    ) {
 7649        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 7650            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 7651                (kill_ring.text().to_string(), kill_ring.metadata_json())
 7652            } else {
 7653                return;
 7654            }
 7655        } else {
 7656            return;
 7657        };
 7658        self.do_paste(&text, metadata, false, window, cx);
 7659    }
 7660
 7661    pub fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
 7662        let selections = self.selections.all::<Point>(cx);
 7663        let buffer = self.buffer.read(cx).read(cx);
 7664        let mut text = String::new();
 7665
 7666        let mut clipboard_selections = Vec::with_capacity(selections.len());
 7667        {
 7668            let max_point = buffer.max_point();
 7669            let mut is_first = true;
 7670            for selection in selections.iter() {
 7671                let mut start = selection.start;
 7672                let mut end = selection.end;
 7673                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 7674                if is_entire_line {
 7675                    start = Point::new(start.row, 0);
 7676                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 7677                }
 7678                if is_first {
 7679                    is_first = false;
 7680                } else {
 7681                    text += "\n";
 7682                }
 7683                let mut len = 0;
 7684                for chunk in buffer.text_for_range(start..end) {
 7685                    text.push_str(chunk);
 7686                    len += chunk.len();
 7687                }
 7688                clipboard_selections.push(ClipboardSelection {
 7689                    len,
 7690                    is_entire_line,
 7691                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 7692                });
 7693            }
 7694        }
 7695
 7696        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 7697            text,
 7698            clipboard_selections,
 7699        ));
 7700    }
 7701
 7702    pub fn do_paste(
 7703        &mut self,
 7704        text: &String,
 7705        clipboard_selections: Option<Vec<ClipboardSelection>>,
 7706        handle_entire_lines: bool,
 7707        window: &mut Window,
 7708        cx: &mut Context<Self>,
 7709    ) {
 7710        if self.read_only(cx) {
 7711            return;
 7712        }
 7713
 7714        let clipboard_text = Cow::Borrowed(text);
 7715
 7716        self.transact(window, cx, |this, window, cx| {
 7717            if let Some(mut clipboard_selections) = clipboard_selections {
 7718                let old_selections = this.selections.all::<usize>(cx);
 7719                let all_selections_were_entire_line =
 7720                    clipboard_selections.iter().all(|s| s.is_entire_line);
 7721                let first_selection_indent_column =
 7722                    clipboard_selections.first().map(|s| s.first_line_indent);
 7723                if clipboard_selections.len() != old_selections.len() {
 7724                    clipboard_selections.drain(..);
 7725                }
 7726                let cursor_offset = this.selections.last::<usize>(cx).head();
 7727                let mut auto_indent_on_paste = true;
 7728
 7729                this.buffer.update(cx, |buffer, cx| {
 7730                    let snapshot = buffer.read(cx);
 7731                    auto_indent_on_paste =
 7732                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 7733
 7734                    let mut start_offset = 0;
 7735                    let mut edits = Vec::new();
 7736                    let mut original_indent_columns = Vec::new();
 7737                    for (ix, selection) in old_selections.iter().enumerate() {
 7738                        let to_insert;
 7739                        let entire_line;
 7740                        let original_indent_column;
 7741                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 7742                            let end_offset = start_offset + clipboard_selection.len;
 7743                            to_insert = &clipboard_text[start_offset..end_offset];
 7744                            entire_line = clipboard_selection.is_entire_line;
 7745                            start_offset = end_offset + 1;
 7746                            original_indent_column = Some(clipboard_selection.first_line_indent);
 7747                        } else {
 7748                            to_insert = clipboard_text.as_str();
 7749                            entire_line = all_selections_were_entire_line;
 7750                            original_indent_column = first_selection_indent_column
 7751                        }
 7752
 7753                        // If the corresponding selection was empty when this slice of the
 7754                        // clipboard text was written, then the entire line containing the
 7755                        // selection was copied. If this selection is also currently empty,
 7756                        // then paste the line before the current line of the buffer.
 7757                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 7758                            let column = selection.start.to_point(&snapshot).column as usize;
 7759                            let line_start = selection.start - column;
 7760                            line_start..line_start
 7761                        } else {
 7762                            selection.range()
 7763                        };
 7764
 7765                        edits.push((range, to_insert));
 7766                        original_indent_columns.extend(original_indent_column);
 7767                    }
 7768                    drop(snapshot);
 7769
 7770                    buffer.edit(
 7771                        edits,
 7772                        if auto_indent_on_paste {
 7773                            Some(AutoindentMode::Block {
 7774                                original_indent_columns,
 7775                            })
 7776                        } else {
 7777                            None
 7778                        },
 7779                        cx,
 7780                    );
 7781                });
 7782
 7783                let selections = this.selections.all::<usize>(cx);
 7784                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7785                    s.select(selections)
 7786                });
 7787            } else {
 7788                this.insert(&clipboard_text, window, cx);
 7789            }
 7790        });
 7791    }
 7792
 7793    pub fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 7794        if let Some(item) = cx.read_from_clipboard() {
 7795            let entries = item.entries();
 7796
 7797            match entries.first() {
 7798                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 7799                // of all the pasted entries.
 7800                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 7801                    .do_paste(
 7802                        clipboard_string.text(),
 7803                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 7804                        true,
 7805                        window,
 7806                        cx,
 7807                    ),
 7808                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, window, cx),
 7809            }
 7810        }
 7811    }
 7812
 7813    pub fn undo(&mut self, _: &Undo, window: &mut Window, cx: &mut Context<Self>) {
 7814        if self.read_only(cx) {
 7815            return;
 7816        }
 7817
 7818        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 7819            if let Some((selections, _)) =
 7820                self.selection_history.transaction(transaction_id).cloned()
 7821            {
 7822                self.change_selections(None, window, cx, |s| {
 7823                    s.select_anchors(selections.to_vec());
 7824                });
 7825            }
 7826            self.request_autoscroll(Autoscroll::fit(), cx);
 7827            self.unmark_text(window, cx);
 7828            self.refresh_inline_completion(true, false, window, cx);
 7829            cx.emit(EditorEvent::Edited { transaction_id });
 7830            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7831        }
 7832    }
 7833
 7834    pub fn redo(&mut self, _: &Redo, window: &mut Window, cx: &mut Context<Self>) {
 7835        if self.read_only(cx) {
 7836            return;
 7837        }
 7838
 7839        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7840            if let Some((_, Some(selections))) =
 7841                self.selection_history.transaction(transaction_id).cloned()
 7842            {
 7843                self.change_selections(None, window, cx, |s| {
 7844                    s.select_anchors(selections.to_vec());
 7845                });
 7846            }
 7847            self.request_autoscroll(Autoscroll::fit(), cx);
 7848            self.unmark_text(window, cx);
 7849            self.refresh_inline_completion(true, false, window, cx);
 7850            cx.emit(EditorEvent::Edited { transaction_id });
 7851        }
 7852    }
 7853
 7854    pub fn finalize_last_transaction(&mut self, cx: &mut Context<Self>) {
 7855        self.buffer
 7856            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7857    }
 7858
 7859    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut Context<Self>) {
 7860        self.buffer
 7861            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7862    }
 7863
 7864    pub fn move_left(&mut self, _: &MoveLeft, window: &mut Window, cx: &mut Context<Self>) {
 7865        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7866            let line_mode = s.line_mode;
 7867            s.move_with(|map, selection| {
 7868                let cursor = if selection.is_empty() && !line_mode {
 7869                    movement::left(map, selection.start)
 7870                } else {
 7871                    selection.start
 7872                };
 7873                selection.collapse_to(cursor, SelectionGoal::None);
 7874            });
 7875        })
 7876    }
 7877
 7878    pub fn select_left(&mut self, _: &SelectLeft, window: &mut Window, cx: &mut Context<Self>) {
 7879        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7880            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7881        })
 7882    }
 7883
 7884    pub fn move_right(&mut self, _: &MoveRight, window: &mut Window, cx: &mut Context<Self>) {
 7885        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7886            let line_mode = s.line_mode;
 7887            s.move_with(|map, selection| {
 7888                let cursor = if selection.is_empty() && !line_mode {
 7889                    movement::right(map, selection.end)
 7890                } else {
 7891                    selection.end
 7892                };
 7893                selection.collapse_to(cursor, SelectionGoal::None)
 7894            });
 7895        })
 7896    }
 7897
 7898    pub fn select_right(&mut self, _: &SelectRight, window: &mut Window, cx: &mut Context<Self>) {
 7899        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7900            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7901        })
 7902    }
 7903
 7904    pub fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 7905        if self.take_rename(true, window, cx).is_some() {
 7906            return;
 7907        }
 7908
 7909        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7910            cx.propagate();
 7911            return;
 7912        }
 7913
 7914        let text_layout_details = &self.text_layout_details(window);
 7915        let selection_count = self.selections.count();
 7916        let first_selection = self.selections.first_anchor();
 7917
 7918        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7919            let line_mode = s.line_mode;
 7920            s.move_with(|map, selection| {
 7921                if !selection.is_empty() && !line_mode {
 7922                    selection.goal = SelectionGoal::None;
 7923                }
 7924                let (cursor, goal) = movement::up(
 7925                    map,
 7926                    selection.start,
 7927                    selection.goal,
 7928                    false,
 7929                    text_layout_details,
 7930                );
 7931                selection.collapse_to(cursor, goal);
 7932            });
 7933        });
 7934
 7935        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7936        {
 7937            cx.propagate();
 7938        }
 7939    }
 7940
 7941    pub fn move_up_by_lines(
 7942        &mut self,
 7943        action: &MoveUpByLines,
 7944        window: &mut Window,
 7945        cx: &mut Context<Self>,
 7946    ) {
 7947        if self.take_rename(true, window, cx).is_some() {
 7948            return;
 7949        }
 7950
 7951        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7952            cx.propagate();
 7953            return;
 7954        }
 7955
 7956        let text_layout_details = &self.text_layout_details(window);
 7957
 7958        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7959            let line_mode = s.line_mode;
 7960            s.move_with(|map, selection| {
 7961                if !selection.is_empty() && !line_mode {
 7962                    selection.goal = SelectionGoal::None;
 7963                }
 7964                let (cursor, goal) = movement::up_by_rows(
 7965                    map,
 7966                    selection.start,
 7967                    action.lines,
 7968                    selection.goal,
 7969                    false,
 7970                    text_layout_details,
 7971                );
 7972                selection.collapse_to(cursor, goal);
 7973            });
 7974        })
 7975    }
 7976
 7977    pub fn move_down_by_lines(
 7978        &mut self,
 7979        action: &MoveDownByLines,
 7980        window: &mut Window,
 7981        cx: &mut Context<Self>,
 7982    ) {
 7983        if self.take_rename(true, window, cx).is_some() {
 7984            return;
 7985        }
 7986
 7987        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7988            cx.propagate();
 7989            return;
 7990        }
 7991
 7992        let text_layout_details = &self.text_layout_details(window);
 7993
 7994        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 7995            let line_mode = s.line_mode;
 7996            s.move_with(|map, selection| {
 7997                if !selection.is_empty() && !line_mode {
 7998                    selection.goal = SelectionGoal::None;
 7999                }
 8000                let (cursor, goal) = movement::down_by_rows(
 8001                    map,
 8002                    selection.start,
 8003                    action.lines,
 8004                    selection.goal,
 8005                    false,
 8006                    text_layout_details,
 8007                );
 8008                selection.collapse_to(cursor, goal);
 8009            });
 8010        })
 8011    }
 8012
 8013    pub fn select_down_by_lines(
 8014        &mut self,
 8015        action: &SelectDownByLines,
 8016        window: &mut Window,
 8017        cx: &mut Context<Self>,
 8018    ) {
 8019        let text_layout_details = &self.text_layout_details(window);
 8020        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8021            s.move_heads_with(|map, head, goal| {
 8022                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8023            })
 8024        })
 8025    }
 8026
 8027    pub fn select_up_by_lines(
 8028        &mut self,
 8029        action: &SelectUpByLines,
 8030        window: &mut Window,
 8031        cx: &mut Context<Self>,
 8032    ) {
 8033        let text_layout_details = &self.text_layout_details(window);
 8034        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8035            s.move_heads_with(|map, head, goal| {
 8036                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 8037            })
 8038        })
 8039    }
 8040
 8041    pub fn select_page_up(
 8042        &mut self,
 8043        _: &SelectPageUp,
 8044        window: &mut Window,
 8045        cx: &mut Context<Self>,
 8046    ) {
 8047        let Some(row_count) = self.visible_row_count() else {
 8048            return;
 8049        };
 8050
 8051        let text_layout_details = &self.text_layout_details(window);
 8052
 8053        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8054            s.move_heads_with(|map, head, goal| {
 8055                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 8056            })
 8057        })
 8058    }
 8059
 8060    pub fn move_page_up(
 8061        &mut self,
 8062        action: &MovePageUp,
 8063        window: &mut Window,
 8064        cx: &mut Context<Self>,
 8065    ) {
 8066        if self.take_rename(true, window, cx).is_some() {
 8067            return;
 8068        }
 8069
 8070        if self
 8071            .context_menu
 8072            .borrow_mut()
 8073            .as_mut()
 8074            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 8075            .unwrap_or(false)
 8076        {
 8077            return;
 8078        }
 8079
 8080        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8081            cx.propagate();
 8082            return;
 8083        }
 8084
 8085        let Some(row_count) = self.visible_row_count() else {
 8086            return;
 8087        };
 8088
 8089        let autoscroll = if action.center_cursor {
 8090            Autoscroll::center()
 8091        } else {
 8092            Autoscroll::fit()
 8093        };
 8094
 8095        let text_layout_details = &self.text_layout_details(window);
 8096
 8097        self.change_selections(Some(autoscroll), window, cx, |s| {
 8098            let line_mode = s.line_mode;
 8099            s.move_with(|map, selection| {
 8100                if !selection.is_empty() && !line_mode {
 8101                    selection.goal = SelectionGoal::None;
 8102                }
 8103                let (cursor, goal) = movement::up_by_rows(
 8104                    map,
 8105                    selection.end,
 8106                    row_count,
 8107                    selection.goal,
 8108                    false,
 8109                    text_layout_details,
 8110                );
 8111                selection.collapse_to(cursor, goal);
 8112            });
 8113        });
 8114    }
 8115
 8116    pub fn select_up(&mut self, _: &SelectUp, window: &mut Window, cx: &mut Context<Self>) {
 8117        let text_layout_details = &self.text_layout_details(window);
 8118        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8119            s.move_heads_with(|map, head, goal| {
 8120                movement::up(map, head, goal, false, text_layout_details)
 8121            })
 8122        })
 8123    }
 8124
 8125    pub fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 8126        self.take_rename(true, window, cx);
 8127
 8128        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8129            cx.propagate();
 8130            return;
 8131        }
 8132
 8133        let text_layout_details = &self.text_layout_details(window);
 8134        let selection_count = self.selections.count();
 8135        let first_selection = self.selections.first_anchor();
 8136
 8137        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8138            let line_mode = s.line_mode;
 8139            s.move_with(|map, selection| {
 8140                if !selection.is_empty() && !line_mode {
 8141                    selection.goal = SelectionGoal::None;
 8142                }
 8143                let (cursor, goal) = movement::down(
 8144                    map,
 8145                    selection.end,
 8146                    selection.goal,
 8147                    false,
 8148                    text_layout_details,
 8149                );
 8150                selection.collapse_to(cursor, goal);
 8151            });
 8152        });
 8153
 8154        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 8155        {
 8156            cx.propagate();
 8157        }
 8158    }
 8159
 8160    pub fn select_page_down(
 8161        &mut self,
 8162        _: &SelectPageDown,
 8163        window: &mut Window,
 8164        cx: &mut Context<Self>,
 8165    ) {
 8166        let Some(row_count) = self.visible_row_count() else {
 8167            return;
 8168        };
 8169
 8170        let text_layout_details = &self.text_layout_details(window);
 8171
 8172        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8173            s.move_heads_with(|map, head, goal| {
 8174                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 8175            })
 8176        })
 8177    }
 8178
 8179    pub fn move_page_down(
 8180        &mut self,
 8181        action: &MovePageDown,
 8182        window: &mut Window,
 8183        cx: &mut Context<Self>,
 8184    ) {
 8185        if self.take_rename(true, window, cx).is_some() {
 8186            return;
 8187        }
 8188
 8189        if self
 8190            .context_menu
 8191            .borrow_mut()
 8192            .as_mut()
 8193            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 8194            .unwrap_or(false)
 8195        {
 8196            return;
 8197        }
 8198
 8199        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8200            cx.propagate();
 8201            return;
 8202        }
 8203
 8204        let Some(row_count) = self.visible_row_count() else {
 8205            return;
 8206        };
 8207
 8208        let autoscroll = if action.center_cursor {
 8209            Autoscroll::center()
 8210        } else {
 8211            Autoscroll::fit()
 8212        };
 8213
 8214        let text_layout_details = &self.text_layout_details(window);
 8215        self.change_selections(Some(autoscroll), window, cx, |s| {
 8216            let line_mode = s.line_mode;
 8217            s.move_with(|map, selection| {
 8218                if !selection.is_empty() && !line_mode {
 8219                    selection.goal = SelectionGoal::None;
 8220                }
 8221                let (cursor, goal) = movement::down_by_rows(
 8222                    map,
 8223                    selection.end,
 8224                    row_count,
 8225                    selection.goal,
 8226                    false,
 8227                    text_layout_details,
 8228                );
 8229                selection.collapse_to(cursor, goal);
 8230            });
 8231        });
 8232    }
 8233
 8234    pub fn select_down(&mut self, _: &SelectDown, window: &mut Window, cx: &mut Context<Self>) {
 8235        let text_layout_details = &self.text_layout_details(window);
 8236        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8237            s.move_heads_with(|map, head, goal| {
 8238                movement::down(map, head, goal, false, text_layout_details)
 8239            })
 8240        });
 8241    }
 8242
 8243    pub fn context_menu_first(
 8244        &mut self,
 8245        _: &ContextMenuFirst,
 8246        _window: &mut Window,
 8247        cx: &mut Context<Self>,
 8248    ) {
 8249        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8250            context_menu.select_first(self.completion_provider.as_deref(), cx);
 8251        }
 8252    }
 8253
 8254    pub fn context_menu_prev(
 8255        &mut self,
 8256        _: &ContextMenuPrev,
 8257        _window: &mut Window,
 8258        cx: &mut Context<Self>,
 8259    ) {
 8260        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8261            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 8262        }
 8263    }
 8264
 8265    pub fn context_menu_next(
 8266        &mut self,
 8267        _: &ContextMenuNext,
 8268        _window: &mut Window,
 8269        cx: &mut Context<Self>,
 8270    ) {
 8271        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8272            context_menu.select_next(self.completion_provider.as_deref(), cx);
 8273        }
 8274    }
 8275
 8276    pub fn context_menu_last(
 8277        &mut self,
 8278        _: &ContextMenuLast,
 8279        _window: &mut Window,
 8280        cx: &mut Context<Self>,
 8281    ) {
 8282        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 8283            context_menu.select_last(self.completion_provider.as_deref(), cx);
 8284        }
 8285    }
 8286
 8287    pub fn move_to_previous_word_start(
 8288        &mut self,
 8289        _: &MoveToPreviousWordStart,
 8290        window: &mut Window,
 8291        cx: &mut Context<Self>,
 8292    ) {
 8293        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8294            s.move_cursors_with(|map, head, _| {
 8295                (
 8296                    movement::previous_word_start(map, head),
 8297                    SelectionGoal::None,
 8298                )
 8299            });
 8300        })
 8301    }
 8302
 8303    pub fn move_to_previous_subword_start(
 8304        &mut self,
 8305        _: &MoveToPreviousSubwordStart,
 8306        window: &mut Window,
 8307        cx: &mut Context<Self>,
 8308    ) {
 8309        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8310            s.move_cursors_with(|map, head, _| {
 8311                (
 8312                    movement::previous_subword_start(map, head),
 8313                    SelectionGoal::None,
 8314                )
 8315            });
 8316        })
 8317    }
 8318
 8319    pub fn select_to_previous_word_start(
 8320        &mut self,
 8321        _: &SelectToPreviousWordStart,
 8322        window: &mut Window,
 8323        cx: &mut Context<Self>,
 8324    ) {
 8325        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8326            s.move_heads_with(|map, head, _| {
 8327                (
 8328                    movement::previous_word_start(map, head),
 8329                    SelectionGoal::None,
 8330                )
 8331            });
 8332        })
 8333    }
 8334
 8335    pub fn select_to_previous_subword_start(
 8336        &mut self,
 8337        _: &SelectToPreviousSubwordStart,
 8338        window: &mut Window,
 8339        cx: &mut Context<Self>,
 8340    ) {
 8341        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8342            s.move_heads_with(|map, head, _| {
 8343                (
 8344                    movement::previous_subword_start(map, head),
 8345                    SelectionGoal::None,
 8346                )
 8347            });
 8348        })
 8349    }
 8350
 8351    pub fn delete_to_previous_word_start(
 8352        &mut self,
 8353        action: &DeleteToPreviousWordStart,
 8354        window: &mut Window,
 8355        cx: &mut Context<Self>,
 8356    ) {
 8357        self.transact(window, cx, |this, window, cx| {
 8358            this.select_autoclose_pair(window, cx);
 8359            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8360                let line_mode = s.line_mode;
 8361                s.move_with(|map, selection| {
 8362                    if selection.is_empty() && !line_mode {
 8363                        let cursor = if action.ignore_newlines {
 8364                            movement::previous_word_start(map, selection.head())
 8365                        } else {
 8366                            movement::previous_word_start_or_newline(map, selection.head())
 8367                        };
 8368                        selection.set_head(cursor, SelectionGoal::None);
 8369                    }
 8370                });
 8371            });
 8372            this.insert("", window, cx);
 8373        });
 8374    }
 8375
 8376    pub fn delete_to_previous_subword_start(
 8377        &mut self,
 8378        _: &DeleteToPreviousSubwordStart,
 8379        window: &mut Window,
 8380        cx: &mut Context<Self>,
 8381    ) {
 8382        self.transact(window, cx, |this, window, cx| {
 8383            this.select_autoclose_pair(window, cx);
 8384            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8385                let line_mode = s.line_mode;
 8386                s.move_with(|map, selection| {
 8387                    if selection.is_empty() && !line_mode {
 8388                        let cursor = movement::previous_subword_start(map, selection.head());
 8389                        selection.set_head(cursor, SelectionGoal::None);
 8390                    }
 8391                });
 8392            });
 8393            this.insert("", window, cx);
 8394        });
 8395    }
 8396
 8397    pub fn move_to_next_word_end(
 8398        &mut self,
 8399        _: &MoveToNextWordEnd,
 8400        window: &mut Window,
 8401        cx: &mut Context<Self>,
 8402    ) {
 8403        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8404            s.move_cursors_with(|map, head, _| {
 8405                (movement::next_word_end(map, head), SelectionGoal::None)
 8406            });
 8407        })
 8408    }
 8409
 8410    pub fn move_to_next_subword_end(
 8411        &mut self,
 8412        _: &MoveToNextSubwordEnd,
 8413        window: &mut Window,
 8414        cx: &mut Context<Self>,
 8415    ) {
 8416        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8417            s.move_cursors_with(|map, head, _| {
 8418                (movement::next_subword_end(map, head), SelectionGoal::None)
 8419            });
 8420        })
 8421    }
 8422
 8423    pub fn select_to_next_word_end(
 8424        &mut self,
 8425        _: &SelectToNextWordEnd,
 8426        window: &mut Window,
 8427        cx: &mut Context<Self>,
 8428    ) {
 8429        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8430            s.move_heads_with(|map, head, _| {
 8431                (movement::next_word_end(map, head), SelectionGoal::None)
 8432            });
 8433        })
 8434    }
 8435
 8436    pub fn select_to_next_subword_end(
 8437        &mut self,
 8438        _: &SelectToNextSubwordEnd,
 8439        window: &mut Window,
 8440        cx: &mut Context<Self>,
 8441    ) {
 8442        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8443            s.move_heads_with(|map, head, _| {
 8444                (movement::next_subword_end(map, head), SelectionGoal::None)
 8445            });
 8446        })
 8447    }
 8448
 8449    pub fn delete_to_next_word_end(
 8450        &mut self,
 8451        action: &DeleteToNextWordEnd,
 8452        window: &mut Window,
 8453        cx: &mut Context<Self>,
 8454    ) {
 8455        self.transact(window, cx, |this, window, cx| {
 8456            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8457                let line_mode = s.line_mode;
 8458                s.move_with(|map, selection| {
 8459                    if selection.is_empty() && !line_mode {
 8460                        let cursor = if action.ignore_newlines {
 8461                            movement::next_word_end(map, selection.head())
 8462                        } else {
 8463                            movement::next_word_end_or_newline(map, selection.head())
 8464                        };
 8465                        selection.set_head(cursor, SelectionGoal::None);
 8466                    }
 8467                });
 8468            });
 8469            this.insert("", window, cx);
 8470        });
 8471    }
 8472
 8473    pub fn delete_to_next_subword_end(
 8474        &mut self,
 8475        _: &DeleteToNextSubwordEnd,
 8476        window: &mut Window,
 8477        cx: &mut Context<Self>,
 8478    ) {
 8479        self.transact(window, cx, |this, window, cx| {
 8480            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8481                s.move_with(|map, selection| {
 8482                    if selection.is_empty() {
 8483                        let cursor = movement::next_subword_end(map, selection.head());
 8484                        selection.set_head(cursor, SelectionGoal::None);
 8485                    }
 8486                });
 8487            });
 8488            this.insert("", window, cx);
 8489        });
 8490    }
 8491
 8492    pub fn move_to_beginning_of_line(
 8493        &mut self,
 8494        action: &MoveToBeginningOfLine,
 8495        window: &mut Window,
 8496        cx: &mut Context<Self>,
 8497    ) {
 8498        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8499            s.move_cursors_with(|map, head, _| {
 8500                (
 8501                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8502                    SelectionGoal::None,
 8503                )
 8504            });
 8505        })
 8506    }
 8507
 8508    pub fn select_to_beginning_of_line(
 8509        &mut self,
 8510        action: &SelectToBeginningOfLine,
 8511        window: &mut Window,
 8512        cx: &mut Context<Self>,
 8513    ) {
 8514        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8515            s.move_heads_with(|map, head, _| {
 8516                (
 8517                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 8518                    SelectionGoal::None,
 8519                )
 8520            });
 8521        });
 8522    }
 8523
 8524    pub fn delete_to_beginning_of_line(
 8525        &mut self,
 8526        _: &DeleteToBeginningOfLine,
 8527        window: &mut Window,
 8528        cx: &mut Context<Self>,
 8529    ) {
 8530        self.transact(window, cx, |this, window, cx| {
 8531            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8532                s.move_with(|_, selection| {
 8533                    selection.reversed = true;
 8534                });
 8535            });
 8536
 8537            this.select_to_beginning_of_line(
 8538                &SelectToBeginningOfLine {
 8539                    stop_at_soft_wraps: false,
 8540                },
 8541                window,
 8542                cx,
 8543            );
 8544            this.backspace(&Backspace, window, cx);
 8545        });
 8546    }
 8547
 8548    pub fn move_to_end_of_line(
 8549        &mut self,
 8550        action: &MoveToEndOfLine,
 8551        window: &mut Window,
 8552        cx: &mut Context<Self>,
 8553    ) {
 8554        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8555            s.move_cursors_with(|map, head, _| {
 8556                (
 8557                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8558                    SelectionGoal::None,
 8559                )
 8560            });
 8561        })
 8562    }
 8563
 8564    pub fn select_to_end_of_line(
 8565        &mut self,
 8566        action: &SelectToEndOfLine,
 8567        window: &mut Window,
 8568        cx: &mut Context<Self>,
 8569    ) {
 8570        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8571            s.move_heads_with(|map, head, _| {
 8572                (
 8573                    movement::line_end(map, head, action.stop_at_soft_wraps),
 8574                    SelectionGoal::None,
 8575                )
 8576            });
 8577        })
 8578    }
 8579
 8580    pub fn delete_to_end_of_line(
 8581        &mut self,
 8582        _: &DeleteToEndOfLine,
 8583        window: &mut Window,
 8584        cx: &mut Context<Self>,
 8585    ) {
 8586        self.transact(window, cx, |this, window, cx| {
 8587            this.select_to_end_of_line(
 8588                &SelectToEndOfLine {
 8589                    stop_at_soft_wraps: false,
 8590                },
 8591                window,
 8592                cx,
 8593            );
 8594            this.delete(&Delete, window, cx);
 8595        });
 8596    }
 8597
 8598    pub fn cut_to_end_of_line(
 8599        &mut self,
 8600        _: &CutToEndOfLine,
 8601        window: &mut Window,
 8602        cx: &mut Context<Self>,
 8603    ) {
 8604        self.transact(window, cx, |this, window, cx| {
 8605            this.select_to_end_of_line(
 8606                &SelectToEndOfLine {
 8607                    stop_at_soft_wraps: false,
 8608                },
 8609                window,
 8610                cx,
 8611            );
 8612            this.cut(&Cut, window, cx);
 8613        });
 8614    }
 8615
 8616    pub fn move_to_start_of_paragraph(
 8617        &mut self,
 8618        _: &MoveToStartOfParagraph,
 8619        window: &mut Window,
 8620        cx: &mut Context<Self>,
 8621    ) {
 8622        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8623            cx.propagate();
 8624            return;
 8625        }
 8626
 8627        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8628            s.move_with(|map, selection| {
 8629                selection.collapse_to(
 8630                    movement::start_of_paragraph(map, selection.head(), 1),
 8631                    SelectionGoal::None,
 8632                )
 8633            });
 8634        })
 8635    }
 8636
 8637    pub fn move_to_end_of_paragraph(
 8638        &mut self,
 8639        _: &MoveToEndOfParagraph,
 8640        window: &mut Window,
 8641        cx: &mut Context<Self>,
 8642    ) {
 8643        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8644            cx.propagate();
 8645            return;
 8646        }
 8647
 8648        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8649            s.move_with(|map, selection| {
 8650                selection.collapse_to(
 8651                    movement::end_of_paragraph(map, selection.head(), 1),
 8652                    SelectionGoal::None,
 8653                )
 8654            });
 8655        })
 8656    }
 8657
 8658    pub fn select_to_start_of_paragraph(
 8659        &mut self,
 8660        _: &SelectToStartOfParagraph,
 8661        window: &mut Window,
 8662        cx: &mut Context<Self>,
 8663    ) {
 8664        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8665            cx.propagate();
 8666            return;
 8667        }
 8668
 8669        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8670            s.move_heads_with(|map, head, _| {
 8671                (
 8672                    movement::start_of_paragraph(map, head, 1),
 8673                    SelectionGoal::None,
 8674                )
 8675            });
 8676        })
 8677    }
 8678
 8679    pub fn select_to_end_of_paragraph(
 8680        &mut self,
 8681        _: &SelectToEndOfParagraph,
 8682        window: &mut Window,
 8683        cx: &mut Context<Self>,
 8684    ) {
 8685        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8686            cx.propagate();
 8687            return;
 8688        }
 8689
 8690        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8691            s.move_heads_with(|map, head, _| {
 8692                (
 8693                    movement::end_of_paragraph(map, head, 1),
 8694                    SelectionGoal::None,
 8695                )
 8696            });
 8697        })
 8698    }
 8699
 8700    pub fn move_to_beginning(
 8701        &mut self,
 8702        _: &MoveToBeginning,
 8703        window: &mut Window,
 8704        cx: &mut Context<Self>,
 8705    ) {
 8706        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8707            cx.propagate();
 8708            return;
 8709        }
 8710
 8711        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8712            s.select_ranges(vec![0..0]);
 8713        });
 8714    }
 8715
 8716    pub fn select_to_beginning(
 8717        &mut self,
 8718        _: &SelectToBeginning,
 8719        window: &mut Window,
 8720        cx: &mut Context<Self>,
 8721    ) {
 8722        let mut selection = self.selections.last::<Point>(cx);
 8723        selection.set_head(Point::zero(), SelectionGoal::None);
 8724
 8725        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8726            s.select(vec![selection]);
 8727        });
 8728    }
 8729
 8730    pub fn move_to_end(&mut self, _: &MoveToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8731        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 8732            cx.propagate();
 8733            return;
 8734        }
 8735
 8736        let cursor = self.buffer.read(cx).read(cx).len();
 8737        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8738            s.select_ranges(vec![cursor..cursor])
 8739        });
 8740    }
 8741
 8742    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 8743        self.nav_history = nav_history;
 8744    }
 8745
 8746    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 8747        self.nav_history.as_ref()
 8748    }
 8749
 8750    fn push_to_nav_history(
 8751        &mut self,
 8752        cursor_anchor: Anchor,
 8753        new_position: Option<Point>,
 8754        cx: &mut Context<Self>,
 8755    ) {
 8756        if let Some(nav_history) = self.nav_history.as_mut() {
 8757            let buffer = self.buffer.read(cx).read(cx);
 8758            let cursor_position = cursor_anchor.to_point(&buffer);
 8759            let scroll_state = self.scroll_manager.anchor();
 8760            let scroll_top_row = scroll_state.top_row(&buffer);
 8761            drop(buffer);
 8762
 8763            if let Some(new_position) = new_position {
 8764                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 8765                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 8766                    return;
 8767                }
 8768            }
 8769
 8770            nav_history.push(
 8771                Some(NavigationData {
 8772                    cursor_anchor,
 8773                    cursor_position,
 8774                    scroll_anchor: scroll_state,
 8775                    scroll_top_row,
 8776                }),
 8777                cx,
 8778            );
 8779        }
 8780    }
 8781
 8782    pub fn select_to_end(&mut self, _: &SelectToEnd, window: &mut Window, cx: &mut Context<Self>) {
 8783        let buffer = self.buffer.read(cx).snapshot(cx);
 8784        let mut selection = self.selections.first::<usize>(cx);
 8785        selection.set_head(buffer.len(), SelectionGoal::None);
 8786        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8787            s.select(vec![selection]);
 8788        });
 8789    }
 8790
 8791    pub fn select_all(&mut self, _: &SelectAll, window: &mut Window, cx: &mut Context<Self>) {
 8792        let end = self.buffer.read(cx).read(cx).len();
 8793        self.change_selections(None, window, cx, |s| {
 8794            s.select_ranges(vec![0..end]);
 8795        });
 8796    }
 8797
 8798    pub fn select_line(&mut self, _: &SelectLine, window: &mut Window, cx: &mut Context<Self>) {
 8799        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8800        let mut selections = self.selections.all::<Point>(cx);
 8801        let max_point = display_map.buffer_snapshot.max_point();
 8802        for selection in &mut selections {
 8803            let rows = selection.spanned_rows(true, &display_map);
 8804            selection.start = Point::new(rows.start.0, 0);
 8805            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 8806            selection.reversed = false;
 8807        }
 8808        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8809            s.select(selections);
 8810        });
 8811    }
 8812
 8813    pub fn split_selection_into_lines(
 8814        &mut self,
 8815        _: &SplitSelectionIntoLines,
 8816        window: &mut Window,
 8817        cx: &mut Context<Self>,
 8818    ) {
 8819        let mut to_unfold = Vec::new();
 8820        let mut new_selection_ranges = Vec::new();
 8821        {
 8822            let selections = self.selections.all::<Point>(cx);
 8823            let buffer = self.buffer.read(cx).read(cx);
 8824            for selection in selections {
 8825                for row in selection.start.row..selection.end.row {
 8826                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 8827                    new_selection_ranges.push(cursor..cursor);
 8828                }
 8829                new_selection_ranges.push(selection.end..selection.end);
 8830                to_unfold.push(selection.start..selection.end);
 8831            }
 8832        }
 8833        self.unfold_ranges(&to_unfold, true, true, cx);
 8834        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8835            s.select_ranges(new_selection_ranges);
 8836        });
 8837    }
 8838
 8839    pub fn add_selection_above(
 8840        &mut self,
 8841        _: &AddSelectionAbove,
 8842        window: &mut Window,
 8843        cx: &mut Context<Self>,
 8844    ) {
 8845        self.add_selection(true, window, cx);
 8846    }
 8847
 8848    pub fn add_selection_below(
 8849        &mut self,
 8850        _: &AddSelectionBelow,
 8851        window: &mut Window,
 8852        cx: &mut Context<Self>,
 8853    ) {
 8854        self.add_selection(false, window, cx);
 8855    }
 8856
 8857    fn add_selection(&mut self, above: bool, window: &mut Window, cx: &mut Context<Self>) {
 8858        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8859        let mut selections = self.selections.all::<Point>(cx);
 8860        let text_layout_details = self.text_layout_details(window);
 8861        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 8862            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 8863            let range = oldest_selection.display_range(&display_map).sorted();
 8864
 8865            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 8866            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 8867            let positions = start_x.min(end_x)..start_x.max(end_x);
 8868
 8869            selections.clear();
 8870            let mut stack = Vec::new();
 8871            for row in range.start.row().0..=range.end.row().0 {
 8872                if let Some(selection) = self.selections.build_columnar_selection(
 8873                    &display_map,
 8874                    DisplayRow(row),
 8875                    &positions,
 8876                    oldest_selection.reversed,
 8877                    &text_layout_details,
 8878                ) {
 8879                    stack.push(selection.id);
 8880                    selections.push(selection);
 8881                }
 8882            }
 8883
 8884            if above {
 8885                stack.reverse();
 8886            }
 8887
 8888            AddSelectionsState { above, stack }
 8889        });
 8890
 8891        let last_added_selection = *state.stack.last().unwrap();
 8892        let mut new_selections = Vec::new();
 8893        if above == state.above {
 8894            let end_row = if above {
 8895                DisplayRow(0)
 8896            } else {
 8897                display_map.max_point().row()
 8898            };
 8899
 8900            'outer: for selection in selections {
 8901                if selection.id == last_added_selection {
 8902                    let range = selection.display_range(&display_map).sorted();
 8903                    debug_assert_eq!(range.start.row(), range.end.row());
 8904                    let mut row = range.start.row();
 8905                    let positions =
 8906                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 8907                            px(start)..px(end)
 8908                        } else {
 8909                            let start_x =
 8910                                display_map.x_for_display_point(range.start, &text_layout_details);
 8911                            let end_x =
 8912                                display_map.x_for_display_point(range.end, &text_layout_details);
 8913                            start_x.min(end_x)..start_x.max(end_x)
 8914                        };
 8915
 8916                    while row != end_row {
 8917                        if above {
 8918                            row.0 -= 1;
 8919                        } else {
 8920                            row.0 += 1;
 8921                        }
 8922
 8923                        if let Some(new_selection) = self.selections.build_columnar_selection(
 8924                            &display_map,
 8925                            row,
 8926                            &positions,
 8927                            selection.reversed,
 8928                            &text_layout_details,
 8929                        ) {
 8930                            state.stack.push(new_selection.id);
 8931                            if above {
 8932                                new_selections.push(new_selection);
 8933                                new_selections.push(selection);
 8934                            } else {
 8935                                new_selections.push(selection);
 8936                                new_selections.push(new_selection);
 8937                            }
 8938
 8939                            continue 'outer;
 8940                        }
 8941                    }
 8942                }
 8943
 8944                new_selections.push(selection);
 8945            }
 8946        } else {
 8947            new_selections = selections;
 8948            new_selections.retain(|s| s.id != last_added_selection);
 8949            state.stack.pop();
 8950        }
 8951
 8952        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 8953            s.select(new_selections);
 8954        });
 8955        if state.stack.len() > 1 {
 8956            self.add_selections_state = Some(state);
 8957        }
 8958    }
 8959
 8960    pub fn select_next_match_internal(
 8961        &mut self,
 8962        display_map: &DisplaySnapshot,
 8963        replace_newest: bool,
 8964        autoscroll: Option<Autoscroll>,
 8965        window: &mut Window,
 8966        cx: &mut Context<Self>,
 8967    ) -> Result<()> {
 8968        fn select_next_match_ranges(
 8969            this: &mut Editor,
 8970            range: Range<usize>,
 8971            replace_newest: bool,
 8972            auto_scroll: Option<Autoscroll>,
 8973            window: &mut Window,
 8974            cx: &mut Context<Editor>,
 8975        ) {
 8976            this.unfold_ranges(&[range.clone()], false, true, cx);
 8977            this.change_selections(auto_scroll, window, cx, |s| {
 8978                if replace_newest {
 8979                    s.delete(s.newest_anchor().id);
 8980                }
 8981                s.insert_range(range.clone());
 8982            });
 8983        }
 8984
 8985        let buffer = &display_map.buffer_snapshot;
 8986        let mut selections = self.selections.all::<usize>(cx);
 8987        if let Some(mut select_next_state) = self.select_next_state.take() {
 8988            let query = &select_next_state.query;
 8989            if !select_next_state.done {
 8990                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8991                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8992                let mut next_selected_range = None;
 8993
 8994                let bytes_after_last_selection =
 8995                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8996                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8997                let query_matches = query
 8998                    .stream_find_iter(bytes_after_last_selection)
 8999                    .map(|result| (last_selection.end, result))
 9000                    .chain(
 9001                        query
 9002                            .stream_find_iter(bytes_before_first_selection)
 9003                            .map(|result| (0, result)),
 9004                    );
 9005
 9006                for (start_offset, query_match) in query_matches {
 9007                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9008                    let offset_range =
 9009                        start_offset + query_match.start()..start_offset + query_match.end();
 9010                    let display_range = offset_range.start.to_display_point(display_map)
 9011                        ..offset_range.end.to_display_point(display_map);
 9012
 9013                    if !select_next_state.wordwise
 9014                        || (!movement::is_inside_word(display_map, display_range.start)
 9015                            && !movement::is_inside_word(display_map, display_range.end))
 9016                    {
 9017                        // TODO: This is n^2, because we might check all the selections
 9018                        if !selections
 9019                            .iter()
 9020                            .any(|selection| selection.range().overlaps(&offset_range))
 9021                        {
 9022                            next_selected_range = Some(offset_range);
 9023                            break;
 9024                        }
 9025                    }
 9026                }
 9027
 9028                if let Some(next_selected_range) = next_selected_range {
 9029                    select_next_match_ranges(
 9030                        self,
 9031                        next_selected_range,
 9032                        replace_newest,
 9033                        autoscroll,
 9034                        window,
 9035                        cx,
 9036                    );
 9037                } else {
 9038                    select_next_state.done = true;
 9039                }
 9040            }
 9041
 9042            self.select_next_state = Some(select_next_state);
 9043        } else {
 9044            let mut only_carets = true;
 9045            let mut same_text_selected = true;
 9046            let mut selected_text = None;
 9047
 9048            let mut selections_iter = selections.iter().peekable();
 9049            while let Some(selection) = selections_iter.next() {
 9050                if selection.start != selection.end {
 9051                    only_carets = false;
 9052                }
 9053
 9054                if same_text_selected {
 9055                    if selected_text.is_none() {
 9056                        selected_text =
 9057                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9058                    }
 9059
 9060                    if let Some(next_selection) = selections_iter.peek() {
 9061                        if next_selection.range().len() == selection.range().len() {
 9062                            let next_selected_text = buffer
 9063                                .text_for_range(next_selection.range())
 9064                                .collect::<String>();
 9065                            if Some(next_selected_text) != selected_text {
 9066                                same_text_selected = false;
 9067                                selected_text = None;
 9068                            }
 9069                        } else {
 9070                            same_text_selected = false;
 9071                            selected_text = None;
 9072                        }
 9073                    }
 9074                }
 9075            }
 9076
 9077            if only_carets {
 9078                for selection in &mut selections {
 9079                    let word_range = movement::surrounding_word(
 9080                        display_map,
 9081                        selection.start.to_display_point(display_map),
 9082                    );
 9083                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 9084                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 9085                    selection.goal = SelectionGoal::None;
 9086                    selection.reversed = false;
 9087                    select_next_match_ranges(
 9088                        self,
 9089                        selection.start..selection.end,
 9090                        replace_newest,
 9091                        autoscroll,
 9092                        window,
 9093                        cx,
 9094                    );
 9095                }
 9096
 9097                if selections.len() == 1 {
 9098                    let selection = selections
 9099                        .last()
 9100                        .expect("ensured that there's only one selection");
 9101                    let query = buffer
 9102                        .text_for_range(selection.start..selection.end)
 9103                        .collect::<String>();
 9104                    let is_empty = query.is_empty();
 9105                    let select_state = SelectNextState {
 9106                        query: AhoCorasick::new(&[query])?,
 9107                        wordwise: true,
 9108                        done: is_empty,
 9109                    };
 9110                    self.select_next_state = Some(select_state);
 9111                } else {
 9112                    self.select_next_state = None;
 9113                }
 9114            } else if let Some(selected_text) = selected_text {
 9115                self.select_next_state = Some(SelectNextState {
 9116                    query: AhoCorasick::new(&[selected_text])?,
 9117                    wordwise: false,
 9118                    done: false,
 9119                });
 9120                self.select_next_match_internal(
 9121                    display_map,
 9122                    replace_newest,
 9123                    autoscroll,
 9124                    window,
 9125                    cx,
 9126                )?;
 9127            }
 9128        }
 9129        Ok(())
 9130    }
 9131
 9132    pub fn select_all_matches(
 9133        &mut self,
 9134        _action: &SelectAllMatches,
 9135        window: &mut Window,
 9136        cx: &mut Context<Self>,
 9137    ) -> Result<()> {
 9138        self.push_to_selection_history();
 9139        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9140
 9141        self.select_next_match_internal(&display_map, false, None, window, cx)?;
 9142        let Some(select_next_state) = self.select_next_state.as_mut() else {
 9143            return Ok(());
 9144        };
 9145        if select_next_state.done {
 9146            return Ok(());
 9147        }
 9148
 9149        let mut new_selections = self.selections.all::<usize>(cx);
 9150
 9151        let buffer = &display_map.buffer_snapshot;
 9152        let query_matches = select_next_state
 9153            .query
 9154            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 9155
 9156        for query_match in query_matches {
 9157            let query_match = query_match.unwrap(); // can only fail due to I/O
 9158            let offset_range = query_match.start()..query_match.end();
 9159            let display_range = offset_range.start.to_display_point(&display_map)
 9160                ..offset_range.end.to_display_point(&display_map);
 9161
 9162            if !select_next_state.wordwise
 9163                || (!movement::is_inside_word(&display_map, display_range.start)
 9164                    && !movement::is_inside_word(&display_map, display_range.end))
 9165            {
 9166                self.selections.change_with(cx, |selections| {
 9167                    new_selections.push(Selection {
 9168                        id: selections.new_selection_id(),
 9169                        start: offset_range.start,
 9170                        end: offset_range.end,
 9171                        reversed: false,
 9172                        goal: SelectionGoal::None,
 9173                    });
 9174                });
 9175            }
 9176        }
 9177
 9178        new_selections.sort_by_key(|selection| selection.start);
 9179        let mut ix = 0;
 9180        while ix + 1 < new_selections.len() {
 9181            let current_selection = &new_selections[ix];
 9182            let next_selection = &new_selections[ix + 1];
 9183            if current_selection.range().overlaps(&next_selection.range()) {
 9184                if current_selection.id < next_selection.id {
 9185                    new_selections.remove(ix + 1);
 9186                } else {
 9187                    new_selections.remove(ix);
 9188                }
 9189            } else {
 9190                ix += 1;
 9191            }
 9192        }
 9193
 9194        let reversed = self.selections.oldest::<usize>(cx).reversed;
 9195
 9196        for selection in new_selections.iter_mut() {
 9197            selection.reversed = reversed;
 9198        }
 9199
 9200        select_next_state.done = true;
 9201        self.unfold_ranges(
 9202            &new_selections
 9203                .iter()
 9204                .map(|selection| selection.range())
 9205                .collect::<Vec<_>>(),
 9206            false,
 9207            false,
 9208            cx,
 9209        );
 9210        self.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
 9211            selections.select(new_selections)
 9212        });
 9213
 9214        Ok(())
 9215    }
 9216
 9217    pub fn select_next(
 9218        &mut self,
 9219        action: &SelectNext,
 9220        window: &mut Window,
 9221        cx: &mut Context<Self>,
 9222    ) -> Result<()> {
 9223        self.push_to_selection_history();
 9224        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9225        self.select_next_match_internal(
 9226            &display_map,
 9227            action.replace_newest,
 9228            Some(Autoscroll::newest()),
 9229            window,
 9230            cx,
 9231        )?;
 9232        Ok(())
 9233    }
 9234
 9235    pub fn select_previous(
 9236        &mut self,
 9237        action: &SelectPrevious,
 9238        window: &mut Window,
 9239        cx: &mut Context<Self>,
 9240    ) -> Result<()> {
 9241        self.push_to_selection_history();
 9242        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9243        let buffer = &display_map.buffer_snapshot;
 9244        let mut selections = self.selections.all::<usize>(cx);
 9245        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 9246            let query = &select_prev_state.query;
 9247            if !select_prev_state.done {
 9248                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 9249                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 9250                let mut next_selected_range = None;
 9251                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 9252                let bytes_before_last_selection =
 9253                    buffer.reversed_bytes_in_range(0..last_selection.start);
 9254                let bytes_after_first_selection =
 9255                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 9256                let query_matches = query
 9257                    .stream_find_iter(bytes_before_last_selection)
 9258                    .map(|result| (last_selection.start, result))
 9259                    .chain(
 9260                        query
 9261                            .stream_find_iter(bytes_after_first_selection)
 9262                            .map(|result| (buffer.len(), result)),
 9263                    );
 9264                for (end_offset, query_match) in query_matches {
 9265                    let query_match = query_match.unwrap(); // can only fail due to I/O
 9266                    let offset_range =
 9267                        end_offset - query_match.end()..end_offset - query_match.start();
 9268                    let display_range = offset_range.start.to_display_point(&display_map)
 9269                        ..offset_range.end.to_display_point(&display_map);
 9270
 9271                    if !select_prev_state.wordwise
 9272                        || (!movement::is_inside_word(&display_map, display_range.start)
 9273                            && !movement::is_inside_word(&display_map, display_range.end))
 9274                    {
 9275                        next_selected_range = Some(offset_range);
 9276                        break;
 9277                    }
 9278                }
 9279
 9280                if let Some(next_selected_range) = next_selected_range {
 9281                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 9282                    self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9283                        if action.replace_newest {
 9284                            s.delete(s.newest_anchor().id);
 9285                        }
 9286                        s.insert_range(next_selected_range);
 9287                    });
 9288                } else {
 9289                    select_prev_state.done = true;
 9290                }
 9291            }
 9292
 9293            self.select_prev_state = Some(select_prev_state);
 9294        } else {
 9295            let mut only_carets = true;
 9296            let mut same_text_selected = true;
 9297            let mut selected_text = None;
 9298
 9299            let mut selections_iter = selections.iter().peekable();
 9300            while let Some(selection) = selections_iter.next() {
 9301                if selection.start != selection.end {
 9302                    only_carets = false;
 9303                }
 9304
 9305                if same_text_selected {
 9306                    if selected_text.is_none() {
 9307                        selected_text =
 9308                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 9309                    }
 9310
 9311                    if let Some(next_selection) = selections_iter.peek() {
 9312                        if next_selection.range().len() == selection.range().len() {
 9313                            let next_selected_text = buffer
 9314                                .text_for_range(next_selection.range())
 9315                                .collect::<String>();
 9316                            if Some(next_selected_text) != selected_text {
 9317                                same_text_selected = false;
 9318                                selected_text = None;
 9319                            }
 9320                        } else {
 9321                            same_text_selected = false;
 9322                            selected_text = None;
 9323                        }
 9324                    }
 9325                }
 9326            }
 9327
 9328            if only_carets {
 9329                for selection in &mut selections {
 9330                    let word_range = movement::surrounding_word(
 9331                        &display_map,
 9332                        selection.start.to_display_point(&display_map),
 9333                    );
 9334                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 9335                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 9336                    selection.goal = SelectionGoal::None;
 9337                    selection.reversed = false;
 9338                }
 9339                if selections.len() == 1 {
 9340                    let selection = selections
 9341                        .last()
 9342                        .expect("ensured that there's only one selection");
 9343                    let query = buffer
 9344                        .text_for_range(selection.start..selection.end)
 9345                        .collect::<String>();
 9346                    let is_empty = query.is_empty();
 9347                    let select_state = SelectNextState {
 9348                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 9349                        wordwise: true,
 9350                        done: is_empty,
 9351                    };
 9352                    self.select_prev_state = Some(select_state);
 9353                } else {
 9354                    self.select_prev_state = None;
 9355                }
 9356
 9357                self.unfold_ranges(
 9358                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 9359                    false,
 9360                    true,
 9361                    cx,
 9362                );
 9363                self.change_selections(Some(Autoscroll::newest()), window, cx, |s| {
 9364                    s.select(selections);
 9365                });
 9366            } else if let Some(selected_text) = selected_text {
 9367                self.select_prev_state = Some(SelectNextState {
 9368                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 9369                    wordwise: false,
 9370                    done: false,
 9371                });
 9372                self.select_previous(action, window, cx)?;
 9373            }
 9374        }
 9375        Ok(())
 9376    }
 9377
 9378    pub fn toggle_comments(
 9379        &mut self,
 9380        action: &ToggleComments,
 9381        window: &mut Window,
 9382        cx: &mut Context<Self>,
 9383    ) {
 9384        if self.read_only(cx) {
 9385            return;
 9386        }
 9387        let text_layout_details = &self.text_layout_details(window);
 9388        self.transact(window, cx, |this, window, cx| {
 9389            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 9390            let mut edits = Vec::new();
 9391            let mut selection_edit_ranges = Vec::new();
 9392            let mut last_toggled_row = None;
 9393            let snapshot = this.buffer.read(cx).read(cx);
 9394            let empty_str: Arc<str> = Arc::default();
 9395            let mut suffixes_inserted = Vec::new();
 9396            let ignore_indent = action.ignore_indent;
 9397
 9398            fn comment_prefix_range(
 9399                snapshot: &MultiBufferSnapshot,
 9400                row: MultiBufferRow,
 9401                comment_prefix: &str,
 9402                comment_prefix_whitespace: &str,
 9403                ignore_indent: bool,
 9404            ) -> Range<Point> {
 9405                let indent_size = if ignore_indent {
 9406                    0
 9407                } else {
 9408                    snapshot.indent_size_for_line(row).len
 9409                };
 9410
 9411                let start = Point::new(row.0, indent_size);
 9412
 9413                let mut line_bytes = snapshot
 9414                    .bytes_in_range(start..snapshot.max_point())
 9415                    .flatten()
 9416                    .copied();
 9417
 9418                // If this line currently begins with the line comment prefix, then record
 9419                // the range containing the prefix.
 9420                if line_bytes
 9421                    .by_ref()
 9422                    .take(comment_prefix.len())
 9423                    .eq(comment_prefix.bytes())
 9424                {
 9425                    // Include any whitespace that matches the comment prefix.
 9426                    let matching_whitespace_len = line_bytes
 9427                        .zip(comment_prefix_whitespace.bytes())
 9428                        .take_while(|(a, b)| a == b)
 9429                        .count() as u32;
 9430                    let end = Point::new(
 9431                        start.row,
 9432                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 9433                    );
 9434                    start..end
 9435                } else {
 9436                    start..start
 9437                }
 9438            }
 9439
 9440            fn comment_suffix_range(
 9441                snapshot: &MultiBufferSnapshot,
 9442                row: MultiBufferRow,
 9443                comment_suffix: &str,
 9444                comment_suffix_has_leading_space: bool,
 9445            ) -> Range<Point> {
 9446                let end = Point::new(row.0, snapshot.line_len(row));
 9447                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 9448
 9449                let mut line_end_bytes = snapshot
 9450                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 9451                    .flatten()
 9452                    .copied();
 9453
 9454                let leading_space_len = if suffix_start_column > 0
 9455                    && line_end_bytes.next() == Some(b' ')
 9456                    && comment_suffix_has_leading_space
 9457                {
 9458                    1
 9459                } else {
 9460                    0
 9461                };
 9462
 9463                // If this line currently begins with the line comment prefix, then record
 9464                // the range containing the prefix.
 9465                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 9466                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 9467                    start..end
 9468                } else {
 9469                    end..end
 9470                }
 9471            }
 9472
 9473            // TODO: Handle selections that cross excerpts
 9474            for selection in &mut selections {
 9475                let start_column = snapshot
 9476                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 9477                    .len;
 9478                let language = if let Some(language) =
 9479                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 9480                {
 9481                    language
 9482                } else {
 9483                    continue;
 9484                };
 9485
 9486                selection_edit_ranges.clear();
 9487
 9488                // If multiple selections contain a given row, avoid processing that
 9489                // row more than once.
 9490                let mut start_row = MultiBufferRow(selection.start.row);
 9491                if last_toggled_row == Some(start_row) {
 9492                    start_row = start_row.next_row();
 9493                }
 9494                let end_row =
 9495                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 9496                        MultiBufferRow(selection.end.row - 1)
 9497                    } else {
 9498                        MultiBufferRow(selection.end.row)
 9499                    };
 9500                last_toggled_row = Some(end_row);
 9501
 9502                if start_row > end_row {
 9503                    continue;
 9504                }
 9505
 9506                // If the language has line comments, toggle those.
 9507                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 9508
 9509                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 9510                if ignore_indent {
 9511                    full_comment_prefixes = full_comment_prefixes
 9512                        .into_iter()
 9513                        .map(|s| Arc::from(s.trim_end()))
 9514                        .collect();
 9515                }
 9516
 9517                if !full_comment_prefixes.is_empty() {
 9518                    let first_prefix = full_comment_prefixes
 9519                        .first()
 9520                        .expect("prefixes is non-empty");
 9521                    let prefix_trimmed_lengths = full_comment_prefixes
 9522                        .iter()
 9523                        .map(|p| p.trim_end_matches(' ').len())
 9524                        .collect::<SmallVec<[usize; 4]>>();
 9525
 9526                    let mut all_selection_lines_are_comments = true;
 9527
 9528                    for row in start_row.0..=end_row.0 {
 9529                        let row = MultiBufferRow(row);
 9530                        if start_row < end_row && snapshot.is_line_blank(row) {
 9531                            continue;
 9532                        }
 9533
 9534                        let prefix_range = full_comment_prefixes
 9535                            .iter()
 9536                            .zip(prefix_trimmed_lengths.iter().copied())
 9537                            .map(|(prefix, trimmed_prefix_len)| {
 9538                                comment_prefix_range(
 9539                                    snapshot.deref(),
 9540                                    row,
 9541                                    &prefix[..trimmed_prefix_len],
 9542                                    &prefix[trimmed_prefix_len..],
 9543                                    ignore_indent,
 9544                                )
 9545                            })
 9546                            .max_by_key(|range| range.end.column - range.start.column)
 9547                            .expect("prefixes is non-empty");
 9548
 9549                        if prefix_range.is_empty() {
 9550                            all_selection_lines_are_comments = false;
 9551                        }
 9552
 9553                        selection_edit_ranges.push(prefix_range);
 9554                    }
 9555
 9556                    if all_selection_lines_are_comments {
 9557                        edits.extend(
 9558                            selection_edit_ranges
 9559                                .iter()
 9560                                .cloned()
 9561                                .map(|range| (range, empty_str.clone())),
 9562                        );
 9563                    } else {
 9564                        let min_column = selection_edit_ranges
 9565                            .iter()
 9566                            .map(|range| range.start.column)
 9567                            .min()
 9568                            .unwrap_or(0);
 9569                        edits.extend(selection_edit_ranges.iter().map(|range| {
 9570                            let position = Point::new(range.start.row, min_column);
 9571                            (position..position, first_prefix.clone())
 9572                        }));
 9573                    }
 9574                } else if let Some((full_comment_prefix, comment_suffix)) =
 9575                    language.block_comment_delimiters()
 9576                {
 9577                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 9578                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 9579                    let prefix_range = comment_prefix_range(
 9580                        snapshot.deref(),
 9581                        start_row,
 9582                        comment_prefix,
 9583                        comment_prefix_whitespace,
 9584                        ignore_indent,
 9585                    );
 9586                    let suffix_range = comment_suffix_range(
 9587                        snapshot.deref(),
 9588                        end_row,
 9589                        comment_suffix.trim_start_matches(' '),
 9590                        comment_suffix.starts_with(' '),
 9591                    );
 9592
 9593                    if prefix_range.is_empty() || suffix_range.is_empty() {
 9594                        edits.push((
 9595                            prefix_range.start..prefix_range.start,
 9596                            full_comment_prefix.clone(),
 9597                        ));
 9598                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 9599                        suffixes_inserted.push((end_row, comment_suffix.len()));
 9600                    } else {
 9601                        edits.push((prefix_range, empty_str.clone()));
 9602                        edits.push((suffix_range, empty_str.clone()));
 9603                    }
 9604                } else {
 9605                    continue;
 9606                }
 9607            }
 9608
 9609            drop(snapshot);
 9610            this.buffer.update(cx, |buffer, cx| {
 9611                buffer.edit(edits, None, cx);
 9612            });
 9613
 9614            // Adjust selections so that they end before any comment suffixes that
 9615            // were inserted.
 9616            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 9617            let mut selections = this.selections.all::<Point>(cx);
 9618            let snapshot = this.buffer.read(cx).read(cx);
 9619            for selection in &mut selections {
 9620                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 9621                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 9622                        Ordering::Less => {
 9623                            suffixes_inserted.next();
 9624                            continue;
 9625                        }
 9626                        Ordering::Greater => break,
 9627                        Ordering::Equal => {
 9628                            if selection.end.column == snapshot.line_len(row) {
 9629                                if selection.is_empty() {
 9630                                    selection.start.column -= suffix_len as u32;
 9631                                }
 9632                                selection.end.column -= suffix_len as u32;
 9633                            }
 9634                            break;
 9635                        }
 9636                    }
 9637                }
 9638            }
 9639
 9640            drop(snapshot);
 9641            this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9642                s.select(selections)
 9643            });
 9644
 9645            let selections = this.selections.all::<Point>(cx);
 9646            let selections_on_single_row = selections.windows(2).all(|selections| {
 9647                selections[0].start.row == selections[1].start.row
 9648                    && selections[0].end.row == selections[1].end.row
 9649                    && selections[0].start.row == selections[0].end.row
 9650            });
 9651            let selections_selecting = selections
 9652                .iter()
 9653                .any(|selection| selection.start != selection.end);
 9654            let advance_downwards = action.advance_downwards
 9655                && selections_on_single_row
 9656                && !selections_selecting
 9657                && !matches!(this.mode, EditorMode::SingleLine { .. });
 9658
 9659            if advance_downwards {
 9660                let snapshot = this.buffer.read(cx).snapshot(cx);
 9661
 9662                this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9663                    s.move_cursors_with(|display_snapshot, display_point, _| {
 9664                        let mut point = display_point.to_point(display_snapshot);
 9665                        point.row += 1;
 9666                        point = snapshot.clip_point(point, Bias::Left);
 9667                        let display_point = point.to_display_point(display_snapshot);
 9668                        let goal = SelectionGoal::HorizontalPosition(
 9669                            display_snapshot
 9670                                .x_for_display_point(display_point, text_layout_details)
 9671                                .into(),
 9672                        );
 9673                        (display_point, goal)
 9674                    })
 9675                });
 9676            }
 9677        });
 9678    }
 9679
 9680    pub fn select_enclosing_symbol(
 9681        &mut self,
 9682        _: &SelectEnclosingSymbol,
 9683        window: &mut Window,
 9684        cx: &mut Context<Self>,
 9685    ) {
 9686        let buffer = self.buffer.read(cx).snapshot(cx);
 9687        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9688
 9689        fn update_selection(
 9690            selection: &Selection<usize>,
 9691            buffer_snap: &MultiBufferSnapshot,
 9692        ) -> Option<Selection<usize>> {
 9693            let cursor = selection.head();
 9694            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 9695            for symbol in symbols.iter().rev() {
 9696                let start = symbol.range.start.to_offset(buffer_snap);
 9697                let end = symbol.range.end.to_offset(buffer_snap);
 9698                let new_range = start..end;
 9699                if start < selection.start || end > selection.end {
 9700                    return Some(Selection {
 9701                        id: selection.id,
 9702                        start: new_range.start,
 9703                        end: new_range.end,
 9704                        goal: SelectionGoal::None,
 9705                        reversed: selection.reversed,
 9706                    });
 9707                }
 9708            }
 9709            None
 9710        }
 9711
 9712        let mut selected_larger_symbol = false;
 9713        let new_selections = old_selections
 9714            .iter()
 9715            .map(|selection| match update_selection(selection, &buffer) {
 9716                Some(new_selection) => {
 9717                    if new_selection.range() != selection.range() {
 9718                        selected_larger_symbol = true;
 9719                    }
 9720                    new_selection
 9721                }
 9722                None => selection.clone(),
 9723            })
 9724            .collect::<Vec<_>>();
 9725
 9726        if selected_larger_symbol {
 9727            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9728                s.select(new_selections);
 9729            });
 9730        }
 9731    }
 9732
 9733    pub fn select_larger_syntax_node(
 9734        &mut self,
 9735        _: &SelectLargerSyntaxNode,
 9736        window: &mut Window,
 9737        cx: &mut Context<Self>,
 9738    ) {
 9739        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 9740        let buffer = self.buffer.read(cx).snapshot(cx);
 9741        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 9742
 9743        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9744        let mut selected_larger_node = false;
 9745        let new_selections = old_selections
 9746            .iter()
 9747            .map(|selection| {
 9748                let old_range = selection.start..selection.end;
 9749                let mut new_range = old_range.clone();
 9750                let mut new_node = None;
 9751                while let Some((node, containing_range)) = buffer.syntax_ancestor(new_range.clone())
 9752                {
 9753                    new_node = Some(node);
 9754                    new_range = containing_range;
 9755                    if !display_map.intersects_fold(new_range.start)
 9756                        && !display_map.intersects_fold(new_range.end)
 9757                    {
 9758                        break;
 9759                    }
 9760                }
 9761
 9762                if let Some(node) = new_node {
 9763                    // Log the ancestor, to support using this action as a way to explore TreeSitter
 9764                    // nodes. Parent and grandparent are also logged because this operation will not
 9765                    // visit nodes that have the same range as their parent.
 9766                    log::info!("Node: {node:?}");
 9767                    let parent = node.parent();
 9768                    log::info!("Parent: {parent:?}");
 9769                    let grandparent = parent.and_then(|x| x.parent());
 9770                    log::info!("Grandparent: {grandparent:?}");
 9771                }
 9772
 9773                selected_larger_node |= new_range != old_range;
 9774                Selection {
 9775                    id: selection.id,
 9776                    start: new_range.start,
 9777                    end: new_range.end,
 9778                    goal: SelectionGoal::None,
 9779                    reversed: selection.reversed,
 9780                }
 9781            })
 9782            .collect::<Vec<_>>();
 9783
 9784        if selected_larger_node {
 9785            stack.push(old_selections);
 9786            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9787                s.select(new_selections);
 9788            });
 9789        }
 9790        self.select_larger_syntax_node_stack = stack;
 9791    }
 9792
 9793    pub fn select_smaller_syntax_node(
 9794        &mut self,
 9795        _: &SelectSmallerSyntaxNode,
 9796        window: &mut Window,
 9797        cx: &mut Context<Self>,
 9798    ) {
 9799        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 9800        if let Some(selections) = stack.pop() {
 9801            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9802                s.select(selections.to_vec());
 9803            });
 9804        }
 9805        self.select_larger_syntax_node_stack = stack;
 9806    }
 9807
 9808    fn refresh_runnables(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Task<()> {
 9809        if !EditorSettings::get_global(cx).gutter.runnables {
 9810            self.clear_tasks();
 9811            return Task::ready(());
 9812        }
 9813        let project = self.project.as_ref().map(Entity::downgrade);
 9814        cx.spawn_in(window, |this, mut cx| async move {
 9815            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 9816            let Some(project) = project.and_then(|p| p.upgrade()) else {
 9817                return;
 9818            };
 9819            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 9820                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 9821            }) else {
 9822                return;
 9823            };
 9824
 9825            let hide_runnables = project
 9826                .update(&mut cx, |project, cx| {
 9827                    // Do not display any test indicators in non-dev server remote projects.
 9828                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 9829                })
 9830                .unwrap_or(true);
 9831            if hide_runnables {
 9832                return;
 9833            }
 9834            let new_rows =
 9835                cx.background_executor()
 9836                    .spawn({
 9837                        let snapshot = display_snapshot.clone();
 9838                        async move {
 9839                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 9840                        }
 9841                    })
 9842                    .await;
 9843
 9844            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 9845            this.update(&mut cx, |this, _| {
 9846                this.clear_tasks();
 9847                for (key, value) in rows {
 9848                    this.insert_tasks(key, value);
 9849                }
 9850            })
 9851            .ok();
 9852        })
 9853    }
 9854    fn fetch_runnable_ranges(
 9855        snapshot: &DisplaySnapshot,
 9856        range: Range<Anchor>,
 9857    ) -> Vec<language::RunnableRange> {
 9858        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 9859    }
 9860
 9861    fn runnable_rows(
 9862        project: Entity<Project>,
 9863        snapshot: DisplaySnapshot,
 9864        runnable_ranges: Vec<RunnableRange>,
 9865        mut cx: AsyncWindowContext,
 9866    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 9867        runnable_ranges
 9868            .into_iter()
 9869            .filter_map(|mut runnable| {
 9870                let tasks = cx
 9871                    .update(|_, cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 9872                    .ok()?;
 9873                if tasks.is_empty() {
 9874                    return None;
 9875                }
 9876
 9877                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 9878
 9879                let row = snapshot
 9880                    .buffer_snapshot
 9881                    .buffer_line_for_row(MultiBufferRow(point.row))?
 9882                    .1
 9883                    .start
 9884                    .row;
 9885
 9886                let context_range =
 9887                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 9888                Some((
 9889                    (runnable.buffer_id, row),
 9890                    RunnableTasks {
 9891                        templates: tasks,
 9892                        offset: MultiBufferOffset(runnable.run_range.start),
 9893                        context_range,
 9894                        column: point.column,
 9895                        extra_variables: runnable.extra_captures,
 9896                    },
 9897                ))
 9898            })
 9899            .collect()
 9900    }
 9901
 9902    fn templates_with_tags(
 9903        project: &Entity<Project>,
 9904        runnable: &mut Runnable,
 9905        cx: &mut App,
 9906    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 9907        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 9908            let (worktree_id, file) = project
 9909                .buffer_for_id(runnable.buffer, cx)
 9910                .and_then(|buffer| buffer.read(cx).file())
 9911                .map(|file| (file.worktree_id(cx), file.clone()))
 9912                .unzip();
 9913
 9914            (
 9915                project.task_store().read(cx).task_inventory().cloned(),
 9916                worktree_id,
 9917                file,
 9918            )
 9919        });
 9920
 9921        let tags = mem::take(&mut runnable.tags);
 9922        let mut tags: Vec<_> = tags
 9923            .into_iter()
 9924            .flat_map(|tag| {
 9925                let tag = tag.0.clone();
 9926                inventory
 9927                    .as_ref()
 9928                    .into_iter()
 9929                    .flat_map(|inventory| {
 9930                        inventory.read(cx).list_tasks(
 9931                            file.clone(),
 9932                            Some(runnable.language.clone()),
 9933                            worktree_id,
 9934                            cx,
 9935                        )
 9936                    })
 9937                    .filter(move |(_, template)| {
 9938                        template.tags.iter().any(|source_tag| source_tag == &tag)
 9939                    })
 9940            })
 9941            .sorted_by_key(|(kind, _)| kind.to_owned())
 9942            .collect();
 9943        if let Some((leading_tag_source, _)) = tags.first() {
 9944            // Strongest source wins; if we have worktree tag binding, prefer that to
 9945            // global and language bindings;
 9946            // if we have a global binding, prefer that to language binding.
 9947            let first_mismatch = tags
 9948                .iter()
 9949                .position(|(tag_source, _)| tag_source != leading_tag_source);
 9950            if let Some(index) = first_mismatch {
 9951                tags.truncate(index);
 9952            }
 9953        }
 9954
 9955        tags
 9956    }
 9957
 9958    pub fn move_to_enclosing_bracket(
 9959        &mut self,
 9960        _: &MoveToEnclosingBracket,
 9961        window: &mut Window,
 9962        cx: &mut Context<Self>,
 9963    ) {
 9964        self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
 9965            s.move_offsets_with(|snapshot, selection| {
 9966                let Some(enclosing_bracket_ranges) =
 9967                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 9968                else {
 9969                    return;
 9970                };
 9971
 9972                let mut best_length = usize::MAX;
 9973                let mut best_inside = false;
 9974                let mut best_in_bracket_range = false;
 9975                let mut best_destination = None;
 9976                for (open, close) in enclosing_bracket_ranges {
 9977                    let close = close.to_inclusive();
 9978                    let length = close.end() - open.start;
 9979                    let inside = selection.start >= open.end && selection.end <= *close.start();
 9980                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 9981                        || close.contains(&selection.head());
 9982
 9983                    // If best is next to a bracket and current isn't, skip
 9984                    if !in_bracket_range && best_in_bracket_range {
 9985                        continue;
 9986                    }
 9987
 9988                    // Prefer smaller lengths unless best is inside and current isn't
 9989                    if length > best_length && (best_inside || !inside) {
 9990                        continue;
 9991                    }
 9992
 9993                    best_length = length;
 9994                    best_inside = inside;
 9995                    best_in_bracket_range = in_bracket_range;
 9996                    best_destination = Some(
 9997                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9998                            if inside {
 9999                                open.end
10000                            } else {
10001                                open.start
10002                            }
10003                        } else if inside {
10004                            *close.start()
10005                        } else {
10006                            *close.end()
10007                        },
10008                    );
10009                }
10010
10011                if let Some(destination) = best_destination {
10012                    selection.collapse_to(destination, SelectionGoal::None);
10013                }
10014            })
10015        });
10016    }
10017
10018    pub fn undo_selection(
10019        &mut self,
10020        _: &UndoSelection,
10021        window: &mut Window,
10022        cx: &mut Context<Self>,
10023    ) {
10024        self.end_selection(window, cx);
10025        self.selection_history.mode = SelectionHistoryMode::Undoing;
10026        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
10027            self.change_selections(None, window, cx, |s| {
10028                s.select_anchors(entry.selections.to_vec())
10029            });
10030            self.select_next_state = entry.select_next_state;
10031            self.select_prev_state = entry.select_prev_state;
10032            self.add_selections_state = entry.add_selections_state;
10033            self.request_autoscroll(Autoscroll::newest(), cx);
10034        }
10035        self.selection_history.mode = SelectionHistoryMode::Normal;
10036    }
10037
10038    pub fn redo_selection(
10039        &mut self,
10040        _: &RedoSelection,
10041        window: &mut Window,
10042        cx: &mut Context<Self>,
10043    ) {
10044        self.end_selection(window, cx);
10045        self.selection_history.mode = SelectionHistoryMode::Redoing;
10046        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
10047            self.change_selections(None, window, cx, |s| {
10048                s.select_anchors(entry.selections.to_vec())
10049            });
10050            self.select_next_state = entry.select_next_state;
10051            self.select_prev_state = entry.select_prev_state;
10052            self.add_selections_state = entry.add_selections_state;
10053            self.request_autoscroll(Autoscroll::newest(), cx);
10054        }
10055        self.selection_history.mode = SelectionHistoryMode::Normal;
10056    }
10057
10058    pub fn expand_excerpts(
10059        &mut self,
10060        action: &ExpandExcerpts,
10061        _: &mut Window,
10062        cx: &mut Context<Self>,
10063    ) {
10064        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
10065    }
10066
10067    pub fn expand_excerpts_down(
10068        &mut self,
10069        action: &ExpandExcerptsDown,
10070        _: &mut Window,
10071        cx: &mut Context<Self>,
10072    ) {
10073        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
10074    }
10075
10076    pub fn expand_excerpts_up(
10077        &mut self,
10078        action: &ExpandExcerptsUp,
10079        _: &mut Window,
10080        cx: &mut Context<Self>,
10081    ) {
10082        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
10083    }
10084
10085    pub fn expand_excerpts_for_direction(
10086        &mut self,
10087        lines: u32,
10088        direction: ExpandExcerptDirection,
10089
10090        cx: &mut Context<Self>,
10091    ) {
10092        let selections = self.selections.disjoint_anchors();
10093
10094        let lines = if lines == 0 {
10095            EditorSettings::get_global(cx).expand_excerpt_lines
10096        } else {
10097            lines
10098        };
10099
10100        self.buffer.update(cx, |buffer, cx| {
10101            let snapshot = buffer.snapshot(cx);
10102            let mut excerpt_ids = selections
10103                .iter()
10104                .flat_map(|selection| snapshot.excerpt_ids_for_range(selection.range()))
10105                .collect::<Vec<_>>();
10106            excerpt_ids.sort();
10107            excerpt_ids.dedup();
10108            buffer.expand_excerpts(excerpt_ids, lines, direction, cx)
10109        })
10110    }
10111
10112    pub fn expand_excerpt(
10113        &mut self,
10114        excerpt: ExcerptId,
10115        direction: ExpandExcerptDirection,
10116        cx: &mut Context<Self>,
10117    ) {
10118        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
10119        self.buffer.update(cx, |buffer, cx| {
10120            buffer.expand_excerpts([excerpt], lines, direction, cx)
10121        })
10122    }
10123
10124    pub fn go_to_singleton_buffer_point(
10125        &mut self,
10126        point: Point,
10127        window: &mut Window,
10128        cx: &mut Context<Self>,
10129    ) {
10130        self.go_to_singleton_buffer_range(point..point, window, cx);
10131    }
10132
10133    pub fn go_to_singleton_buffer_range(
10134        &mut self,
10135        range: Range<Point>,
10136        window: &mut Window,
10137        cx: &mut Context<Self>,
10138    ) {
10139        let multibuffer = self.buffer().read(cx);
10140        let Some(buffer) = multibuffer.as_singleton() else {
10141            return;
10142        };
10143        let Some(start) = multibuffer.buffer_point_to_anchor(&buffer, range.start, cx) else {
10144            return;
10145        };
10146        let Some(end) = multibuffer.buffer_point_to_anchor(&buffer, range.end, cx) else {
10147            return;
10148        };
10149        self.change_selections(Some(Autoscroll::center()), window, cx, |s| {
10150            s.select_anchor_ranges([start..end])
10151        });
10152    }
10153
10154    fn go_to_diagnostic(
10155        &mut self,
10156        _: &GoToDiagnostic,
10157        window: &mut Window,
10158        cx: &mut Context<Self>,
10159    ) {
10160        self.go_to_diagnostic_impl(Direction::Next, window, cx)
10161    }
10162
10163    fn go_to_prev_diagnostic(
10164        &mut self,
10165        _: &GoToPrevDiagnostic,
10166        window: &mut Window,
10167        cx: &mut Context<Self>,
10168    ) {
10169        self.go_to_diagnostic_impl(Direction::Prev, window, cx)
10170    }
10171
10172    pub fn go_to_diagnostic_impl(
10173        &mut self,
10174        direction: Direction,
10175        window: &mut Window,
10176        cx: &mut Context<Self>,
10177    ) {
10178        let buffer = self.buffer.read(cx).snapshot(cx);
10179        let selection = self.selections.newest::<usize>(cx);
10180
10181        // If there is an active Diagnostic Popover jump to its diagnostic instead.
10182        if direction == Direction::Next {
10183            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
10184                let Some(buffer_id) = popover.local_diagnostic.range.start.buffer_id else {
10185                    return;
10186                };
10187                self.activate_diagnostics(
10188                    buffer_id,
10189                    popover.local_diagnostic.diagnostic.group_id,
10190                    window,
10191                    cx,
10192                );
10193                if let Some(active_diagnostics) = self.active_diagnostics.as_ref() {
10194                    let primary_range_start = active_diagnostics.primary_range.start;
10195                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10196                        let mut new_selection = s.newest_anchor().clone();
10197                        new_selection.collapse_to(primary_range_start, SelectionGoal::None);
10198                        s.select_anchors(vec![new_selection.clone()]);
10199                    });
10200                    self.refresh_inline_completion(false, true, window, cx);
10201                }
10202                return;
10203            }
10204        }
10205
10206        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
10207            active_diagnostics
10208                .primary_range
10209                .to_offset(&buffer)
10210                .to_inclusive()
10211        });
10212        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
10213            if active_primary_range.contains(&selection.head()) {
10214                *active_primary_range.start()
10215            } else {
10216                selection.head()
10217            }
10218        } else {
10219            selection.head()
10220        };
10221        let snapshot = self.snapshot(window, cx);
10222        loop {
10223            let mut diagnostics;
10224            if direction == Direction::Prev {
10225                diagnostics = buffer
10226                    .diagnostics_in_range::<usize>(0..search_start)
10227                    .collect::<Vec<_>>();
10228                diagnostics.reverse();
10229            } else {
10230                diagnostics = buffer
10231                    .diagnostics_in_range::<usize>(search_start..buffer.len())
10232                    .collect::<Vec<_>>();
10233            };
10234            let group = diagnostics
10235                .into_iter()
10236                .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start))
10237                // relies on diagnostics_in_range to return diagnostics with the same starting range to
10238                // be sorted in a stable way
10239                // skip until we are at current active diagnostic, if it exists
10240                .skip_while(|entry| {
10241                    let is_in_range = match direction {
10242                        Direction::Prev => entry.range.end > search_start,
10243                        Direction::Next => entry.range.start < search_start,
10244                    };
10245                    is_in_range
10246                        && self
10247                            .active_diagnostics
10248                            .as_ref()
10249                            .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
10250                })
10251                .find_map(|entry| {
10252                    if entry.diagnostic.is_primary
10253                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
10254                        && entry.range.start != entry.range.end
10255                        // if we match with the active diagnostic, skip it
10256                        && Some(entry.diagnostic.group_id)
10257                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
10258                    {
10259                        Some((entry.range, entry.diagnostic.group_id))
10260                    } else {
10261                        None
10262                    }
10263                });
10264
10265            if let Some((primary_range, group_id)) = group {
10266                let Some(buffer_id) = buffer.anchor_after(primary_range.start).buffer_id else {
10267                    return;
10268                };
10269                self.activate_diagnostics(buffer_id, group_id, window, cx);
10270                if self.active_diagnostics.is_some() {
10271                    self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10272                        s.select(vec![Selection {
10273                            id: selection.id,
10274                            start: primary_range.start,
10275                            end: primary_range.start,
10276                            reversed: false,
10277                            goal: SelectionGoal::None,
10278                        }]);
10279                    });
10280                    self.refresh_inline_completion(false, true, window, cx);
10281                }
10282                break;
10283            } else {
10284                // Cycle around to the start of the buffer, potentially moving back to the start of
10285                // the currently active diagnostic.
10286                active_primary_range.take();
10287                if direction == Direction::Prev {
10288                    if search_start == buffer.len() {
10289                        break;
10290                    } else {
10291                        search_start = buffer.len();
10292                    }
10293                } else if search_start == 0 {
10294                    break;
10295                } else {
10296                    search_start = 0;
10297                }
10298            }
10299        }
10300    }
10301
10302    fn go_to_next_hunk(&mut self, _: &GoToHunk, window: &mut Window, cx: &mut Context<Self>) {
10303        let snapshot = self.snapshot(window, cx);
10304        let selection = self.selections.newest::<Point>(cx);
10305        self.go_to_hunk_after_position(&snapshot, selection.head(), window, cx);
10306    }
10307
10308    fn go_to_hunk_after_position(
10309        &mut self,
10310        snapshot: &EditorSnapshot,
10311        position: Point,
10312        window: &mut Window,
10313        cx: &mut Context<Editor>,
10314    ) -> Option<MultiBufferDiffHunk> {
10315        let mut hunk = snapshot
10316            .buffer_snapshot
10317            .diff_hunks_in_range(position..snapshot.buffer_snapshot.max_point())
10318            .find(|hunk| hunk.row_range.start.0 > position.row);
10319        if hunk.is_none() {
10320            hunk = snapshot
10321                .buffer_snapshot
10322                .diff_hunks_in_range(Point::zero()..position)
10323                .find(|hunk| hunk.row_range.end.0 < position.row)
10324        }
10325        if let Some(hunk) = &hunk {
10326            let destination = Point::new(hunk.row_range.start.0, 0);
10327            self.unfold_ranges(&[destination..destination], false, false, cx);
10328            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10329                s.select_ranges(vec![destination..destination]);
10330            });
10331        }
10332
10333        hunk
10334    }
10335
10336    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, window: &mut Window, cx: &mut Context<Self>) {
10337        let snapshot = self.snapshot(window, cx);
10338        let selection = self.selections.newest::<Point>(cx);
10339        self.go_to_hunk_before_position(&snapshot, selection.head(), window, cx);
10340    }
10341
10342    fn go_to_hunk_before_position(
10343        &mut self,
10344        snapshot: &EditorSnapshot,
10345        position: Point,
10346        window: &mut Window,
10347        cx: &mut Context<Editor>,
10348    ) -> Option<MultiBufferDiffHunk> {
10349        let mut hunk = snapshot.buffer_snapshot.diff_hunk_before(position);
10350        if hunk.is_none() {
10351            hunk = snapshot.buffer_snapshot.diff_hunk_before(Point::MAX);
10352        }
10353        if let Some(hunk) = &hunk {
10354            let destination = Point::new(hunk.row_range.start.0, 0);
10355            self.unfold_ranges(&[destination..destination], false, false, cx);
10356            self.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
10357                s.select_ranges(vec![destination..destination]);
10358            });
10359        }
10360
10361        hunk
10362    }
10363
10364    pub fn go_to_definition(
10365        &mut self,
10366        _: &GoToDefinition,
10367        window: &mut Window,
10368        cx: &mut Context<Self>,
10369    ) -> Task<Result<Navigated>> {
10370        let definition =
10371            self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, window, cx);
10372        cx.spawn_in(window, |editor, mut cx| async move {
10373            if definition.await? == Navigated::Yes {
10374                return Ok(Navigated::Yes);
10375            }
10376            match editor.update_in(&mut cx, |editor, window, cx| {
10377                editor.find_all_references(&FindAllReferences, window, cx)
10378            })? {
10379                Some(references) => references.await,
10380                None => Ok(Navigated::No),
10381            }
10382        })
10383    }
10384
10385    pub fn go_to_declaration(
10386        &mut self,
10387        _: &GoToDeclaration,
10388        window: &mut Window,
10389        cx: &mut Context<Self>,
10390    ) -> Task<Result<Navigated>> {
10391        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, window, cx)
10392    }
10393
10394    pub fn go_to_declaration_split(
10395        &mut self,
10396        _: &GoToDeclaration,
10397        window: &mut Window,
10398        cx: &mut Context<Self>,
10399    ) -> Task<Result<Navigated>> {
10400        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, window, cx)
10401    }
10402
10403    pub fn go_to_implementation(
10404        &mut self,
10405        _: &GoToImplementation,
10406        window: &mut Window,
10407        cx: &mut Context<Self>,
10408    ) -> Task<Result<Navigated>> {
10409        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, window, cx)
10410    }
10411
10412    pub fn go_to_implementation_split(
10413        &mut self,
10414        _: &GoToImplementationSplit,
10415        window: &mut Window,
10416        cx: &mut Context<Self>,
10417    ) -> Task<Result<Navigated>> {
10418        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, window, cx)
10419    }
10420
10421    pub fn go_to_type_definition(
10422        &mut self,
10423        _: &GoToTypeDefinition,
10424        window: &mut Window,
10425        cx: &mut Context<Self>,
10426    ) -> Task<Result<Navigated>> {
10427        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, window, cx)
10428    }
10429
10430    pub fn go_to_definition_split(
10431        &mut self,
10432        _: &GoToDefinitionSplit,
10433        window: &mut Window,
10434        cx: &mut Context<Self>,
10435    ) -> Task<Result<Navigated>> {
10436        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, window, cx)
10437    }
10438
10439    pub fn go_to_type_definition_split(
10440        &mut self,
10441        _: &GoToTypeDefinitionSplit,
10442        window: &mut Window,
10443        cx: &mut Context<Self>,
10444    ) -> Task<Result<Navigated>> {
10445        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, window, cx)
10446    }
10447
10448    fn go_to_definition_of_kind(
10449        &mut self,
10450        kind: GotoDefinitionKind,
10451        split: bool,
10452        window: &mut Window,
10453        cx: &mut Context<Self>,
10454    ) -> Task<Result<Navigated>> {
10455        let Some(provider) = self.semantics_provider.clone() else {
10456            return Task::ready(Ok(Navigated::No));
10457        };
10458        let head = self.selections.newest::<usize>(cx).head();
10459        let buffer = self.buffer.read(cx);
10460        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
10461            text_anchor
10462        } else {
10463            return Task::ready(Ok(Navigated::No));
10464        };
10465
10466        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
10467            return Task::ready(Ok(Navigated::No));
10468        };
10469
10470        cx.spawn_in(window, |editor, mut cx| async move {
10471            let definitions = definitions.await?;
10472            let navigated = editor
10473                .update_in(&mut cx, |editor, window, cx| {
10474                    editor.navigate_to_hover_links(
10475                        Some(kind),
10476                        definitions
10477                            .into_iter()
10478                            .filter(|location| {
10479                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
10480                            })
10481                            .map(HoverLink::Text)
10482                            .collect::<Vec<_>>(),
10483                        split,
10484                        window,
10485                        cx,
10486                    )
10487                })?
10488                .await?;
10489            anyhow::Ok(navigated)
10490        })
10491    }
10492
10493    pub fn open_url(&mut self, _: &OpenUrl, window: &mut Window, cx: &mut Context<Self>) {
10494        let selection = self.selections.newest_anchor();
10495        let head = selection.head();
10496        let tail = selection.tail();
10497
10498        let Some((buffer, start_position)) =
10499            self.buffer.read(cx).text_anchor_for_position(head, cx)
10500        else {
10501            return;
10502        };
10503
10504        let end_position = if head != tail {
10505            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
10506                return;
10507            };
10508            Some(pos)
10509        } else {
10510            None
10511        };
10512
10513        let url_finder = cx.spawn_in(window, |editor, mut cx| async move {
10514            let url = if let Some(end_pos) = end_position {
10515                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
10516            } else {
10517                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
10518            };
10519
10520            if let Some(url) = url {
10521                editor.update(&mut cx, |_, cx| {
10522                    cx.open_url(&url);
10523                })
10524            } else {
10525                Ok(())
10526            }
10527        });
10528
10529        url_finder.detach();
10530    }
10531
10532    pub fn open_selected_filename(
10533        &mut self,
10534        _: &OpenSelectedFilename,
10535        window: &mut Window,
10536        cx: &mut Context<Self>,
10537    ) {
10538        let Some(workspace) = self.workspace() else {
10539            return;
10540        };
10541
10542        let position = self.selections.newest_anchor().head();
10543
10544        let Some((buffer, buffer_position)) =
10545            self.buffer.read(cx).text_anchor_for_position(position, cx)
10546        else {
10547            return;
10548        };
10549
10550        let project = self.project.clone();
10551
10552        cx.spawn_in(window, |_, mut cx| async move {
10553            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
10554
10555            if let Some((_, path)) = result {
10556                workspace
10557                    .update_in(&mut cx, |workspace, window, cx| {
10558                        workspace.open_resolved_path(path, window, cx)
10559                    })?
10560                    .await?;
10561            }
10562            anyhow::Ok(())
10563        })
10564        .detach();
10565    }
10566
10567    pub(crate) fn navigate_to_hover_links(
10568        &mut self,
10569        kind: Option<GotoDefinitionKind>,
10570        mut definitions: Vec<HoverLink>,
10571        split: bool,
10572        window: &mut Window,
10573        cx: &mut Context<Editor>,
10574    ) -> Task<Result<Navigated>> {
10575        // If there is one definition, just open it directly
10576        if definitions.len() == 1 {
10577            let definition = definitions.pop().unwrap();
10578
10579            enum TargetTaskResult {
10580                Location(Option<Location>),
10581                AlreadyNavigated,
10582            }
10583
10584            let target_task = match definition {
10585                HoverLink::Text(link) => {
10586                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
10587                }
10588                HoverLink::InlayHint(lsp_location, server_id) => {
10589                    let computation =
10590                        self.compute_target_location(lsp_location, server_id, window, cx);
10591                    cx.background_executor().spawn(async move {
10592                        let location = computation.await?;
10593                        Ok(TargetTaskResult::Location(location))
10594                    })
10595                }
10596                HoverLink::Url(url) => {
10597                    cx.open_url(&url);
10598                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
10599                }
10600                HoverLink::File(path) => {
10601                    if let Some(workspace) = self.workspace() {
10602                        cx.spawn_in(window, |_, mut cx| async move {
10603                            workspace
10604                                .update_in(&mut cx, |workspace, window, cx| {
10605                                    workspace.open_resolved_path(path, window, cx)
10606                                })?
10607                                .await
10608                                .map(|_| TargetTaskResult::AlreadyNavigated)
10609                        })
10610                    } else {
10611                        Task::ready(Ok(TargetTaskResult::Location(None)))
10612                    }
10613                }
10614            };
10615            cx.spawn_in(window, |editor, mut cx| async move {
10616                let target = match target_task.await.context("target resolution task")? {
10617                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
10618                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
10619                    TargetTaskResult::Location(Some(target)) => target,
10620                };
10621
10622                editor.update_in(&mut cx, |editor, window, cx| {
10623                    let Some(workspace) = editor.workspace() else {
10624                        return Navigated::No;
10625                    };
10626                    let pane = workspace.read(cx).active_pane().clone();
10627
10628                    let range = target.range.to_point(target.buffer.read(cx));
10629                    let range = editor.range_for_match(&range);
10630                    let range = collapse_multiline_range(range);
10631
10632                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
10633                        editor.go_to_singleton_buffer_range(range.clone(), window, cx);
10634                    } else {
10635                        window.defer(cx, move |window, cx| {
10636                            let target_editor: Entity<Self> =
10637                                workspace.update(cx, |workspace, cx| {
10638                                    let pane = if split {
10639                                        workspace.adjacent_pane(window, cx)
10640                                    } else {
10641                                        workspace.active_pane().clone()
10642                                    };
10643
10644                                    workspace.open_project_item(
10645                                        pane,
10646                                        target.buffer.clone(),
10647                                        true,
10648                                        true,
10649                                        window,
10650                                        cx,
10651                                    )
10652                                });
10653                            target_editor.update(cx, |target_editor, cx| {
10654                                // When selecting a definition in a different buffer, disable the nav history
10655                                // to avoid creating a history entry at the previous cursor location.
10656                                pane.update(cx, |pane, _| pane.disable_history());
10657                                target_editor.go_to_singleton_buffer_range(range, window, cx);
10658                                pane.update(cx, |pane, _| pane.enable_history());
10659                            });
10660                        });
10661                    }
10662                    Navigated::Yes
10663                })
10664            })
10665        } else if !definitions.is_empty() {
10666            cx.spawn_in(window, |editor, mut cx| async move {
10667                let (title, location_tasks, workspace) = editor
10668                    .update_in(&mut cx, |editor, window, cx| {
10669                        let tab_kind = match kind {
10670                            Some(GotoDefinitionKind::Implementation) => "Implementations",
10671                            _ => "Definitions",
10672                        };
10673                        let title = definitions
10674                            .iter()
10675                            .find_map(|definition| match definition {
10676                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
10677                                    let buffer = origin.buffer.read(cx);
10678                                    format!(
10679                                        "{} for {}",
10680                                        tab_kind,
10681                                        buffer
10682                                            .text_for_range(origin.range.clone())
10683                                            .collect::<String>()
10684                                    )
10685                                }),
10686                                HoverLink::InlayHint(_, _) => None,
10687                                HoverLink::Url(_) => None,
10688                                HoverLink::File(_) => None,
10689                            })
10690                            .unwrap_or(tab_kind.to_string());
10691                        let location_tasks = definitions
10692                            .into_iter()
10693                            .map(|definition| match definition {
10694                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
10695                                HoverLink::InlayHint(lsp_location, server_id) => editor
10696                                    .compute_target_location(lsp_location, server_id, window, cx),
10697                                HoverLink::Url(_) => Task::ready(Ok(None)),
10698                                HoverLink::File(_) => Task::ready(Ok(None)),
10699                            })
10700                            .collect::<Vec<_>>();
10701                        (title, location_tasks, editor.workspace().clone())
10702                    })
10703                    .context("location tasks preparation")?;
10704
10705                let locations = future::join_all(location_tasks)
10706                    .await
10707                    .into_iter()
10708                    .filter_map(|location| location.transpose())
10709                    .collect::<Result<_>>()
10710                    .context("location tasks")?;
10711
10712                let Some(workspace) = workspace else {
10713                    return Ok(Navigated::No);
10714                };
10715                let opened = workspace
10716                    .update_in(&mut cx, |workspace, window, cx| {
10717                        Self::open_locations_in_multibuffer(
10718                            workspace,
10719                            locations,
10720                            title,
10721                            split,
10722                            MultibufferSelectionMode::First,
10723                            window,
10724                            cx,
10725                        )
10726                    })
10727                    .ok();
10728
10729                anyhow::Ok(Navigated::from_bool(opened.is_some()))
10730            })
10731        } else {
10732            Task::ready(Ok(Navigated::No))
10733        }
10734    }
10735
10736    fn compute_target_location(
10737        &self,
10738        lsp_location: lsp::Location,
10739        server_id: LanguageServerId,
10740        window: &mut Window,
10741        cx: &mut Context<Self>,
10742    ) -> Task<anyhow::Result<Option<Location>>> {
10743        let Some(project) = self.project.clone() else {
10744            return Task::ready(Ok(None));
10745        };
10746
10747        cx.spawn_in(window, move |editor, mut cx| async move {
10748            let location_task = editor.update(&mut cx, |_, cx| {
10749                project.update(cx, |project, cx| {
10750                    let language_server_name = project
10751                        .language_server_statuses(cx)
10752                        .find(|(id, _)| server_id == *id)
10753                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
10754                    language_server_name.map(|language_server_name| {
10755                        project.open_local_buffer_via_lsp(
10756                            lsp_location.uri.clone(),
10757                            server_id,
10758                            language_server_name,
10759                            cx,
10760                        )
10761                    })
10762                })
10763            })?;
10764            let location = match location_task {
10765                Some(task) => Some({
10766                    let target_buffer_handle = task.await.context("open local buffer")?;
10767                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
10768                        let target_start = target_buffer
10769                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
10770                        let target_end = target_buffer
10771                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
10772                        target_buffer.anchor_after(target_start)
10773                            ..target_buffer.anchor_before(target_end)
10774                    })?;
10775                    Location {
10776                        buffer: target_buffer_handle,
10777                        range,
10778                    }
10779                }),
10780                None => None,
10781            };
10782            Ok(location)
10783        })
10784    }
10785
10786    pub fn find_all_references(
10787        &mut self,
10788        _: &FindAllReferences,
10789        window: &mut Window,
10790        cx: &mut Context<Self>,
10791    ) -> Option<Task<Result<Navigated>>> {
10792        let selection = self.selections.newest::<usize>(cx);
10793        let multi_buffer = self.buffer.read(cx);
10794        let head = selection.head();
10795
10796        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
10797        let head_anchor = multi_buffer_snapshot.anchor_at(
10798            head,
10799            if head < selection.tail() {
10800                Bias::Right
10801            } else {
10802                Bias::Left
10803            },
10804        );
10805
10806        match self
10807            .find_all_references_task_sources
10808            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
10809        {
10810            Ok(_) => {
10811                log::info!(
10812                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
10813                );
10814                return None;
10815            }
10816            Err(i) => {
10817                self.find_all_references_task_sources.insert(i, head_anchor);
10818            }
10819        }
10820
10821        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
10822        let workspace = self.workspace()?;
10823        let project = workspace.read(cx).project().clone();
10824        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
10825        Some(cx.spawn_in(window, |editor, mut cx| async move {
10826            let _cleanup = defer({
10827                let mut cx = cx.clone();
10828                move || {
10829                    let _ = editor.update(&mut cx, |editor, _| {
10830                        if let Ok(i) =
10831                            editor
10832                                .find_all_references_task_sources
10833                                .binary_search_by(|anchor| {
10834                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
10835                                })
10836                        {
10837                            editor.find_all_references_task_sources.remove(i);
10838                        }
10839                    });
10840                }
10841            });
10842
10843            let locations = references.await?;
10844            if locations.is_empty() {
10845                return anyhow::Ok(Navigated::No);
10846            }
10847
10848            workspace.update_in(&mut cx, |workspace, window, cx| {
10849                let title = locations
10850                    .first()
10851                    .as_ref()
10852                    .map(|location| {
10853                        let buffer = location.buffer.read(cx);
10854                        format!(
10855                            "References to `{}`",
10856                            buffer
10857                                .text_for_range(location.range.clone())
10858                                .collect::<String>()
10859                        )
10860                    })
10861                    .unwrap();
10862                Self::open_locations_in_multibuffer(
10863                    workspace,
10864                    locations,
10865                    title,
10866                    false,
10867                    MultibufferSelectionMode::First,
10868                    window,
10869                    cx,
10870                );
10871                Navigated::Yes
10872            })
10873        }))
10874    }
10875
10876    /// Opens a multibuffer with the given project locations in it
10877    pub fn open_locations_in_multibuffer(
10878        workspace: &mut Workspace,
10879        mut locations: Vec<Location>,
10880        title: String,
10881        split: bool,
10882        multibuffer_selection_mode: MultibufferSelectionMode,
10883        window: &mut Window,
10884        cx: &mut Context<Workspace>,
10885    ) {
10886        // If there are multiple definitions, open them in a multibuffer
10887        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10888        let mut locations = locations.into_iter().peekable();
10889        let mut ranges = Vec::new();
10890        let capability = workspace.project().read(cx).capability();
10891
10892        let excerpt_buffer = cx.new(|cx| {
10893            let mut multibuffer = MultiBuffer::new(capability);
10894            while let Some(location) = locations.next() {
10895                let buffer = location.buffer.read(cx);
10896                let mut ranges_for_buffer = Vec::new();
10897                let range = location.range.to_offset(buffer);
10898                ranges_for_buffer.push(range.clone());
10899
10900                while let Some(next_location) = locations.peek() {
10901                    if next_location.buffer == location.buffer {
10902                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
10903                        locations.next();
10904                    } else {
10905                        break;
10906                    }
10907                }
10908
10909                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10910                ranges.extend(multibuffer.push_excerpts_with_context_lines(
10911                    location.buffer.clone(),
10912                    ranges_for_buffer,
10913                    DEFAULT_MULTIBUFFER_CONTEXT,
10914                    cx,
10915                ))
10916            }
10917
10918            multibuffer.with_title(title)
10919        });
10920
10921        let editor = cx.new(|cx| {
10922            Editor::for_multibuffer(
10923                excerpt_buffer,
10924                Some(workspace.project().clone()),
10925                true,
10926                window,
10927                cx,
10928            )
10929        });
10930        editor.update(cx, |editor, cx| {
10931            match multibuffer_selection_mode {
10932                MultibufferSelectionMode::First => {
10933                    if let Some(first_range) = ranges.first() {
10934                        editor.change_selections(None, window, cx, |selections| {
10935                            selections.clear_disjoint();
10936                            selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10937                        });
10938                    }
10939                    editor.highlight_background::<Self>(
10940                        &ranges,
10941                        |theme| theme.editor_highlighted_line_background,
10942                        cx,
10943                    );
10944                }
10945                MultibufferSelectionMode::All => {
10946                    editor.change_selections(None, window, cx, |selections| {
10947                        selections.clear_disjoint();
10948                        selections.select_anchor_ranges(ranges);
10949                    });
10950                }
10951            }
10952            editor.register_buffers_with_language_servers(cx);
10953        });
10954
10955        let item = Box::new(editor);
10956        let item_id = item.item_id();
10957
10958        if split {
10959            workspace.split_item(SplitDirection::Right, item.clone(), window, cx);
10960        } else {
10961            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10962                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10963                    pane.close_current_preview_item(window, cx)
10964                } else {
10965                    None
10966                }
10967            });
10968            workspace.add_item_to_active_pane(item.clone(), destination_index, true, window, cx);
10969        }
10970        workspace.active_pane().update(cx, |pane, cx| {
10971            pane.set_preview_item_id(Some(item_id), cx);
10972        });
10973    }
10974
10975    pub fn rename(
10976        &mut self,
10977        _: &Rename,
10978        window: &mut Window,
10979        cx: &mut Context<Self>,
10980    ) -> Option<Task<Result<()>>> {
10981        use language::ToOffset as _;
10982
10983        let provider = self.semantics_provider.clone()?;
10984        let selection = self.selections.newest_anchor().clone();
10985        let (cursor_buffer, cursor_buffer_position) = self
10986            .buffer
10987            .read(cx)
10988            .text_anchor_for_position(selection.head(), cx)?;
10989        let (tail_buffer, cursor_buffer_position_end) = self
10990            .buffer
10991            .read(cx)
10992            .text_anchor_for_position(selection.tail(), cx)?;
10993        if tail_buffer != cursor_buffer {
10994            return None;
10995        }
10996
10997        let snapshot = cursor_buffer.read(cx).snapshot();
10998        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10999        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
11000        let prepare_rename = provider
11001            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
11002            .unwrap_or_else(|| Task::ready(Ok(None)));
11003        drop(snapshot);
11004
11005        Some(cx.spawn_in(window, |this, mut cx| async move {
11006            let rename_range = if let Some(range) = prepare_rename.await? {
11007                Some(range)
11008            } else {
11009                this.update(&mut cx, |this, cx| {
11010                    let buffer = this.buffer.read(cx).snapshot(cx);
11011                    let mut buffer_highlights = this
11012                        .document_highlights_for_position(selection.head(), &buffer)
11013                        .filter(|highlight| {
11014                            highlight.start.excerpt_id == selection.head().excerpt_id
11015                                && highlight.end.excerpt_id == selection.head().excerpt_id
11016                        });
11017                    buffer_highlights
11018                        .next()
11019                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
11020                })?
11021            };
11022            if let Some(rename_range) = rename_range {
11023                this.update_in(&mut cx, |this, window, cx| {
11024                    let snapshot = cursor_buffer.read(cx).snapshot();
11025                    let rename_buffer_range = rename_range.to_offset(&snapshot);
11026                    let cursor_offset_in_rename_range =
11027                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
11028                    let cursor_offset_in_rename_range_end =
11029                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
11030
11031                    this.take_rename(false, window, cx);
11032                    let buffer = this.buffer.read(cx).read(cx);
11033                    let cursor_offset = selection.head().to_offset(&buffer);
11034                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
11035                    let rename_end = rename_start + rename_buffer_range.len();
11036                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
11037                    let mut old_highlight_id = None;
11038                    let old_name: Arc<str> = buffer
11039                        .chunks(rename_start..rename_end, true)
11040                        .map(|chunk| {
11041                            if old_highlight_id.is_none() {
11042                                old_highlight_id = chunk.syntax_highlight_id;
11043                            }
11044                            chunk.text
11045                        })
11046                        .collect::<String>()
11047                        .into();
11048
11049                    drop(buffer);
11050
11051                    // Position the selection in the rename editor so that it matches the current selection.
11052                    this.show_local_selections = false;
11053                    let rename_editor = cx.new(|cx| {
11054                        let mut editor = Editor::single_line(window, cx);
11055                        editor.buffer.update(cx, |buffer, cx| {
11056                            buffer.edit([(0..0, old_name.clone())], None, cx)
11057                        });
11058                        let rename_selection_range = match cursor_offset_in_rename_range
11059                            .cmp(&cursor_offset_in_rename_range_end)
11060                        {
11061                            Ordering::Equal => {
11062                                editor.select_all(&SelectAll, window, cx);
11063                                return editor;
11064                            }
11065                            Ordering::Less => {
11066                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
11067                            }
11068                            Ordering::Greater => {
11069                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
11070                            }
11071                        };
11072                        if rename_selection_range.end > old_name.len() {
11073                            editor.select_all(&SelectAll, window, cx);
11074                        } else {
11075                            editor.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
11076                                s.select_ranges([rename_selection_range]);
11077                            });
11078                        }
11079                        editor
11080                    });
11081                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
11082                        if e == &EditorEvent::Focused {
11083                            cx.emit(EditorEvent::FocusedIn)
11084                        }
11085                    })
11086                    .detach();
11087
11088                    let write_highlights =
11089                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
11090                    let read_highlights =
11091                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
11092                    let ranges = write_highlights
11093                        .iter()
11094                        .flat_map(|(_, ranges)| ranges.iter())
11095                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
11096                        .cloned()
11097                        .collect();
11098
11099                    this.highlight_text::<Rename>(
11100                        ranges,
11101                        HighlightStyle {
11102                            fade_out: Some(0.6),
11103                            ..Default::default()
11104                        },
11105                        cx,
11106                    );
11107                    let rename_focus_handle = rename_editor.focus_handle(cx);
11108                    window.focus(&rename_focus_handle);
11109                    let block_id = this.insert_blocks(
11110                        [BlockProperties {
11111                            style: BlockStyle::Flex,
11112                            placement: BlockPlacement::Below(range.start),
11113                            height: 1,
11114                            render: Arc::new({
11115                                let rename_editor = rename_editor.clone();
11116                                move |cx: &mut BlockContext| {
11117                                    let mut text_style = cx.editor_style.text.clone();
11118                                    if let Some(highlight_style) = old_highlight_id
11119                                        .and_then(|h| h.style(&cx.editor_style.syntax))
11120                                    {
11121                                        text_style = text_style.highlight(highlight_style);
11122                                    }
11123                                    div()
11124                                        .block_mouse_down()
11125                                        .pl(cx.anchor_x)
11126                                        .child(EditorElement::new(
11127                                            &rename_editor,
11128                                            EditorStyle {
11129                                                background: cx.theme().system().transparent,
11130                                                local_player: cx.editor_style.local_player,
11131                                                text: text_style,
11132                                                scrollbar_width: cx.editor_style.scrollbar_width,
11133                                                syntax: cx.editor_style.syntax.clone(),
11134                                                status: cx.editor_style.status.clone(),
11135                                                inlay_hints_style: HighlightStyle {
11136                                                    font_weight: Some(FontWeight::BOLD),
11137                                                    ..make_inlay_hints_style(cx.app)
11138                                                },
11139                                                inline_completion_styles: make_suggestion_styles(
11140                                                    cx.app,
11141                                                ),
11142                                                ..EditorStyle::default()
11143                                            },
11144                                        ))
11145                                        .into_any_element()
11146                                }
11147                            }),
11148                            priority: 0,
11149                        }],
11150                        Some(Autoscroll::fit()),
11151                        cx,
11152                    )[0];
11153                    this.pending_rename = Some(RenameState {
11154                        range,
11155                        old_name,
11156                        editor: rename_editor,
11157                        block_id,
11158                    });
11159                })?;
11160            }
11161
11162            Ok(())
11163        }))
11164    }
11165
11166    pub fn confirm_rename(
11167        &mut self,
11168        _: &ConfirmRename,
11169        window: &mut Window,
11170        cx: &mut Context<Self>,
11171    ) -> Option<Task<Result<()>>> {
11172        let rename = self.take_rename(false, window, cx)?;
11173        let workspace = self.workspace()?.downgrade();
11174        let (buffer, start) = self
11175            .buffer
11176            .read(cx)
11177            .text_anchor_for_position(rename.range.start, cx)?;
11178        let (end_buffer, _) = self
11179            .buffer
11180            .read(cx)
11181            .text_anchor_for_position(rename.range.end, cx)?;
11182        if buffer != end_buffer {
11183            return None;
11184        }
11185
11186        let old_name = rename.old_name;
11187        let new_name = rename.editor.read(cx).text(cx);
11188
11189        let rename = self.semantics_provider.as_ref()?.perform_rename(
11190            &buffer,
11191            start,
11192            new_name.clone(),
11193            cx,
11194        )?;
11195
11196        Some(cx.spawn_in(window, |editor, mut cx| async move {
11197            let project_transaction = rename.await?;
11198            Self::open_project_transaction(
11199                &editor,
11200                workspace,
11201                project_transaction,
11202                format!("Rename: {}{}", old_name, new_name),
11203                cx.clone(),
11204            )
11205            .await?;
11206
11207            editor.update(&mut cx, |editor, cx| {
11208                editor.refresh_document_highlights(cx);
11209            })?;
11210            Ok(())
11211        }))
11212    }
11213
11214    fn take_rename(
11215        &mut self,
11216        moving_cursor: bool,
11217        window: &mut Window,
11218        cx: &mut Context<Self>,
11219    ) -> Option<RenameState> {
11220        let rename = self.pending_rename.take()?;
11221        if rename.editor.focus_handle(cx).is_focused(window) {
11222            window.focus(&self.focus_handle);
11223        }
11224
11225        self.remove_blocks(
11226            [rename.block_id].into_iter().collect(),
11227            Some(Autoscroll::fit()),
11228            cx,
11229        );
11230        self.clear_highlights::<Rename>(cx);
11231        self.show_local_selections = true;
11232
11233        if moving_cursor {
11234            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
11235                editor.selections.newest::<usize>(cx).head()
11236            });
11237
11238            // Update the selection to match the position of the selection inside
11239            // the rename editor.
11240            let snapshot = self.buffer.read(cx).read(cx);
11241            let rename_range = rename.range.to_offset(&snapshot);
11242            let cursor_in_editor = snapshot
11243                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
11244                .min(rename_range.end);
11245            drop(snapshot);
11246
11247            self.change_selections(None, window, cx, |s| {
11248                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
11249            });
11250        } else {
11251            self.refresh_document_highlights(cx);
11252        }
11253
11254        Some(rename)
11255    }
11256
11257    pub fn pending_rename(&self) -> Option<&RenameState> {
11258        self.pending_rename.as_ref()
11259    }
11260
11261    fn format(
11262        &mut self,
11263        _: &Format,
11264        window: &mut Window,
11265        cx: &mut Context<Self>,
11266    ) -> Option<Task<Result<()>>> {
11267        let project = match &self.project {
11268            Some(project) => project.clone(),
11269            None => return None,
11270        };
11271
11272        Some(self.perform_format(
11273            project,
11274            FormatTrigger::Manual,
11275            FormatTarget::Buffers,
11276            window,
11277            cx,
11278        ))
11279    }
11280
11281    fn format_selections(
11282        &mut self,
11283        _: &FormatSelections,
11284        window: &mut Window,
11285        cx: &mut Context<Self>,
11286    ) -> Option<Task<Result<()>>> {
11287        let project = match &self.project {
11288            Some(project) => project.clone(),
11289            None => return None,
11290        };
11291
11292        let ranges = self
11293            .selections
11294            .all_adjusted(cx)
11295            .into_iter()
11296            .map(|selection| selection.range())
11297            .collect_vec();
11298
11299        Some(self.perform_format(
11300            project,
11301            FormatTrigger::Manual,
11302            FormatTarget::Ranges(ranges),
11303            window,
11304            cx,
11305        ))
11306    }
11307
11308    fn perform_format(
11309        &mut self,
11310        project: Entity<Project>,
11311        trigger: FormatTrigger,
11312        target: FormatTarget,
11313        window: &mut Window,
11314        cx: &mut Context<Self>,
11315    ) -> Task<Result<()>> {
11316        let buffer = self.buffer.clone();
11317        let (buffers, target) = match target {
11318            FormatTarget::Buffers => {
11319                let mut buffers = buffer.read(cx).all_buffers();
11320                if trigger == FormatTrigger::Save {
11321                    buffers.retain(|buffer| buffer.read(cx).is_dirty());
11322                }
11323                (buffers, LspFormatTarget::Buffers)
11324            }
11325            FormatTarget::Ranges(selection_ranges) => {
11326                let multi_buffer = buffer.read(cx);
11327                let snapshot = multi_buffer.read(cx);
11328                let mut buffers = HashSet::default();
11329                let mut buffer_id_to_ranges: BTreeMap<BufferId, Vec<Range<text::Anchor>>> =
11330                    BTreeMap::new();
11331                for selection_range in selection_ranges {
11332                    for (buffer, buffer_range, _) in
11333                        snapshot.range_to_buffer_ranges(selection_range)
11334                    {
11335                        let buffer_id = buffer.remote_id();
11336                        let start = buffer.anchor_before(buffer_range.start);
11337                        let end = buffer.anchor_after(buffer_range.end);
11338                        buffers.insert(multi_buffer.buffer(buffer_id).unwrap());
11339                        buffer_id_to_ranges
11340                            .entry(buffer_id)
11341                            .and_modify(|buffer_ranges| buffer_ranges.push(start..end))
11342                            .or_insert_with(|| vec![start..end]);
11343                    }
11344                }
11345                (buffers, LspFormatTarget::Ranges(buffer_id_to_ranges))
11346            }
11347        };
11348
11349        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
11350        let format = project.update(cx, |project, cx| {
11351            project.format(buffers, target, true, trigger, cx)
11352        });
11353
11354        cx.spawn_in(window, |_, mut cx| async move {
11355            let transaction = futures::select_biased! {
11356                () = timeout => {
11357                    log::warn!("timed out waiting for formatting");
11358                    None
11359                }
11360                transaction = format.log_err().fuse() => transaction,
11361            };
11362
11363            buffer
11364                .update(&mut cx, |buffer, cx| {
11365                    if let Some(transaction) = transaction {
11366                        if !buffer.is_singleton() {
11367                            buffer.push_transaction(&transaction.0, cx);
11368                        }
11369                    }
11370
11371                    cx.notify();
11372                })
11373                .ok();
11374
11375            Ok(())
11376        })
11377    }
11378
11379    fn restart_language_server(
11380        &mut self,
11381        _: &RestartLanguageServer,
11382        _: &mut Window,
11383        cx: &mut Context<Self>,
11384    ) {
11385        if let Some(project) = self.project.clone() {
11386            self.buffer.update(cx, |multi_buffer, cx| {
11387                project.update(cx, |project, cx| {
11388                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
11389                });
11390            })
11391        }
11392    }
11393
11394    fn cancel_language_server_work(
11395        workspace: &mut Workspace,
11396        _: &actions::CancelLanguageServerWork,
11397        _: &mut Window,
11398        cx: &mut Context<Workspace>,
11399    ) {
11400        let project = workspace.project();
11401        let buffers = workspace
11402            .active_item(cx)
11403            .and_then(|item| item.act_as::<Editor>(cx))
11404            .map_or(HashSet::default(), |editor| {
11405                editor.read(cx).buffer.read(cx).all_buffers()
11406            });
11407        project.update(cx, |project, cx| {
11408            project.cancel_language_server_work_for_buffers(buffers, cx);
11409        });
11410    }
11411
11412    fn show_character_palette(
11413        &mut self,
11414        _: &ShowCharacterPalette,
11415        window: &mut Window,
11416        _: &mut Context<Self>,
11417    ) {
11418        window.show_character_palette();
11419    }
11420
11421    fn refresh_active_diagnostics(&mut self, cx: &mut Context<Editor>) {
11422        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
11423            let buffer = self.buffer.read(cx).snapshot(cx);
11424            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
11425            let primary_range_end = active_diagnostics.primary_range.end.to_offset(&buffer);
11426            let is_valid = buffer
11427                .diagnostics_in_range::<usize>(primary_range_start..primary_range_end)
11428                .any(|entry| {
11429                    entry.diagnostic.is_primary
11430                        && !entry.range.is_empty()
11431                        && entry.range.start == primary_range_start
11432                        && entry.diagnostic.message == active_diagnostics.primary_message
11433                });
11434
11435            if is_valid != active_diagnostics.is_valid {
11436                active_diagnostics.is_valid = is_valid;
11437                let mut new_styles = HashMap::default();
11438                for (block_id, diagnostic) in &active_diagnostics.blocks {
11439                    new_styles.insert(
11440                        *block_id,
11441                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
11442                    );
11443                }
11444                self.display_map.update(cx, |display_map, _cx| {
11445                    display_map.replace_blocks(new_styles)
11446                });
11447            }
11448        }
11449    }
11450
11451    fn activate_diagnostics(
11452        &mut self,
11453        buffer_id: BufferId,
11454        group_id: usize,
11455        window: &mut Window,
11456        cx: &mut Context<Self>,
11457    ) {
11458        self.dismiss_diagnostics(cx);
11459        let snapshot = self.snapshot(window, cx);
11460        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
11461            let buffer = self.buffer.read(cx).snapshot(cx);
11462
11463            let mut primary_range = None;
11464            let mut primary_message = None;
11465            let diagnostic_group = buffer
11466                .diagnostic_group(buffer_id, group_id)
11467                .filter_map(|entry| {
11468                    let start = entry.range.start;
11469                    let end = entry.range.end;
11470                    if snapshot.is_line_folded(MultiBufferRow(start.row))
11471                        && (start.row == end.row
11472                            || snapshot.is_line_folded(MultiBufferRow(end.row)))
11473                    {
11474                        return None;
11475                    }
11476                    if entry.diagnostic.is_primary {
11477                        primary_range = Some(entry.range.clone());
11478                        primary_message = Some(entry.diagnostic.message.clone());
11479                    }
11480                    Some(entry)
11481                })
11482                .collect::<Vec<_>>();
11483            let primary_range = primary_range?;
11484            let primary_message = primary_message?;
11485
11486            let blocks = display_map
11487                .insert_blocks(
11488                    diagnostic_group.iter().map(|entry| {
11489                        let diagnostic = entry.diagnostic.clone();
11490                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
11491                        BlockProperties {
11492                            style: BlockStyle::Fixed,
11493                            placement: BlockPlacement::Below(
11494                                buffer.anchor_after(entry.range.start),
11495                            ),
11496                            height: message_height,
11497                            render: diagnostic_block_renderer(diagnostic, None, true, true),
11498                            priority: 0,
11499                        }
11500                    }),
11501                    cx,
11502                )
11503                .into_iter()
11504                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
11505                .collect();
11506
11507            Some(ActiveDiagnosticGroup {
11508                primary_range: buffer.anchor_before(primary_range.start)
11509                    ..buffer.anchor_after(primary_range.end),
11510                primary_message,
11511                group_id,
11512                blocks,
11513                is_valid: true,
11514            })
11515        });
11516    }
11517
11518    fn dismiss_diagnostics(&mut self, cx: &mut Context<Self>) {
11519        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
11520            self.display_map.update(cx, |display_map, cx| {
11521                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
11522            });
11523            cx.notify();
11524        }
11525    }
11526
11527    pub fn set_selections_from_remote(
11528        &mut self,
11529        selections: Vec<Selection<Anchor>>,
11530        pending_selection: Option<Selection<Anchor>>,
11531        window: &mut Window,
11532        cx: &mut Context<Self>,
11533    ) {
11534        let old_cursor_position = self.selections.newest_anchor().head();
11535        self.selections.change_with(cx, |s| {
11536            s.select_anchors(selections);
11537            if let Some(pending_selection) = pending_selection {
11538                s.set_pending(pending_selection, SelectMode::Character);
11539            } else {
11540                s.clear_pending();
11541            }
11542        });
11543        self.selections_did_change(false, &old_cursor_position, true, window, cx);
11544    }
11545
11546    fn push_to_selection_history(&mut self) {
11547        self.selection_history.push(SelectionHistoryEntry {
11548            selections: self.selections.disjoint_anchors(),
11549            select_next_state: self.select_next_state.clone(),
11550            select_prev_state: self.select_prev_state.clone(),
11551            add_selections_state: self.add_selections_state.clone(),
11552        });
11553    }
11554
11555    pub fn transact(
11556        &mut self,
11557        window: &mut Window,
11558        cx: &mut Context<Self>,
11559        update: impl FnOnce(&mut Self, &mut Window, &mut Context<Self>),
11560    ) -> Option<TransactionId> {
11561        self.start_transaction_at(Instant::now(), window, cx);
11562        update(self, window, cx);
11563        self.end_transaction_at(Instant::now(), cx)
11564    }
11565
11566    pub fn start_transaction_at(
11567        &mut self,
11568        now: Instant,
11569        window: &mut Window,
11570        cx: &mut Context<Self>,
11571    ) {
11572        self.end_selection(window, cx);
11573        if let Some(tx_id) = self
11574            .buffer
11575            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
11576        {
11577            self.selection_history
11578                .insert_transaction(tx_id, self.selections.disjoint_anchors());
11579            cx.emit(EditorEvent::TransactionBegun {
11580                transaction_id: tx_id,
11581            })
11582        }
11583    }
11584
11585    pub fn end_transaction_at(
11586        &mut self,
11587        now: Instant,
11588        cx: &mut Context<Self>,
11589    ) -> Option<TransactionId> {
11590        if let Some(transaction_id) = self
11591            .buffer
11592            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
11593        {
11594            if let Some((_, end_selections)) =
11595                self.selection_history.transaction_mut(transaction_id)
11596            {
11597                *end_selections = Some(self.selections.disjoint_anchors());
11598            } else {
11599                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
11600            }
11601
11602            cx.emit(EditorEvent::Edited { transaction_id });
11603            Some(transaction_id)
11604        } else {
11605            None
11606        }
11607    }
11608
11609    pub fn set_mark(&mut self, _: &actions::SetMark, window: &mut Window, cx: &mut Context<Self>) {
11610        if self.selection_mark_mode {
11611            self.change_selections(None, window, cx, |s| {
11612                s.move_with(|_, sel| {
11613                    sel.collapse_to(sel.head(), SelectionGoal::None);
11614                });
11615            })
11616        }
11617        self.selection_mark_mode = true;
11618        cx.notify();
11619    }
11620
11621    pub fn swap_selection_ends(
11622        &mut self,
11623        _: &actions::SwapSelectionEnds,
11624        window: &mut Window,
11625        cx: &mut Context<Self>,
11626    ) {
11627        self.change_selections(None, window, cx, |s| {
11628            s.move_with(|_, sel| {
11629                if sel.start != sel.end {
11630                    sel.reversed = !sel.reversed
11631                }
11632            });
11633        });
11634        self.request_autoscroll(Autoscroll::newest(), cx);
11635        cx.notify();
11636    }
11637
11638    pub fn toggle_fold(
11639        &mut self,
11640        _: &actions::ToggleFold,
11641        window: &mut Window,
11642        cx: &mut Context<Self>,
11643    ) {
11644        if self.is_singleton(cx) {
11645            let selection = self.selections.newest::<Point>(cx);
11646
11647            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11648            let range = if selection.is_empty() {
11649                let point = selection.head().to_display_point(&display_map);
11650                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11651                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11652                    .to_point(&display_map);
11653                start..end
11654            } else {
11655                selection.range()
11656            };
11657            if display_map.folds_in_range(range).next().is_some() {
11658                self.unfold_lines(&Default::default(), window, cx)
11659            } else {
11660                self.fold(&Default::default(), window, cx)
11661            }
11662        } else {
11663            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11664            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11665                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11666                .map(|(snapshot, _, _)| snapshot.remote_id())
11667                .collect();
11668
11669            for buffer_id in buffer_ids {
11670                if self.is_buffer_folded(buffer_id, cx) {
11671                    self.unfold_buffer(buffer_id, cx);
11672                } else {
11673                    self.fold_buffer(buffer_id, cx);
11674                }
11675            }
11676        }
11677    }
11678
11679    pub fn toggle_fold_recursive(
11680        &mut self,
11681        _: &actions::ToggleFoldRecursive,
11682        window: &mut Window,
11683        cx: &mut Context<Self>,
11684    ) {
11685        let selection = self.selections.newest::<Point>(cx);
11686
11687        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11688        let range = if selection.is_empty() {
11689            let point = selection.head().to_display_point(&display_map);
11690            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
11691            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
11692                .to_point(&display_map);
11693            start..end
11694        } else {
11695            selection.range()
11696        };
11697        if display_map.folds_in_range(range).next().is_some() {
11698            self.unfold_recursive(&Default::default(), window, cx)
11699        } else {
11700            self.fold_recursive(&Default::default(), window, cx)
11701        }
11702    }
11703
11704    pub fn fold(&mut self, _: &actions::Fold, window: &mut Window, cx: &mut Context<Self>) {
11705        if self.is_singleton(cx) {
11706            let mut to_fold = Vec::new();
11707            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11708            let selections = self.selections.all_adjusted(cx);
11709
11710            for selection in selections {
11711                let range = selection.range().sorted();
11712                let buffer_start_row = range.start.row;
11713
11714                if range.start.row != range.end.row {
11715                    let mut found = false;
11716                    let mut row = range.start.row;
11717                    while row <= range.end.row {
11718                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
11719                        {
11720                            found = true;
11721                            row = crease.range().end.row + 1;
11722                            to_fold.push(crease);
11723                        } else {
11724                            row += 1
11725                        }
11726                    }
11727                    if found {
11728                        continue;
11729                    }
11730                }
11731
11732                for row in (0..=range.start.row).rev() {
11733                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11734                        if crease.range().end.row >= buffer_start_row {
11735                            to_fold.push(crease);
11736                            if row <= range.start.row {
11737                                break;
11738                            }
11739                        }
11740                    }
11741                }
11742            }
11743
11744            self.fold_creases(to_fold, true, window, cx);
11745        } else {
11746            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11747
11748            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11749                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11750                .map(|(snapshot, _, _)| snapshot.remote_id())
11751                .collect();
11752            for buffer_id in buffer_ids {
11753                self.fold_buffer(buffer_id, cx);
11754            }
11755        }
11756    }
11757
11758    fn fold_at_level(
11759        &mut self,
11760        fold_at: &FoldAtLevel,
11761        window: &mut Window,
11762        cx: &mut Context<Self>,
11763    ) {
11764        if !self.buffer.read(cx).is_singleton() {
11765            return;
11766        }
11767
11768        let fold_at_level = fold_at.level;
11769        let snapshot = self.buffer.read(cx).snapshot(cx);
11770        let mut to_fold = Vec::new();
11771        let mut stack = vec![(0, snapshot.max_row().0, 1)];
11772
11773        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
11774            while start_row < end_row {
11775                match self
11776                    .snapshot(window, cx)
11777                    .crease_for_buffer_row(MultiBufferRow(start_row))
11778                {
11779                    Some(crease) => {
11780                        let nested_start_row = crease.range().start.row + 1;
11781                        let nested_end_row = crease.range().end.row;
11782
11783                        if current_level < fold_at_level {
11784                            stack.push((nested_start_row, nested_end_row, current_level + 1));
11785                        } else if current_level == fold_at_level {
11786                            to_fold.push(crease);
11787                        }
11788
11789                        start_row = nested_end_row + 1;
11790                    }
11791                    None => start_row += 1,
11792                }
11793            }
11794        }
11795
11796        self.fold_creases(to_fold, true, window, cx);
11797    }
11798
11799    pub fn fold_all(&mut self, _: &actions::FoldAll, window: &mut Window, cx: &mut Context<Self>) {
11800        if self.buffer.read(cx).is_singleton() {
11801            let mut fold_ranges = Vec::new();
11802            let snapshot = self.buffer.read(cx).snapshot(cx);
11803
11804            for row in 0..snapshot.max_row().0 {
11805                if let Some(foldable_range) = self
11806                    .snapshot(window, cx)
11807                    .crease_for_buffer_row(MultiBufferRow(row))
11808                {
11809                    fold_ranges.push(foldable_range);
11810                }
11811            }
11812
11813            self.fold_creases(fold_ranges, true, window, cx);
11814        } else {
11815            self.toggle_fold_multiple_buffers = cx.spawn_in(window, |editor, mut cx| async move {
11816                editor
11817                    .update_in(&mut cx, |editor, _, cx| {
11818                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11819                            editor.fold_buffer(buffer_id, cx);
11820                        }
11821                    })
11822                    .ok();
11823            });
11824        }
11825    }
11826
11827    pub fn fold_function_bodies(
11828        &mut self,
11829        _: &actions::FoldFunctionBodies,
11830        window: &mut Window,
11831        cx: &mut Context<Self>,
11832    ) {
11833        let snapshot = self.buffer.read(cx).snapshot(cx);
11834
11835        let ranges = snapshot
11836            .text_object_ranges(0..snapshot.len(), TreeSitterOptions::default())
11837            .filter_map(|(range, obj)| (obj == TextObject::InsideFunction).then_some(range))
11838            .collect::<Vec<_>>();
11839
11840        let creases = ranges
11841            .into_iter()
11842            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
11843            .collect();
11844
11845        self.fold_creases(creases, true, window, cx);
11846    }
11847
11848    pub fn fold_recursive(
11849        &mut self,
11850        _: &actions::FoldRecursive,
11851        window: &mut Window,
11852        cx: &mut Context<Self>,
11853    ) {
11854        let mut to_fold = Vec::new();
11855        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11856        let selections = self.selections.all_adjusted(cx);
11857
11858        for selection in selections {
11859            let range = selection.range().sorted();
11860            let buffer_start_row = range.start.row;
11861
11862            if range.start.row != range.end.row {
11863                let mut found = false;
11864                for row in range.start.row..=range.end.row {
11865                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11866                        found = true;
11867                        to_fold.push(crease);
11868                    }
11869                }
11870                if found {
11871                    continue;
11872                }
11873            }
11874
11875            for row in (0..=range.start.row).rev() {
11876                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
11877                    if crease.range().end.row >= buffer_start_row {
11878                        to_fold.push(crease);
11879                    } else {
11880                        break;
11881                    }
11882                }
11883            }
11884        }
11885
11886        self.fold_creases(to_fold, true, window, cx);
11887    }
11888
11889    pub fn fold_at(&mut self, fold_at: &FoldAt, window: &mut Window, cx: &mut Context<Self>) {
11890        let buffer_row = fold_at.buffer_row;
11891        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11892
11893        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
11894            let autoscroll = self
11895                .selections
11896                .all::<Point>(cx)
11897                .iter()
11898                .any(|selection| crease.range().overlaps(&selection.range()));
11899
11900            self.fold_creases(vec![crease], autoscroll, window, cx);
11901        }
11902    }
11903
11904    pub fn unfold_lines(&mut self, _: &UnfoldLines, _window: &mut Window, cx: &mut Context<Self>) {
11905        if self.is_singleton(cx) {
11906            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11907            let buffer = &display_map.buffer_snapshot;
11908            let selections = self.selections.all::<Point>(cx);
11909            let ranges = selections
11910                .iter()
11911                .map(|s| {
11912                    let range = s.display_range(&display_map).sorted();
11913                    let mut start = range.start.to_point(&display_map);
11914                    let mut end = range.end.to_point(&display_map);
11915                    start.column = 0;
11916                    end.column = buffer.line_len(MultiBufferRow(end.row));
11917                    start..end
11918                })
11919                .collect::<Vec<_>>();
11920
11921            self.unfold_ranges(&ranges, true, true, cx);
11922        } else {
11923            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
11924            let buffer_ids: HashSet<_> = multi_buffer_snapshot
11925                .ranges_to_buffer_ranges(self.selections.disjoint_anchor_ranges())
11926                .map(|(snapshot, _, _)| snapshot.remote_id())
11927                .collect();
11928            for buffer_id in buffer_ids {
11929                self.unfold_buffer(buffer_id, cx);
11930            }
11931        }
11932    }
11933
11934    pub fn unfold_recursive(
11935        &mut self,
11936        _: &UnfoldRecursive,
11937        _window: &mut Window,
11938        cx: &mut Context<Self>,
11939    ) {
11940        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11941        let selections = self.selections.all::<Point>(cx);
11942        let ranges = selections
11943            .iter()
11944            .map(|s| {
11945                let mut range = s.display_range(&display_map).sorted();
11946                *range.start.column_mut() = 0;
11947                *range.end.column_mut() = display_map.line_len(range.end.row());
11948                let start = range.start.to_point(&display_map);
11949                let end = range.end.to_point(&display_map);
11950                start..end
11951            })
11952            .collect::<Vec<_>>();
11953
11954        self.unfold_ranges(&ranges, true, true, cx);
11955    }
11956
11957    pub fn unfold_at(
11958        &mut self,
11959        unfold_at: &UnfoldAt,
11960        _window: &mut Window,
11961        cx: &mut Context<Self>,
11962    ) {
11963        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11964
11965        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
11966            ..Point::new(
11967                unfold_at.buffer_row.0,
11968                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
11969            );
11970
11971        let autoscroll = self
11972            .selections
11973            .all::<Point>(cx)
11974            .iter()
11975            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
11976
11977        self.unfold_ranges(&[intersection_range], true, autoscroll, cx);
11978    }
11979
11980    pub fn unfold_all(
11981        &mut self,
11982        _: &actions::UnfoldAll,
11983        _window: &mut Window,
11984        cx: &mut Context<Self>,
11985    ) {
11986        if self.buffer.read(cx).is_singleton() {
11987            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
11988            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
11989        } else {
11990            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
11991                editor
11992                    .update(&mut cx, |editor, cx| {
11993                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
11994                            editor.unfold_buffer(buffer_id, cx);
11995                        }
11996                    })
11997                    .ok();
11998            });
11999        }
12000    }
12001
12002    pub fn fold_selected_ranges(
12003        &mut self,
12004        _: &FoldSelectedRanges,
12005        window: &mut Window,
12006        cx: &mut Context<Self>,
12007    ) {
12008        let selections = self.selections.all::<Point>(cx);
12009        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12010        let line_mode = self.selections.line_mode;
12011        let ranges = selections
12012            .into_iter()
12013            .map(|s| {
12014                if line_mode {
12015                    let start = Point::new(s.start.row, 0);
12016                    let end = Point::new(
12017                        s.end.row,
12018                        display_map
12019                            .buffer_snapshot
12020                            .line_len(MultiBufferRow(s.end.row)),
12021                    );
12022                    Crease::simple(start..end, display_map.fold_placeholder.clone())
12023                } else {
12024                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
12025                }
12026            })
12027            .collect::<Vec<_>>();
12028        self.fold_creases(ranges, true, window, cx);
12029    }
12030
12031    pub fn fold_ranges<T: ToOffset + Clone>(
12032        &mut self,
12033        ranges: Vec<Range<T>>,
12034        auto_scroll: bool,
12035        window: &mut Window,
12036        cx: &mut Context<Self>,
12037    ) {
12038        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
12039        let ranges = ranges
12040            .into_iter()
12041            .map(|r| Crease::simple(r, display_map.fold_placeholder.clone()))
12042            .collect::<Vec<_>>();
12043        self.fold_creases(ranges, auto_scroll, window, cx);
12044    }
12045
12046    pub fn fold_creases<T: ToOffset + Clone>(
12047        &mut self,
12048        creases: Vec<Crease<T>>,
12049        auto_scroll: bool,
12050        window: &mut Window,
12051        cx: &mut Context<Self>,
12052    ) {
12053        if creases.is_empty() {
12054            return;
12055        }
12056
12057        let mut buffers_affected = HashSet::default();
12058        let multi_buffer = self.buffer().read(cx);
12059        for crease in &creases {
12060            if let Some((_, buffer, _)) =
12061                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
12062            {
12063                buffers_affected.insert(buffer.read(cx).remote_id());
12064            };
12065        }
12066
12067        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
12068
12069        if auto_scroll {
12070            self.request_autoscroll(Autoscroll::fit(), cx);
12071        }
12072
12073        cx.notify();
12074
12075        if let Some(active_diagnostics) = self.active_diagnostics.take() {
12076            // Clear diagnostics block when folding a range that contains it.
12077            let snapshot = self.snapshot(window, cx);
12078            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
12079                drop(snapshot);
12080                self.active_diagnostics = Some(active_diagnostics);
12081                self.dismiss_diagnostics(cx);
12082            } else {
12083                self.active_diagnostics = Some(active_diagnostics);
12084            }
12085        }
12086
12087        self.scrollbar_marker_state.dirty = true;
12088    }
12089
12090    /// Removes any folds whose ranges intersect any of the given ranges.
12091    pub fn unfold_ranges<T: ToOffset + Clone>(
12092        &mut self,
12093        ranges: &[Range<T>],
12094        inclusive: bool,
12095        auto_scroll: bool,
12096        cx: &mut Context<Self>,
12097    ) {
12098        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12099            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
12100        });
12101    }
12102
12103    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12104        if self.buffer().read(cx).is_singleton() || self.is_buffer_folded(buffer_id, cx) {
12105            return;
12106        }
12107        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12108        self.display_map
12109            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
12110        cx.emit(EditorEvent::BufferFoldToggled {
12111            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
12112            folded: true,
12113        });
12114        cx.notify();
12115    }
12116
12117    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut Context<Self>) {
12118        if self.buffer().read(cx).is_singleton() || !self.is_buffer_folded(buffer_id, cx) {
12119            return;
12120        }
12121        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(buffer_id, cx);
12122        self.display_map.update(cx, |display_map, cx| {
12123            display_map.unfold_buffer(buffer_id, cx);
12124        });
12125        cx.emit(EditorEvent::BufferFoldToggled {
12126            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
12127            folded: false,
12128        });
12129        cx.notify();
12130    }
12131
12132    pub fn is_buffer_folded(&self, buffer: BufferId, cx: &App) -> bool {
12133        self.display_map.read(cx).is_buffer_folded(buffer)
12134    }
12135
12136    pub fn folded_buffers<'a>(&self, cx: &'a App) -> &'a HashSet<BufferId> {
12137        self.display_map.read(cx).folded_buffers()
12138    }
12139
12140    /// Removes any folds with the given ranges.
12141    pub fn remove_folds_with_type<T: ToOffset + Clone>(
12142        &mut self,
12143        ranges: &[Range<T>],
12144        type_id: TypeId,
12145        auto_scroll: bool,
12146        cx: &mut Context<Self>,
12147    ) {
12148        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
12149            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
12150        });
12151    }
12152
12153    fn remove_folds_with<T: ToOffset + Clone>(
12154        &mut self,
12155        ranges: &[Range<T>],
12156        auto_scroll: bool,
12157        cx: &mut Context<Self>,
12158        update: impl FnOnce(&mut DisplayMap, &mut Context<DisplayMap>),
12159    ) {
12160        if ranges.is_empty() {
12161            return;
12162        }
12163
12164        let mut buffers_affected = HashSet::default();
12165        let multi_buffer = self.buffer().read(cx);
12166        for range in ranges {
12167            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
12168                buffers_affected.insert(buffer.read(cx).remote_id());
12169            };
12170        }
12171
12172        self.display_map.update(cx, update);
12173
12174        if auto_scroll {
12175            self.request_autoscroll(Autoscroll::fit(), cx);
12176        }
12177
12178        cx.notify();
12179        self.scrollbar_marker_state.dirty = true;
12180        self.active_indent_guides_state.dirty = true;
12181    }
12182
12183    pub fn default_fold_placeholder(&self, cx: &App) -> FoldPlaceholder {
12184        self.display_map.read(cx).fold_placeholder.clone()
12185    }
12186
12187    pub fn set_expand_all_diff_hunks(&mut self, cx: &mut App) {
12188        self.buffer.update(cx, |buffer, cx| {
12189            buffer.set_all_diff_hunks_expanded(cx);
12190        });
12191    }
12192
12193    pub fn expand_all_diff_hunks(
12194        &mut self,
12195        _: &ExpandAllHunkDiffs,
12196        _window: &mut Window,
12197        cx: &mut Context<Self>,
12198    ) {
12199        self.buffer.update(cx, |buffer, cx| {
12200            buffer.expand_diff_hunks(vec![Anchor::min()..Anchor::max()], cx)
12201        });
12202    }
12203
12204    pub fn toggle_selected_diff_hunks(
12205        &mut self,
12206        _: &ToggleSelectedDiffHunks,
12207        _window: &mut Window,
12208        cx: &mut Context<Self>,
12209    ) {
12210        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12211        self.toggle_diff_hunks_in_ranges(ranges, cx);
12212    }
12213
12214    pub fn expand_selected_diff_hunks(&mut self, cx: &mut Context<Self>) {
12215        let ranges: Vec<_> = self.selections.disjoint.iter().map(|s| s.range()).collect();
12216        self.buffer
12217            .update(cx, |buffer, cx| buffer.expand_diff_hunks(ranges, cx))
12218    }
12219
12220    pub fn clear_expanded_diff_hunks(&mut self, cx: &mut Context<Self>) -> bool {
12221        self.buffer.update(cx, |buffer, cx| {
12222            let ranges = vec![Anchor::min()..Anchor::max()];
12223            if !buffer.all_diff_hunks_expanded()
12224                && buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx)
12225            {
12226                buffer.collapse_diff_hunks(ranges, cx);
12227                true
12228            } else {
12229                false
12230            }
12231        })
12232    }
12233
12234    fn toggle_diff_hunks_in_ranges(
12235        &mut self,
12236        ranges: Vec<Range<Anchor>>,
12237        cx: &mut Context<'_, Editor>,
12238    ) {
12239        self.buffer.update(cx, |buffer, cx| {
12240            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12241            buffer.expand_or_collapse_diff_hunks(ranges, expand, cx);
12242        })
12243    }
12244
12245    fn toggle_diff_hunks_in_ranges_narrow(
12246        &mut self,
12247        ranges: Vec<Range<Anchor>>,
12248        cx: &mut Context<'_, Editor>,
12249    ) {
12250        self.buffer.update(cx, |buffer, cx| {
12251            let expand = !buffer.has_expanded_diff_hunks_in_ranges(&ranges, cx);
12252            buffer.expand_or_collapse_diff_hunks_narrow(ranges, expand, cx);
12253        })
12254    }
12255
12256    pub(crate) fn apply_all_diff_hunks(
12257        &mut self,
12258        _: &ApplyAllDiffHunks,
12259        window: &mut Window,
12260        cx: &mut Context<Self>,
12261    ) {
12262        let buffers = self.buffer.read(cx).all_buffers();
12263        for branch_buffer in buffers {
12264            branch_buffer.update(cx, |branch_buffer, cx| {
12265                branch_buffer.merge_into_base(Vec::new(), cx);
12266            });
12267        }
12268
12269        if let Some(project) = self.project.clone() {
12270            self.save(true, project, window, cx).detach_and_log_err(cx);
12271        }
12272    }
12273
12274    pub(crate) fn apply_selected_diff_hunks(
12275        &mut self,
12276        _: &ApplyDiffHunk,
12277        window: &mut Window,
12278        cx: &mut Context<Self>,
12279    ) {
12280        let snapshot = self.snapshot(window, cx);
12281        let hunks = snapshot.hunks_for_ranges(self.selections.ranges(cx).into_iter());
12282        let mut ranges_by_buffer = HashMap::default();
12283        self.transact(window, cx, |editor, _window, cx| {
12284            for hunk in hunks {
12285                if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
12286                    ranges_by_buffer
12287                        .entry(buffer.clone())
12288                        .or_insert_with(Vec::new)
12289                        .push(hunk.buffer_range.to_offset(buffer.read(cx)));
12290                }
12291            }
12292
12293            for (buffer, ranges) in ranges_by_buffer {
12294                buffer.update(cx, |buffer, cx| {
12295                    buffer.merge_into_base(ranges, cx);
12296                });
12297            }
12298        });
12299
12300        if let Some(project) = self.project.clone() {
12301            self.save(true, project, window, cx).detach_and_log_err(cx);
12302        }
12303    }
12304
12305    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut Context<Self>) {
12306        if hovered != self.gutter_hovered {
12307            self.gutter_hovered = hovered;
12308            cx.notify();
12309        }
12310    }
12311
12312    pub fn insert_blocks(
12313        &mut self,
12314        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
12315        autoscroll: Option<Autoscroll>,
12316        cx: &mut Context<Self>,
12317    ) -> Vec<CustomBlockId> {
12318        let blocks = self
12319            .display_map
12320            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
12321        if let Some(autoscroll) = autoscroll {
12322            self.request_autoscroll(autoscroll, cx);
12323        }
12324        cx.notify();
12325        blocks
12326    }
12327
12328    pub fn resize_blocks(
12329        &mut self,
12330        heights: HashMap<CustomBlockId, u32>,
12331        autoscroll: Option<Autoscroll>,
12332        cx: &mut Context<Self>,
12333    ) {
12334        self.display_map
12335            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
12336        if let Some(autoscroll) = autoscroll {
12337            self.request_autoscroll(autoscroll, cx);
12338        }
12339        cx.notify();
12340    }
12341
12342    pub fn replace_blocks(
12343        &mut self,
12344        renderers: HashMap<CustomBlockId, RenderBlock>,
12345        autoscroll: Option<Autoscroll>,
12346        cx: &mut Context<Self>,
12347    ) {
12348        self.display_map
12349            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
12350        if let Some(autoscroll) = autoscroll {
12351            self.request_autoscroll(autoscroll, cx);
12352        }
12353        cx.notify();
12354    }
12355
12356    pub fn remove_blocks(
12357        &mut self,
12358        block_ids: HashSet<CustomBlockId>,
12359        autoscroll: Option<Autoscroll>,
12360        cx: &mut Context<Self>,
12361    ) {
12362        self.display_map.update(cx, |display_map, cx| {
12363            display_map.remove_blocks(block_ids, cx)
12364        });
12365        if let Some(autoscroll) = autoscroll {
12366            self.request_autoscroll(autoscroll, cx);
12367        }
12368        cx.notify();
12369    }
12370
12371    pub fn row_for_block(
12372        &self,
12373        block_id: CustomBlockId,
12374        cx: &mut Context<Self>,
12375    ) -> Option<DisplayRow> {
12376        self.display_map
12377            .update(cx, |map, cx| map.row_for_block(block_id, cx))
12378    }
12379
12380    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
12381        self.focused_block = Some(focused_block);
12382    }
12383
12384    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
12385        self.focused_block.take()
12386    }
12387
12388    pub fn insert_creases(
12389        &mut self,
12390        creases: impl IntoIterator<Item = Crease<Anchor>>,
12391        cx: &mut Context<Self>,
12392    ) -> Vec<CreaseId> {
12393        self.display_map
12394            .update(cx, |map, cx| map.insert_creases(creases, cx))
12395    }
12396
12397    pub fn remove_creases(
12398        &mut self,
12399        ids: impl IntoIterator<Item = CreaseId>,
12400        cx: &mut Context<Self>,
12401    ) {
12402        self.display_map
12403            .update(cx, |map, cx| map.remove_creases(ids, cx));
12404    }
12405
12406    pub fn longest_row(&self, cx: &mut App) -> DisplayRow {
12407        self.display_map
12408            .update(cx, |map, cx| map.snapshot(cx))
12409            .longest_row()
12410    }
12411
12412    pub fn max_point(&self, cx: &mut App) -> DisplayPoint {
12413        self.display_map
12414            .update(cx, |map, cx| map.snapshot(cx))
12415            .max_point()
12416    }
12417
12418    pub fn text(&self, cx: &App) -> String {
12419        self.buffer.read(cx).read(cx).text()
12420    }
12421
12422    pub fn is_empty(&self, cx: &App) -> bool {
12423        self.buffer.read(cx).read(cx).is_empty()
12424    }
12425
12426    pub fn text_option(&self, cx: &App) -> Option<String> {
12427        let text = self.text(cx);
12428        let text = text.trim();
12429
12430        if text.is_empty() {
12431            return None;
12432        }
12433
12434        Some(text.to_string())
12435    }
12436
12437    pub fn set_text(
12438        &mut self,
12439        text: impl Into<Arc<str>>,
12440        window: &mut Window,
12441        cx: &mut Context<Self>,
12442    ) {
12443        self.transact(window, cx, |this, _, cx| {
12444            this.buffer
12445                .read(cx)
12446                .as_singleton()
12447                .expect("you can only call set_text on editors for singleton buffers")
12448                .update(cx, |buffer, cx| buffer.set_text(text, cx));
12449        });
12450    }
12451
12452    pub fn display_text(&self, cx: &mut App) -> String {
12453        self.display_map
12454            .update(cx, |map, cx| map.snapshot(cx))
12455            .text()
12456    }
12457
12458    pub fn wrap_guides(&self, cx: &App) -> SmallVec<[(usize, bool); 2]> {
12459        let mut wrap_guides = smallvec::smallvec![];
12460
12461        if self.show_wrap_guides == Some(false) {
12462            return wrap_guides;
12463        }
12464
12465        let settings = self.buffer.read(cx).settings_at(0, cx);
12466        if settings.show_wrap_guides {
12467            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
12468                wrap_guides.push((soft_wrap as usize, true));
12469            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
12470                wrap_guides.push((soft_wrap as usize, true));
12471            }
12472            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
12473        }
12474
12475        wrap_guides
12476    }
12477
12478    pub fn soft_wrap_mode(&self, cx: &App) -> SoftWrap {
12479        let settings = self.buffer.read(cx).settings_at(0, cx);
12480        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
12481        match mode {
12482            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
12483                SoftWrap::None
12484            }
12485            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
12486            language_settings::SoftWrap::PreferredLineLength => {
12487                SoftWrap::Column(settings.preferred_line_length)
12488            }
12489            language_settings::SoftWrap::Bounded => {
12490                SoftWrap::Bounded(settings.preferred_line_length)
12491            }
12492        }
12493    }
12494
12495    pub fn set_soft_wrap_mode(
12496        &mut self,
12497        mode: language_settings::SoftWrap,
12498
12499        cx: &mut Context<Self>,
12500    ) {
12501        self.soft_wrap_mode_override = Some(mode);
12502        cx.notify();
12503    }
12504
12505    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
12506        self.text_style_refinement = Some(style);
12507    }
12508
12509    /// called by the Element so we know what style we were most recently rendered with.
12510    pub(crate) fn set_style(
12511        &mut self,
12512        style: EditorStyle,
12513        window: &mut Window,
12514        cx: &mut Context<Self>,
12515    ) {
12516        let rem_size = window.rem_size();
12517        self.display_map.update(cx, |map, cx| {
12518            map.set_font(
12519                style.text.font(),
12520                style.text.font_size.to_pixels(rem_size),
12521                cx,
12522            )
12523        });
12524        self.style = Some(style);
12525    }
12526
12527    pub fn style(&self) -> Option<&EditorStyle> {
12528        self.style.as_ref()
12529    }
12530
12531    // Called by the element. This method is not designed to be called outside of the editor
12532    // element's layout code because it does not notify when rewrapping is computed synchronously.
12533    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut App) -> bool {
12534        self.display_map
12535            .update(cx, |map, cx| map.set_wrap_width(width, cx))
12536    }
12537
12538    pub fn set_soft_wrap(&mut self) {
12539        self.soft_wrap_mode_override = Some(language_settings::SoftWrap::EditorWidth)
12540    }
12541
12542    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, _: &mut Window, cx: &mut Context<Self>) {
12543        if self.soft_wrap_mode_override.is_some() {
12544            self.soft_wrap_mode_override.take();
12545        } else {
12546            let soft_wrap = match self.soft_wrap_mode(cx) {
12547                SoftWrap::GitDiff => return,
12548                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
12549                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
12550                    language_settings::SoftWrap::None
12551                }
12552            };
12553            self.soft_wrap_mode_override = Some(soft_wrap);
12554        }
12555        cx.notify();
12556    }
12557
12558    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, _: &mut Window, cx: &mut Context<Self>) {
12559        let Some(workspace) = self.workspace() else {
12560            return;
12561        };
12562        let fs = workspace.read(cx).app_state().fs.clone();
12563        let current_show = TabBarSettings::get_global(cx).show;
12564        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
12565            setting.show = Some(!current_show);
12566        });
12567    }
12568
12569    pub fn toggle_indent_guides(
12570        &mut self,
12571        _: &ToggleIndentGuides,
12572        _: &mut Window,
12573        cx: &mut Context<Self>,
12574    ) {
12575        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
12576            self.buffer
12577                .read(cx)
12578                .settings_at(0, cx)
12579                .indent_guides
12580                .enabled
12581        });
12582        self.show_indent_guides = Some(!currently_enabled);
12583        cx.notify();
12584    }
12585
12586    fn should_show_indent_guides(&self) -> Option<bool> {
12587        self.show_indent_guides
12588    }
12589
12590    pub fn toggle_line_numbers(
12591        &mut self,
12592        _: &ToggleLineNumbers,
12593        _: &mut Window,
12594        cx: &mut Context<Self>,
12595    ) {
12596        let mut editor_settings = EditorSettings::get_global(cx).clone();
12597        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
12598        EditorSettings::override_global(editor_settings, cx);
12599    }
12600
12601    pub fn should_use_relative_line_numbers(&self, cx: &mut App) -> bool {
12602        self.use_relative_line_numbers
12603            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
12604    }
12605
12606    pub fn toggle_relative_line_numbers(
12607        &mut self,
12608        _: &ToggleRelativeLineNumbers,
12609        _: &mut Window,
12610        cx: &mut Context<Self>,
12611    ) {
12612        let is_relative = self.should_use_relative_line_numbers(cx);
12613        self.set_relative_line_number(Some(!is_relative), cx)
12614    }
12615
12616    pub fn set_relative_line_number(&mut self, is_relative: Option<bool>, cx: &mut Context<Self>) {
12617        self.use_relative_line_numbers = is_relative;
12618        cx.notify();
12619    }
12620
12621    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut Context<Self>) {
12622        self.show_gutter = show_gutter;
12623        cx.notify();
12624    }
12625
12626    pub fn set_show_scrollbars(&mut self, show_scrollbars: bool, cx: &mut Context<Self>) {
12627        self.show_scrollbars = show_scrollbars;
12628        cx.notify();
12629    }
12630
12631    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut Context<Self>) {
12632        self.show_line_numbers = Some(show_line_numbers);
12633        cx.notify();
12634    }
12635
12636    pub fn set_show_git_diff_gutter(&mut self, show_git_diff_gutter: bool, cx: &mut Context<Self>) {
12637        self.show_git_diff_gutter = Some(show_git_diff_gutter);
12638        cx.notify();
12639    }
12640
12641    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut Context<Self>) {
12642        self.show_code_actions = Some(show_code_actions);
12643        cx.notify();
12644    }
12645
12646    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut Context<Self>) {
12647        self.show_runnables = Some(show_runnables);
12648        cx.notify();
12649    }
12650
12651    pub fn set_masked(&mut self, masked: bool, cx: &mut Context<Self>) {
12652        if self.display_map.read(cx).masked != masked {
12653            self.display_map.update(cx, |map, _| map.masked = masked);
12654        }
12655        cx.notify()
12656    }
12657
12658    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut Context<Self>) {
12659        self.show_wrap_guides = Some(show_wrap_guides);
12660        cx.notify();
12661    }
12662
12663    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut Context<Self>) {
12664        self.show_indent_guides = Some(show_indent_guides);
12665        cx.notify();
12666    }
12667
12668    pub fn working_directory(&self, cx: &App) -> Option<PathBuf> {
12669        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
12670            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
12671                if let Some(dir) = file.abs_path(cx).parent() {
12672                    return Some(dir.to_owned());
12673                }
12674            }
12675
12676            if let Some(project_path) = buffer.read(cx).project_path(cx) {
12677                return Some(project_path.path.to_path_buf());
12678            }
12679        }
12680
12681        None
12682    }
12683
12684    fn target_file<'a>(&self, cx: &'a App) -> Option<&'a dyn language::LocalFile> {
12685        self.active_excerpt(cx)?
12686            .1
12687            .read(cx)
12688            .file()
12689            .and_then(|f| f.as_local())
12690    }
12691
12692    fn target_file_abs_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12693        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12694            let project_path = buffer.read(cx).project_path(cx)?;
12695            let project = self.project.as_ref()?.read(cx);
12696            project.absolute_path(&project_path, cx)
12697        })
12698    }
12699
12700    fn target_file_path(&self, cx: &mut Context<Self>) -> Option<PathBuf> {
12701        self.active_excerpt(cx).and_then(|(_, buffer, _)| {
12702            let project_path = buffer.read(cx).project_path(cx)?;
12703            let project = self.project.as_ref()?.read(cx);
12704            let entry = project.entry_for_path(&project_path, cx)?;
12705            let path = entry.path.to_path_buf();
12706            Some(path)
12707        })
12708    }
12709
12710    pub fn reveal_in_finder(
12711        &mut self,
12712        _: &RevealInFileManager,
12713        _window: &mut Window,
12714        cx: &mut Context<Self>,
12715    ) {
12716        if let Some(target) = self.target_file(cx) {
12717            cx.reveal_path(&target.abs_path(cx));
12718        }
12719    }
12720
12721    pub fn copy_path(&mut self, _: &CopyPath, _window: &mut Window, cx: &mut Context<Self>) {
12722        if let Some(path) = self.target_file_abs_path(cx) {
12723            if let Some(path) = path.to_str() {
12724                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12725            }
12726        }
12727    }
12728
12729    pub fn copy_relative_path(
12730        &mut self,
12731        _: &CopyRelativePath,
12732        _window: &mut Window,
12733        cx: &mut Context<Self>,
12734    ) {
12735        if let Some(path) = self.target_file_path(cx) {
12736            if let Some(path) = path.to_str() {
12737                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
12738            }
12739        }
12740    }
12741
12742    pub fn toggle_git_blame(
12743        &mut self,
12744        _: &ToggleGitBlame,
12745        window: &mut Window,
12746        cx: &mut Context<Self>,
12747    ) {
12748        self.show_git_blame_gutter = !self.show_git_blame_gutter;
12749
12750        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
12751            self.start_git_blame(true, window, cx);
12752        }
12753
12754        cx.notify();
12755    }
12756
12757    pub fn toggle_git_blame_inline(
12758        &mut self,
12759        _: &ToggleGitBlameInline,
12760        window: &mut Window,
12761        cx: &mut Context<Self>,
12762    ) {
12763        self.toggle_git_blame_inline_internal(true, window, cx);
12764        cx.notify();
12765    }
12766
12767    pub fn git_blame_inline_enabled(&self) -> bool {
12768        self.git_blame_inline_enabled
12769    }
12770
12771    pub fn toggle_selection_menu(
12772        &mut self,
12773        _: &ToggleSelectionMenu,
12774        _: &mut Window,
12775        cx: &mut Context<Self>,
12776    ) {
12777        self.show_selection_menu = self
12778            .show_selection_menu
12779            .map(|show_selections_menu| !show_selections_menu)
12780            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
12781
12782        cx.notify();
12783    }
12784
12785    pub fn selection_menu_enabled(&self, cx: &App) -> bool {
12786        self.show_selection_menu
12787            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
12788    }
12789
12790    fn start_git_blame(
12791        &mut self,
12792        user_triggered: bool,
12793        window: &mut Window,
12794        cx: &mut Context<Self>,
12795    ) {
12796        if let Some(project) = self.project.as_ref() {
12797            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
12798                return;
12799            };
12800
12801            if buffer.read(cx).file().is_none() {
12802                return;
12803            }
12804
12805            let focused = self.focus_handle(cx).contains_focused(window, cx);
12806
12807            let project = project.clone();
12808            let blame = cx.new(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
12809            self.blame_subscription =
12810                Some(cx.observe_in(&blame, window, |_, _, _, cx| cx.notify()));
12811            self.blame = Some(blame);
12812        }
12813    }
12814
12815    fn toggle_git_blame_inline_internal(
12816        &mut self,
12817        user_triggered: bool,
12818        window: &mut Window,
12819        cx: &mut Context<Self>,
12820    ) {
12821        if self.git_blame_inline_enabled {
12822            self.git_blame_inline_enabled = false;
12823            self.show_git_blame_inline = false;
12824            self.show_git_blame_inline_delay_task.take();
12825        } else {
12826            self.git_blame_inline_enabled = true;
12827            self.start_git_blame_inline(user_triggered, window, cx);
12828        }
12829
12830        cx.notify();
12831    }
12832
12833    fn start_git_blame_inline(
12834        &mut self,
12835        user_triggered: bool,
12836        window: &mut Window,
12837        cx: &mut Context<Self>,
12838    ) {
12839        self.start_git_blame(user_triggered, window, cx);
12840
12841        if ProjectSettings::get_global(cx)
12842            .git
12843            .inline_blame_delay()
12844            .is_some()
12845        {
12846            self.start_inline_blame_timer(window, cx);
12847        } else {
12848            self.show_git_blame_inline = true
12849        }
12850    }
12851
12852    pub fn blame(&self) -> Option<&Entity<GitBlame>> {
12853        self.blame.as_ref()
12854    }
12855
12856    pub fn show_git_blame_gutter(&self) -> bool {
12857        self.show_git_blame_gutter
12858    }
12859
12860    pub fn render_git_blame_gutter(&self, cx: &App) -> bool {
12861        self.show_git_blame_gutter && self.has_blame_entries(cx)
12862    }
12863
12864    pub fn render_git_blame_inline(&self, window: &Window, cx: &App) -> bool {
12865        self.show_git_blame_inline
12866            && self.focus_handle.is_focused(window)
12867            && !self.newest_selection_head_on_empty_line(cx)
12868            && self.has_blame_entries(cx)
12869    }
12870
12871    fn has_blame_entries(&self, cx: &App) -> bool {
12872        self.blame()
12873            .map_or(false, |blame| blame.read(cx).has_generated_entries())
12874    }
12875
12876    fn newest_selection_head_on_empty_line(&self, cx: &App) -> bool {
12877        let cursor_anchor = self.selections.newest_anchor().head();
12878
12879        let snapshot = self.buffer.read(cx).snapshot(cx);
12880        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
12881
12882        snapshot.line_len(buffer_row) == 0
12883    }
12884
12885    fn get_permalink_to_line(&self, cx: &mut Context<Self>) -> Task<Result<url::Url>> {
12886        let buffer_and_selection = maybe!({
12887            let selection = self.selections.newest::<Point>(cx);
12888            let selection_range = selection.range();
12889
12890            let multi_buffer = self.buffer().read(cx);
12891            let multi_buffer_snapshot = multi_buffer.snapshot(cx);
12892            let buffer_ranges = multi_buffer_snapshot.range_to_buffer_ranges(selection_range);
12893
12894            let (buffer, range, _) = if selection.reversed {
12895                buffer_ranges.first()
12896            } else {
12897                buffer_ranges.last()
12898            }?;
12899
12900            let selection = text::ToPoint::to_point(&range.start, &buffer).row
12901                ..text::ToPoint::to_point(&range.end, &buffer).row;
12902            Some((
12903                multi_buffer.buffer(buffer.remote_id()).unwrap().clone(),
12904                selection,
12905            ))
12906        });
12907
12908        let Some((buffer, selection)) = buffer_and_selection else {
12909            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
12910        };
12911
12912        let Some(project) = self.project.as_ref() else {
12913            return Task::ready(Err(anyhow!("editor does not have project")));
12914        };
12915
12916        project.update(cx, |project, cx| {
12917            project.get_permalink_to_line(&buffer, selection, cx)
12918        })
12919    }
12920
12921    pub fn copy_permalink_to_line(
12922        &mut self,
12923        _: &CopyPermalinkToLine,
12924        window: &mut Window,
12925        cx: &mut Context<Self>,
12926    ) {
12927        let permalink_task = self.get_permalink_to_line(cx);
12928        let workspace = self.workspace();
12929
12930        cx.spawn_in(window, |_, mut cx| async move {
12931            match permalink_task.await {
12932                Ok(permalink) => {
12933                    cx.update(|_, cx| {
12934                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
12935                    })
12936                    .ok();
12937                }
12938                Err(err) => {
12939                    let message = format!("Failed to copy permalink: {err}");
12940
12941                    Err::<(), anyhow::Error>(err).log_err();
12942
12943                    if let Some(workspace) = workspace {
12944                        workspace
12945                            .update_in(&mut cx, |workspace, _, cx| {
12946                                struct CopyPermalinkToLine;
12947
12948                                workspace.show_toast(
12949                                    Toast::new(
12950                                        NotificationId::unique::<CopyPermalinkToLine>(),
12951                                        message,
12952                                    ),
12953                                    cx,
12954                                )
12955                            })
12956                            .ok();
12957                    }
12958                }
12959            }
12960        })
12961        .detach();
12962    }
12963
12964    pub fn copy_file_location(
12965        &mut self,
12966        _: &CopyFileLocation,
12967        _: &mut Window,
12968        cx: &mut Context<Self>,
12969    ) {
12970        let selection = self.selections.newest::<Point>(cx).start.row + 1;
12971        if let Some(file) = self.target_file(cx) {
12972            if let Some(path) = file.path().to_str() {
12973                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
12974            }
12975        }
12976    }
12977
12978    pub fn open_permalink_to_line(
12979        &mut self,
12980        _: &OpenPermalinkToLine,
12981        window: &mut Window,
12982        cx: &mut Context<Self>,
12983    ) {
12984        let permalink_task = self.get_permalink_to_line(cx);
12985        let workspace = self.workspace();
12986
12987        cx.spawn_in(window, |_, mut cx| async move {
12988            match permalink_task.await {
12989                Ok(permalink) => {
12990                    cx.update(|_, cx| {
12991                        cx.open_url(permalink.as_ref());
12992                    })
12993                    .ok();
12994                }
12995                Err(err) => {
12996                    let message = format!("Failed to open permalink: {err}");
12997
12998                    Err::<(), anyhow::Error>(err).log_err();
12999
13000                    if let Some(workspace) = workspace {
13001                        workspace
13002                            .update(&mut cx, |workspace, cx| {
13003                                struct OpenPermalinkToLine;
13004
13005                                workspace.show_toast(
13006                                    Toast::new(
13007                                        NotificationId::unique::<OpenPermalinkToLine>(),
13008                                        message,
13009                                    ),
13010                                    cx,
13011                                )
13012                            })
13013                            .ok();
13014                    }
13015                }
13016            }
13017        })
13018        .detach();
13019    }
13020
13021    pub fn insert_uuid_v4(
13022        &mut self,
13023        _: &InsertUuidV4,
13024        window: &mut Window,
13025        cx: &mut Context<Self>,
13026    ) {
13027        self.insert_uuid(UuidVersion::V4, window, cx);
13028    }
13029
13030    pub fn insert_uuid_v7(
13031        &mut self,
13032        _: &InsertUuidV7,
13033        window: &mut Window,
13034        cx: &mut Context<Self>,
13035    ) {
13036        self.insert_uuid(UuidVersion::V7, window, cx);
13037    }
13038
13039    fn insert_uuid(&mut self, version: UuidVersion, window: &mut Window, cx: &mut Context<Self>) {
13040        self.transact(window, cx, |this, window, cx| {
13041            let edits = this
13042                .selections
13043                .all::<Point>(cx)
13044                .into_iter()
13045                .map(|selection| {
13046                    let uuid = match version {
13047                        UuidVersion::V4 => uuid::Uuid::new_v4(),
13048                        UuidVersion::V7 => uuid::Uuid::now_v7(),
13049                    };
13050
13051                    (selection.range(), uuid.to_string())
13052                });
13053            this.edit(edits, cx);
13054            this.refresh_inline_completion(true, false, window, cx);
13055        });
13056    }
13057
13058    pub fn open_selections_in_multibuffer(
13059        &mut self,
13060        _: &OpenSelectionsInMultibuffer,
13061        window: &mut Window,
13062        cx: &mut Context<Self>,
13063    ) {
13064        let multibuffer = self.buffer.read(cx);
13065
13066        let Some(buffer) = multibuffer.as_singleton() else {
13067            return;
13068        };
13069
13070        let Some(workspace) = self.workspace() else {
13071            return;
13072        };
13073
13074        let locations = self
13075            .selections
13076            .disjoint_anchors()
13077            .iter()
13078            .map(|range| Location {
13079                buffer: buffer.clone(),
13080                range: range.start.text_anchor..range.end.text_anchor,
13081            })
13082            .collect::<Vec<_>>();
13083
13084        let title = multibuffer.title(cx).to_string();
13085
13086        cx.spawn_in(window, |_, mut cx| async move {
13087            workspace.update_in(&mut cx, |workspace, window, cx| {
13088                Self::open_locations_in_multibuffer(
13089                    workspace,
13090                    locations,
13091                    format!("Selections for '{title}'"),
13092                    false,
13093                    MultibufferSelectionMode::All,
13094                    window,
13095                    cx,
13096                );
13097            })
13098        })
13099        .detach();
13100    }
13101
13102    /// Adds a row highlight for the given range. If a row has multiple highlights, the
13103    /// last highlight added will be used.
13104    ///
13105    /// If the range ends at the beginning of a line, then that line will not be highlighted.
13106    pub fn highlight_rows<T: 'static>(
13107        &mut self,
13108        range: Range<Anchor>,
13109        color: Hsla,
13110        should_autoscroll: bool,
13111        cx: &mut Context<Self>,
13112    ) {
13113        let snapshot = self.buffer().read(cx).snapshot(cx);
13114        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13115        let ix = row_highlights.binary_search_by(|highlight| {
13116            Ordering::Equal
13117                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
13118                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
13119        });
13120
13121        if let Err(mut ix) = ix {
13122            let index = post_inc(&mut self.highlight_order);
13123
13124            // If this range intersects with the preceding highlight, then merge it with
13125            // the preceding highlight. Otherwise insert a new highlight.
13126            let mut merged = false;
13127            if ix > 0 {
13128                let prev_highlight = &mut row_highlights[ix - 1];
13129                if prev_highlight
13130                    .range
13131                    .end
13132                    .cmp(&range.start, &snapshot)
13133                    .is_ge()
13134                {
13135                    ix -= 1;
13136                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
13137                        prev_highlight.range.end = range.end;
13138                    }
13139                    merged = true;
13140                    prev_highlight.index = index;
13141                    prev_highlight.color = color;
13142                    prev_highlight.should_autoscroll = should_autoscroll;
13143                }
13144            }
13145
13146            if !merged {
13147                row_highlights.insert(
13148                    ix,
13149                    RowHighlight {
13150                        range: range.clone(),
13151                        index,
13152                        color,
13153                        should_autoscroll,
13154                    },
13155                );
13156            }
13157
13158            // If any of the following highlights intersect with this one, merge them.
13159            while let Some(next_highlight) = row_highlights.get(ix + 1) {
13160                let highlight = &row_highlights[ix];
13161                if next_highlight
13162                    .range
13163                    .start
13164                    .cmp(&highlight.range.end, &snapshot)
13165                    .is_le()
13166                {
13167                    if next_highlight
13168                        .range
13169                        .end
13170                        .cmp(&highlight.range.end, &snapshot)
13171                        .is_gt()
13172                    {
13173                        row_highlights[ix].range.end = next_highlight.range.end;
13174                    }
13175                    row_highlights.remove(ix + 1);
13176                } else {
13177                    break;
13178                }
13179            }
13180        }
13181    }
13182
13183    /// Remove any highlighted row ranges of the given type that intersect the
13184    /// given ranges.
13185    pub fn remove_highlighted_rows<T: 'static>(
13186        &mut self,
13187        ranges_to_remove: Vec<Range<Anchor>>,
13188        cx: &mut Context<Self>,
13189    ) {
13190        let snapshot = self.buffer().read(cx).snapshot(cx);
13191        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
13192        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
13193        row_highlights.retain(|highlight| {
13194            while let Some(range_to_remove) = ranges_to_remove.peek() {
13195                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
13196                    Ordering::Less | Ordering::Equal => {
13197                        ranges_to_remove.next();
13198                    }
13199                    Ordering::Greater => {
13200                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
13201                            Ordering::Less | Ordering::Equal => {
13202                                return false;
13203                            }
13204                            Ordering::Greater => break,
13205                        }
13206                    }
13207                }
13208            }
13209
13210            true
13211        })
13212    }
13213
13214    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
13215    pub fn clear_row_highlights<T: 'static>(&mut self) {
13216        self.highlighted_rows.remove(&TypeId::of::<T>());
13217    }
13218
13219    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
13220    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
13221        self.highlighted_rows
13222            .get(&TypeId::of::<T>())
13223            .map_or(&[] as &[_], |vec| vec.as_slice())
13224            .iter()
13225            .map(|highlight| (highlight.range.clone(), highlight.color))
13226    }
13227
13228    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
13229    /// Returns a map of display rows that are highlighted and their corresponding highlight color.
13230    /// Allows to ignore certain kinds of highlights.
13231    pub fn highlighted_display_rows(
13232        &self,
13233        window: &mut Window,
13234        cx: &mut App,
13235    ) -> BTreeMap<DisplayRow, Hsla> {
13236        let snapshot = self.snapshot(window, cx);
13237        let mut used_highlight_orders = HashMap::default();
13238        self.highlighted_rows
13239            .iter()
13240            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
13241            .fold(
13242                BTreeMap::<DisplayRow, Hsla>::new(),
13243                |mut unique_rows, highlight| {
13244                    let start = highlight.range.start.to_display_point(&snapshot);
13245                    let end = highlight.range.end.to_display_point(&snapshot);
13246                    let start_row = start.row().0;
13247                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
13248                        && end.column() == 0
13249                    {
13250                        end.row().0.saturating_sub(1)
13251                    } else {
13252                        end.row().0
13253                    };
13254                    for row in start_row..=end_row {
13255                        let used_index =
13256                            used_highlight_orders.entry(row).or_insert(highlight.index);
13257                        if highlight.index >= *used_index {
13258                            *used_index = highlight.index;
13259                            unique_rows.insert(DisplayRow(row), highlight.color);
13260                        }
13261                    }
13262                    unique_rows
13263                },
13264            )
13265    }
13266
13267    pub fn highlighted_display_row_for_autoscroll(
13268        &self,
13269        snapshot: &DisplaySnapshot,
13270    ) -> Option<DisplayRow> {
13271        self.highlighted_rows
13272            .values()
13273            .flat_map(|highlighted_rows| highlighted_rows.iter())
13274            .filter_map(|highlight| {
13275                if highlight.should_autoscroll {
13276                    Some(highlight.range.start.to_display_point(snapshot).row())
13277                } else {
13278                    None
13279                }
13280            })
13281            .min()
13282    }
13283
13284    pub fn set_search_within_ranges(&mut self, ranges: &[Range<Anchor>], cx: &mut Context<Self>) {
13285        self.highlight_background::<SearchWithinRange>(
13286            ranges,
13287            |colors| colors.editor_document_highlight_read_background,
13288            cx,
13289        )
13290    }
13291
13292    pub fn set_breadcrumb_header(&mut self, new_header: String) {
13293        self.breadcrumb_header = Some(new_header);
13294    }
13295
13296    pub fn clear_search_within_ranges(&mut self, cx: &mut Context<Self>) {
13297        self.clear_background_highlights::<SearchWithinRange>(cx);
13298    }
13299
13300    pub fn highlight_background<T: 'static>(
13301        &mut self,
13302        ranges: &[Range<Anchor>],
13303        color_fetcher: fn(&ThemeColors) -> Hsla,
13304        cx: &mut Context<Self>,
13305    ) {
13306        self.background_highlights
13307            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13308        self.scrollbar_marker_state.dirty = true;
13309        cx.notify();
13310    }
13311
13312    pub fn clear_background_highlights<T: 'static>(
13313        &mut self,
13314        cx: &mut Context<Self>,
13315    ) -> Option<BackgroundHighlight> {
13316        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
13317        if !text_highlights.1.is_empty() {
13318            self.scrollbar_marker_state.dirty = true;
13319            cx.notify();
13320        }
13321        Some(text_highlights)
13322    }
13323
13324    pub fn highlight_gutter<T: 'static>(
13325        &mut self,
13326        ranges: &[Range<Anchor>],
13327        color_fetcher: fn(&App) -> Hsla,
13328        cx: &mut Context<Self>,
13329    ) {
13330        self.gutter_highlights
13331            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
13332        cx.notify();
13333    }
13334
13335    pub fn clear_gutter_highlights<T: 'static>(
13336        &mut self,
13337        cx: &mut Context<Self>,
13338    ) -> Option<GutterHighlight> {
13339        cx.notify();
13340        self.gutter_highlights.remove(&TypeId::of::<T>())
13341    }
13342
13343    #[cfg(feature = "test-support")]
13344    pub fn all_text_background_highlights(
13345        &self,
13346        window: &mut Window,
13347        cx: &mut Context<Self>,
13348    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13349        let snapshot = self.snapshot(window, cx);
13350        let buffer = &snapshot.buffer_snapshot;
13351        let start = buffer.anchor_before(0);
13352        let end = buffer.anchor_after(buffer.len());
13353        let theme = cx.theme().colors();
13354        self.background_highlights_in_range(start..end, &snapshot, theme)
13355    }
13356
13357    #[cfg(feature = "test-support")]
13358    pub fn search_background_highlights(&mut self, cx: &mut Context<Self>) -> Vec<Range<Point>> {
13359        let snapshot = self.buffer().read(cx).snapshot(cx);
13360
13361        let highlights = self
13362            .background_highlights
13363            .get(&TypeId::of::<items::BufferSearchHighlights>());
13364
13365        if let Some((_color, ranges)) = highlights {
13366            ranges
13367                .iter()
13368                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
13369                .collect_vec()
13370        } else {
13371            vec![]
13372        }
13373    }
13374
13375    fn document_highlights_for_position<'a>(
13376        &'a self,
13377        position: Anchor,
13378        buffer: &'a MultiBufferSnapshot,
13379    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
13380        let read_highlights = self
13381            .background_highlights
13382            .get(&TypeId::of::<DocumentHighlightRead>())
13383            .map(|h| &h.1);
13384        let write_highlights = self
13385            .background_highlights
13386            .get(&TypeId::of::<DocumentHighlightWrite>())
13387            .map(|h| &h.1);
13388        let left_position = position.bias_left(buffer);
13389        let right_position = position.bias_right(buffer);
13390        read_highlights
13391            .into_iter()
13392            .chain(write_highlights)
13393            .flat_map(move |ranges| {
13394                let start_ix = match ranges.binary_search_by(|probe| {
13395                    let cmp = probe.end.cmp(&left_position, buffer);
13396                    if cmp.is_ge() {
13397                        Ordering::Greater
13398                    } else {
13399                        Ordering::Less
13400                    }
13401                }) {
13402                    Ok(i) | Err(i) => i,
13403                };
13404
13405                ranges[start_ix..]
13406                    .iter()
13407                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
13408            })
13409    }
13410
13411    pub fn has_background_highlights<T: 'static>(&self) -> bool {
13412        self.background_highlights
13413            .get(&TypeId::of::<T>())
13414            .map_or(false, |(_, highlights)| !highlights.is_empty())
13415    }
13416
13417    pub fn background_highlights_in_range(
13418        &self,
13419        search_range: Range<Anchor>,
13420        display_snapshot: &DisplaySnapshot,
13421        theme: &ThemeColors,
13422    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13423        let mut results = Vec::new();
13424        for (color_fetcher, ranges) in self.background_highlights.values() {
13425            let color = color_fetcher(theme);
13426            let start_ix = match ranges.binary_search_by(|probe| {
13427                let cmp = probe
13428                    .end
13429                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13430                if cmp.is_gt() {
13431                    Ordering::Greater
13432                } else {
13433                    Ordering::Less
13434                }
13435            }) {
13436                Ok(i) | Err(i) => i,
13437            };
13438            for range in &ranges[start_ix..] {
13439                if range
13440                    .start
13441                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13442                    .is_ge()
13443                {
13444                    break;
13445                }
13446
13447                let start = range.start.to_display_point(display_snapshot);
13448                let end = range.end.to_display_point(display_snapshot);
13449                results.push((start..end, color))
13450            }
13451        }
13452        results
13453    }
13454
13455    pub fn background_highlight_row_ranges<T: 'static>(
13456        &self,
13457        search_range: Range<Anchor>,
13458        display_snapshot: &DisplaySnapshot,
13459        count: usize,
13460    ) -> Vec<RangeInclusive<DisplayPoint>> {
13461        let mut results = Vec::new();
13462        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
13463            return vec![];
13464        };
13465
13466        let start_ix = match ranges.binary_search_by(|probe| {
13467            let cmp = probe
13468                .end
13469                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13470            if cmp.is_gt() {
13471                Ordering::Greater
13472            } else {
13473                Ordering::Less
13474            }
13475        }) {
13476            Ok(i) | Err(i) => i,
13477        };
13478        let mut push_region = |start: Option<Point>, end: Option<Point>| {
13479            if let (Some(start_display), Some(end_display)) = (start, end) {
13480                results.push(
13481                    start_display.to_display_point(display_snapshot)
13482                        ..=end_display.to_display_point(display_snapshot),
13483                );
13484            }
13485        };
13486        let mut start_row: Option<Point> = None;
13487        let mut end_row: Option<Point> = None;
13488        if ranges.len() > count {
13489            return Vec::new();
13490        }
13491        for range in &ranges[start_ix..] {
13492            if range
13493                .start
13494                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13495                .is_ge()
13496            {
13497                break;
13498            }
13499            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
13500            if let Some(current_row) = &end_row {
13501                if end.row == current_row.row {
13502                    continue;
13503                }
13504            }
13505            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
13506            if start_row.is_none() {
13507                assert_eq!(end_row, None);
13508                start_row = Some(start);
13509                end_row = Some(end);
13510                continue;
13511            }
13512            if let Some(current_end) = end_row.as_mut() {
13513                if start.row > current_end.row + 1 {
13514                    push_region(start_row, end_row);
13515                    start_row = Some(start);
13516                    end_row = Some(end);
13517                } else {
13518                    // Merge two hunks.
13519                    *current_end = end;
13520                }
13521            } else {
13522                unreachable!();
13523            }
13524        }
13525        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
13526        push_region(start_row, end_row);
13527        results
13528    }
13529
13530    pub fn gutter_highlights_in_range(
13531        &self,
13532        search_range: Range<Anchor>,
13533        display_snapshot: &DisplaySnapshot,
13534        cx: &App,
13535    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
13536        let mut results = Vec::new();
13537        for (color_fetcher, ranges) in self.gutter_highlights.values() {
13538            let color = color_fetcher(cx);
13539            let start_ix = match ranges.binary_search_by(|probe| {
13540                let cmp = probe
13541                    .end
13542                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
13543                if cmp.is_gt() {
13544                    Ordering::Greater
13545                } else {
13546                    Ordering::Less
13547                }
13548            }) {
13549                Ok(i) | Err(i) => i,
13550            };
13551            for range in &ranges[start_ix..] {
13552                if range
13553                    .start
13554                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
13555                    .is_ge()
13556                {
13557                    break;
13558                }
13559
13560                let start = range.start.to_display_point(display_snapshot);
13561                let end = range.end.to_display_point(display_snapshot);
13562                results.push((start..end, color))
13563            }
13564        }
13565        results
13566    }
13567
13568    /// Get the text ranges corresponding to the redaction query
13569    pub fn redacted_ranges(
13570        &self,
13571        search_range: Range<Anchor>,
13572        display_snapshot: &DisplaySnapshot,
13573        cx: &App,
13574    ) -> Vec<Range<DisplayPoint>> {
13575        display_snapshot
13576            .buffer_snapshot
13577            .redacted_ranges(search_range, |file| {
13578                if let Some(file) = file {
13579                    file.is_private()
13580                        && EditorSettings::get(
13581                            Some(SettingsLocation {
13582                                worktree_id: file.worktree_id(cx),
13583                                path: file.path().as_ref(),
13584                            }),
13585                            cx,
13586                        )
13587                        .redact_private_values
13588                } else {
13589                    false
13590                }
13591            })
13592            .map(|range| {
13593                range.start.to_display_point(display_snapshot)
13594                    ..range.end.to_display_point(display_snapshot)
13595            })
13596            .collect()
13597    }
13598
13599    pub fn highlight_text<T: 'static>(
13600        &mut self,
13601        ranges: Vec<Range<Anchor>>,
13602        style: HighlightStyle,
13603        cx: &mut Context<Self>,
13604    ) {
13605        self.display_map.update(cx, |map, _| {
13606            map.highlight_text(TypeId::of::<T>(), ranges, style)
13607        });
13608        cx.notify();
13609    }
13610
13611    pub(crate) fn highlight_inlays<T: 'static>(
13612        &mut self,
13613        highlights: Vec<InlayHighlight>,
13614        style: HighlightStyle,
13615        cx: &mut Context<Self>,
13616    ) {
13617        self.display_map.update(cx, |map, _| {
13618            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
13619        });
13620        cx.notify();
13621    }
13622
13623    pub fn text_highlights<'a, T: 'static>(
13624        &'a self,
13625        cx: &'a App,
13626    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
13627        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
13628    }
13629
13630    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut Context<Self>) {
13631        let cleared = self
13632            .display_map
13633            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
13634        if cleared {
13635            cx.notify();
13636        }
13637    }
13638
13639    pub fn show_local_cursors(&self, window: &mut Window, cx: &mut App) -> bool {
13640        (self.read_only(cx) || self.blink_manager.read(cx).visible())
13641            && self.focus_handle.is_focused(window)
13642    }
13643
13644    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut Context<Self>) {
13645        self.show_cursor_when_unfocused = is_enabled;
13646        cx.notify();
13647    }
13648
13649    pub fn lsp_store(&self, cx: &App) -> Option<Entity<LspStore>> {
13650        self.project
13651            .as_ref()
13652            .map(|project| project.read(cx).lsp_store())
13653    }
13654
13655    fn on_buffer_changed(&mut self, _: Entity<MultiBuffer>, cx: &mut Context<Self>) {
13656        cx.notify();
13657    }
13658
13659    fn on_buffer_event(
13660        &mut self,
13661        multibuffer: &Entity<MultiBuffer>,
13662        event: &multi_buffer::Event,
13663        window: &mut Window,
13664        cx: &mut Context<Self>,
13665    ) {
13666        match event {
13667            multi_buffer::Event::Edited {
13668                singleton_buffer_edited,
13669                edited_buffer: buffer_edited,
13670            } => {
13671                self.scrollbar_marker_state.dirty = true;
13672                self.active_indent_guides_state.dirty = true;
13673                self.refresh_active_diagnostics(cx);
13674                self.refresh_code_actions(window, cx);
13675                if self.has_active_inline_completion() {
13676                    self.update_visible_inline_completion(window, cx);
13677                }
13678                if let Some(buffer) = buffer_edited {
13679                    let buffer_id = buffer.read(cx).remote_id();
13680                    if !self.registered_buffers.contains_key(&buffer_id) {
13681                        if let Some(lsp_store) = self.lsp_store(cx) {
13682                            lsp_store.update(cx, |lsp_store, cx| {
13683                                self.registered_buffers.insert(
13684                                    buffer_id,
13685                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
13686                                );
13687                            })
13688                        }
13689                    }
13690                }
13691                cx.emit(EditorEvent::BufferEdited);
13692                cx.emit(SearchEvent::MatchesInvalidated);
13693                if *singleton_buffer_edited {
13694                    if let Some(project) = &self.project {
13695                        let project = project.read(cx);
13696                        #[allow(clippy::mutable_key_type)]
13697                        let languages_affected = multibuffer
13698                            .read(cx)
13699                            .all_buffers()
13700                            .into_iter()
13701                            .filter_map(|buffer| {
13702                                let buffer = buffer.read(cx);
13703                                let language = buffer.language()?;
13704                                if project.is_local()
13705                                    && project
13706                                        .language_servers_for_local_buffer(buffer, cx)
13707                                        .count()
13708                                        == 0
13709                                {
13710                                    None
13711                                } else {
13712                                    Some(language)
13713                                }
13714                            })
13715                            .cloned()
13716                            .collect::<HashSet<_>>();
13717                        if !languages_affected.is_empty() {
13718                            self.refresh_inlay_hints(
13719                                InlayHintRefreshReason::BufferEdited(languages_affected),
13720                                cx,
13721                            );
13722                        }
13723                    }
13724                }
13725
13726                let Some(project) = &self.project else { return };
13727                let (telemetry, is_via_ssh) = {
13728                    let project = project.read(cx);
13729                    let telemetry = project.client().telemetry().clone();
13730                    let is_via_ssh = project.is_via_ssh();
13731                    (telemetry, is_via_ssh)
13732                };
13733                refresh_linked_ranges(self, window, cx);
13734                telemetry.log_edit_event("editor", is_via_ssh);
13735            }
13736            multi_buffer::Event::ExcerptsAdded {
13737                buffer,
13738                predecessor,
13739                excerpts,
13740            } => {
13741                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13742                let buffer_id = buffer.read(cx).remote_id();
13743                if self.buffer.read(cx).diff_for(buffer_id).is_none() {
13744                    if let Some(project) = &self.project {
13745                        get_uncommitted_diff_for_buffer(
13746                            project,
13747                            [buffer.clone()],
13748                            self.buffer.clone(),
13749                            cx,
13750                        );
13751                    }
13752                }
13753                cx.emit(EditorEvent::ExcerptsAdded {
13754                    buffer: buffer.clone(),
13755                    predecessor: *predecessor,
13756                    excerpts: excerpts.clone(),
13757                });
13758                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13759            }
13760            multi_buffer::Event::ExcerptsRemoved { ids } => {
13761                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
13762                let buffer = self.buffer.read(cx);
13763                self.registered_buffers
13764                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
13765                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
13766            }
13767            multi_buffer::Event::ExcerptsEdited { ids } => {
13768                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
13769            }
13770            multi_buffer::Event::ExcerptsExpanded { ids } => {
13771                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
13772                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
13773            }
13774            multi_buffer::Event::Reparsed(buffer_id) => {
13775                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13776
13777                cx.emit(EditorEvent::Reparsed(*buffer_id));
13778            }
13779            multi_buffer::Event::DiffHunksToggled => {
13780                self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13781            }
13782            multi_buffer::Event::LanguageChanged(buffer_id) => {
13783                linked_editing_ranges::refresh_linked_ranges(self, window, cx);
13784                cx.emit(EditorEvent::Reparsed(*buffer_id));
13785                cx.notify();
13786            }
13787            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
13788            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
13789            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
13790                cx.emit(EditorEvent::TitleChanged)
13791            }
13792            // multi_buffer::Event::DiffBaseChanged => {
13793            //     self.scrollbar_marker_state.dirty = true;
13794            //     cx.emit(EditorEvent::DiffBaseChanged);
13795            //     cx.notify();
13796            // }
13797            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
13798            multi_buffer::Event::DiagnosticsUpdated => {
13799                self.refresh_active_diagnostics(cx);
13800                self.scrollbar_marker_state.dirty = true;
13801                cx.notify();
13802            }
13803            _ => {}
13804        };
13805    }
13806
13807    fn on_display_map_changed(
13808        &mut self,
13809        _: Entity<DisplayMap>,
13810        _: &mut Window,
13811        cx: &mut Context<Self>,
13812    ) {
13813        cx.notify();
13814    }
13815
13816    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
13817        self.tasks_update_task = Some(self.refresh_runnables(window, cx));
13818        self.refresh_inline_completion(true, false, window, cx);
13819        self.refresh_inlay_hints(
13820            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
13821                self.selections.newest_anchor().head(),
13822                &self.buffer.read(cx).snapshot(cx),
13823                cx,
13824            )),
13825            cx,
13826        );
13827
13828        let old_cursor_shape = self.cursor_shape;
13829
13830        {
13831            let editor_settings = EditorSettings::get_global(cx);
13832            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
13833            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
13834            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
13835        }
13836
13837        if old_cursor_shape != self.cursor_shape {
13838            cx.emit(EditorEvent::CursorShapeChanged);
13839        }
13840
13841        let project_settings = ProjectSettings::get_global(cx);
13842        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
13843
13844        if self.mode == EditorMode::Full {
13845            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
13846            if self.git_blame_inline_enabled != inline_blame_enabled {
13847                self.toggle_git_blame_inline_internal(false, window, cx);
13848            }
13849        }
13850
13851        cx.notify();
13852    }
13853
13854    pub fn set_searchable(&mut self, searchable: bool) {
13855        self.searchable = searchable;
13856    }
13857
13858    pub fn searchable(&self) -> bool {
13859        self.searchable
13860    }
13861
13862    fn open_proposed_changes_editor(
13863        &mut self,
13864        _: &OpenProposedChangesEditor,
13865        window: &mut Window,
13866        cx: &mut Context<Self>,
13867    ) {
13868        let Some(workspace) = self.workspace() else {
13869            cx.propagate();
13870            return;
13871        };
13872
13873        let selections = self.selections.all::<usize>(cx);
13874        let multi_buffer = self.buffer.read(cx);
13875        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
13876        let mut new_selections_by_buffer = HashMap::default();
13877        for selection in selections {
13878            for (buffer, range, _) in
13879                multi_buffer_snapshot.range_to_buffer_ranges(selection.start..selection.end)
13880            {
13881                let mut range = range.to_point(buffer);
13882                range.start.column = 0;
13883                range.end.column = buffer.line_len(range.end.row);
13884                new_selections_by_buffer
13885                    .entry(multi_buffer.buffer(buffer.remote_id()).unwrap())
13886                    .or_insert(Vec::new())
13887                    .push(range)
13888            }
13889        }
13890
13891        let proposed_changes_buffers = new_selections_by_buffer
13892            .into_iter()
13893            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
13894            .collect::<Vec<_>>();
13895        let proposed_changes_editor = cx.new(|cx| {
13896            ProposedChangesEditor::new(
13897                "Proposed changes",
13898                proposed_changes_buffers,
13899                self.project.clone(),
13900                window,
13901                cx,
13902            )
13903        });
13904
13905        window.defer(cx, move |window, cx| {
13906            workspace.update(cx, |workspace, cx| {
13907                workspace.active_pane().update(cx, |pane, cx| {
13908                    pane.add_item(
13909                        Box::new(proposed_changes_editor),
13910                        true,
13911                        true,
13912                        None,
13913                        window,
13914                        cx,
13915                    );
13916                });
13917            });
13918        });
13919    }
13920
13921    pub fn open_excerpts_in_split(
13922        &mut self,
13923        _: &OpenExcerptsSplit,
13924        window: &mut Window,
13925        cx: &mut Context<Self>,
13926    ) {
13927        self.open_excerpts_common(None, true, window, cx)
13928    }
13929
13930    pub fn open_excerpts(&mut self, _: &OpenExcerpts, window: &mut Window, cx: &mut Context<Self>) {
13931        self.open_excerpts_common(None, false, window, cx)
13932    }
13933
13934    fn open_excerpts_common(
13935        &mut self,
13936        jump_data: Option<JumpData>,
13937        split: bool,
13938        window: &mut Window,
13939        cx: &mut Context<Self>,
13940    ) {
13941        let Some(workspace) = self.workspace() else {
13942            cx.propagate();
13943            return;
13944        };
13945
13946        if self.buffer.read(cx).is_singleton() {
13947            cx.propagate();
13948            return;
13949        }
13950
13951        let mut new_selections_by_buffer = HashMap::default();
13952        match &jump_data {
13953            Some(JumpData::MultiBufferPoint {
13954                excerpt_id,
13955                position,
13956                anchor,
13957                line_offset_from_top,
13958            }) => {
13959                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
13960                if let Some(buffer) = multi_buffer_snapshot
13961                    .buffer_id_for_excerpt(*excerpt_id)
13962                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
13963                {
13964                    let buffer_snapshot = buffer.read(cx).snapshot();
13965                    let jump_to_point = if buffer_snapshot.can_resolve(anchor) {
13966                        language::ToPoint::to_point(anchor, &buffer_snapshot)
13967                    } else {
13968                        buffer_snapshot.clip_point(*position, Bias::Left)
13969                    };
13970                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
13971                    new_selections_by_buffer.insert(
13972                        buffer,
13973                        (
13974                            vec![jump_to_offset..jump_to_offset],
13975                            Some(*line_offset_from_top),
13976                        ),
13977                    );
13978                }
13979            }
13980            Some(JumpData::MultiBufferRow {
13981                row,
13982                line_offset_from_top,
13983            }) => {
13984                let point = MultiBufferPoint::new(row.0, 0);
13985                if let Some((buffer, buffer_point, _)) =
13986                    self.buffer.read(cx).point_to_buffer_point(point, cx)
13987                {
13988                    let buffer_offset = buffer.read(cx).point_to_offset(buffer_point);
13989                    new_selections_by_buffer
13990                        .entry(buffer)
13991                        .or_insert((Vec::new(), Some(*line_offset_from_top)))
13992                        .0
13993                        .push(buffer_offset..buffer_offset)
13994                }
13995            }
13996            None => {
13997                let selections = self.selections.all::<usize>(cx);
13998                let multi_buffer = self.buffer.read(cx);
13999                for selection in selections {
14000                    for (buffer, mut range, _) in multi_buffer
14001                        .snapshot(cx)
14002                        .range_to_buffer_ranges(selection.range())
14003                    {
14004                        // When editing branch buffers, jump to the corresponding location
14005                        // in their base buffer.
14006                        let mut buffer_handle = multi_buffer.buffer(buffer.remote_id()).unwrap();
14007                        let buffer = buffer_handle.read(cx);
14008                        if let Some(base_buffer) = buffer.base_buffer() {
14009                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
14010                            buffer_handle = base_buffer;
14011                        }
14012
14013                        if selection.reversed {
14014                            mem::swap(&mut range.start, &mut range.end);
14015                        }
14016                        new_selections_by_buffer
14017                            .entry(buffer_handle)
14018                            .or_insert((Vec::new(), None))
14019                            .0
14020                            .push(range)
14021                    }
14022                }
14023            }
14024        }
14025
14026        if new_selections_by_buffer.is_empty() {
14027            return;
14028        }
14029
14030        // We defer the pane interaction because we ourselves are a workspace item
14031        // and activating a new item causes the pane to call a method on us reentrantly,
14032        // which panics if we're on the stack.
14033        window.defer(cx, move |window, cx| {
14034            workspace.update(cx, |workspace, cx| {
14035                let pane = if split {
14036                    workspace.adjacent_pane(window, cx)
14037                } else {
14038                    workspace.active_pane().clone()
14039                };
14040
14041                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
14042                    let editor = buffer
14043                        .read(cx)
14044                        .file()
14045                        .is_none()
14046                        .then(|| {
14047                            // Handle file-less buffers separately: those are not really the project items, so won't have a project path or entity id,
14048                            // so `workspace.open_project_item` will never find them, always opening a new editor.
14049                            // Instead, we try to activate the existing editor in the pane first.
14050                            let (editor, pane_item_index) =
14051                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
14052                                    let editor = item.downcast::<Editor>()?;
14053                                    let singleton_buffer =
14054                                        editor.read(cx).buffer().read(cx).as_singleton()?;
14055                                    if singleton_buffer == buffer {
14056                                        Some((editor, i))
14057                                    } else {
14058                                        None
14059                                    }
14060                                })?;
14061                            pane.update(cx, |pane, cx| {
14062                                pane.activate_item(pane_item_index, true, true, window, cx)
14063                            });
14064                            Some(editor)
14065                        })
14066                        .flatten()
14067                        .unwrap_or_else(|| {
14068                            workspace.open_project_item::<Self>(
14069                                pane.clone(),
14070                                buffer,
14071                                true,
14072                                true,
14073                                window,
14074                                cx,
14075                            )
14076                        });
14077
14078                    editor.update(cx, |editor, cx| {
14079                        let autoscroll = match scroll_offset {
14080                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
14081                            None => Autoscroll::newest(),
14082                        };
14083                        let nav_history = editor.nav_history.take();
14084                        editor.change_selections(Some(autoscroll), window, cx, |s| {
14085                            s.select_ranges(ranges);
14086                        });
14087                        editor.nav_history = nav_history;
14088                    });
14089                }
14090            })
14091        });
14092    }
14093
14094    fn marked_text_ranges(&self, cx: &App) -> Option<Vec<Range<OffsetUtf16>>> {
14095        let snapshot = self.buffer.read(cx).read(cx);
14096        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
14097        Some(
14098            ranges
14099                .iter()
14100                .map(move |range| {
14101                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
14102                })
14103                .collect(),
14104        )
14105    }
14106
14107    fn selection_replacement_ranges(
14108        &self,
14109        range: Range<OffsetUtf16>,
14110        cx: &mut App,
14111    ) -> Vec<Range<OffsetUtf16>> {
14112        let selections = self.selections.all::<OffsetUtf16>(cx);
14113        let newest_selection = selections
14114            .iter()
14115            .max_by_key(|selection| selection.id)
14116            .unwrap();
14117        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
14118        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
14119        let snapshot = self.buffer.read(cx).read(cx);
14120        selections
14121            .into_iter()
14122            .map(|mut selection| {
14123                selection.start.0 =
14124                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
14125                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
14126                snapshot.clip_offset_utf16(selection.start, Bias::Left)
14127                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
14128            })
14129            .collect()
14130    }
14131
14132    fn report_editor_event(
14133        &self,
14134        event_type: &'static str,
14135        file_extension: Option<String>,
14136        cx: &App,
14137    ) {
14138        if cfg!(any(test, feature = "test-support")) {
14139            return;
14140        }
14141
14142        let Some(project) = &self.project else { return };
14143
14144        // If None, we are in a file without an extension
14145        let file = self
14146            .buffer
14147            .read(cx)
14148            .as_singleton()
14149            .and_then(|b| b.read(cx).file());
14150        let file_extension = file_extension.or(file
14151            .as_ref()
14152            .and_then(|file| Path::new(file.file_name(cx)).extension())
14153            .and_then(|e| e.to_str())
14154            .map(|a| a.to_string()));
14155
14156        let vim_mode = cx
14157            .global::<SettingsStore>()
14158            .raw_user_settings()
14159            .get("vim_mode")
14160            == Some(&serde_json::Value::Bool(true));
14161
14162        let edit_predictions_provider = all_language_settings(file, cx).inline_completions.provider;
14163        let copilot_enabled = edit_predictions_provider
14164            == language::language_settings::InlineCompletionProvider::Copilot;
14165        let copilot_enabled_for_language = self
14166            .buffer
14167            .read(cx)
14168            .settings_at(0, cx)
14169            .show_inline_completions;
14170
14171        let project = project.read(cx);
14172        telemetry::event!(
14173            event_type,
14174            file_extension,
14175            vim_mode,
14176            copilot_enabled,
14177            copilot_enabled_for_language,
14178            edit_predictions_provider,
14179            is_via_ssh = project.is_via_ssh(),
14180        );
14181    }
14182
14183    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
14184    /// with each line being an array of {text, highlight} objects.
14185    fn copy_highlight_json(
14186        &mut self,
14187        _: &CopyHighlightJson,
14188        window: &mut Window,
14189        cx: &mut Context<Self>,
14190    ) {
14191        #[derive(Serialize)]
14192        struct Chunk<'a> {
14193            text: String,
14194            highlight: Option<&'a str>,
14195        }
14196
14197        let snapshot = self.buffer.read(cx).snapshot(cx);
14198        let range = self
14199            .selected_text_range(false, window, cx)
14200            .and_then(|selection| {
14201                if selection.range.is_empty() {
14202                    None
14203                } else {
14204                    Some(selection.range)
14205                }
14206            })
14207            .unwrap_or_else(|| 0..snapshot.len());
14208
14209        let chunks = snapshot.chunks(range, true);
14210        let mut lines = Vec::new();
14211        let mut line: VecDeque<Chunk> = VecDeque::new();
14212
14213        let Some(style) = self.style.as_ref() else {
14214            return;
14215        };
14216
14217        for chunk in chunks {
14218            let highlight = chunk
14219                .syntax_highlight_id
14220                .and_then(|id| id.name(&style.syntax));
14221            let mut chunk_lines = chunk.text.split('\n').peekable();
14222            while let Some(text) = chunk_lines.next() {
14223                let mut merged_with_last_token = false;
14224                if let Some(last_token) = line.back_mut() {
14225                    if last_token.highlight == highlight {
14226                        last_token.text.push_str(text);
14227                        merged_with_last_token = true;
14228                    }
14229                }
14230
14231                if !merged_with_last_token {
14232                    line.push_back(Chunk {
14233                        text: text.into(),
14234                        highlight,
14235                    });
14236                }
14237
14238                if chunk_lines.peek().is_some() {
14239                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
14240                        line.pop_front();
14241                    }
14242                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
14243                        line.pop_back();
14244                    }
14245
14246                    lines.push(mem::take(&mut line));
14247                }
14248            }
14249        }
14250
14251        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
14252            return;
14253        };
14254        cx.write_to_clipboard(ClipboardItem::new_string(lines));
14255    }
14256
14257    pub fn open_context_menu(
14258        &mut self,
14259        _: &OpenContextMenu,
14260        window: &mut Window,
14261        cx: &mut Context<Self>,
14262    ) {
14263        self.request_autoscroll(Autoscroll::newest(), cx);
14264        let position = self.selections.newest_display(cx).start;
14265        mouse_context_menu::deploy_context_menu(self, None, position, window, cx);
14266    }
14267
14268    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
14269        &self.inlay_hint_cache
14270    }
14271
14272    pub fn replay_insert_event(
14273        &mut self,
14274        text: &str,
14275        relative_utf16_range: Option<Range<isize>>,
14276        window: &mut Window,
14277        cx: &mut Context<Self>,
14278    ) {
14279        if !self.input_enabled {
14280            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14281            return;
14282        }
14283        if let Some(relative_utf16_range) = relative_utf16_range {
14284            let selections = self.selections.all::<OffsetUtf16>(cx);
14285            self.change_selections(None, window, cx, |s| {
14286                let new_ranges = selections.into_iter().map(|range| {
14287                    let start = OffsetUtf16(
14288                        range
14289                            .head()
14290                            .0
14291                            .saturating_add_signed(relative_utf16_range.start),
14292                    );
14293                    let end = OffsetUtf16(
14294                        range
14295                            .head()
14296                            .0
14297                            .saturating_add_signed(relative_utf16_range.end),
14298                    );
14299                    start..end
14300                });
14301                s.select_ranges(new_ranges);
14302            });
14303        }
14304
14305        self.handle_input(text, window, cx);
14306    }
14307
14308    pub fn supports_inlay_hints(&self, cx: &App) -> bool {
14309        let Some(provider) = self.semantics_provider.as_ref() else {
14310            return false;
14311        };
14312
14313        let mut supports = false;
14314        self.buffer().read(cx).for_each_buffer(|buffer| {
14315            supports |= provider.supports_inlay_hints(buffer, cx);
14316        });
14317        supports
14318    }
14319    pub fn is_focused(&self, window: &mut Window) -> bool {
14320        self.focus_handle.is_focused(window)
14321    }
14322
14323    fn handle_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14324        cx.emit(EditorEvent::Focused);
14325
14326        if let Some(descendant) = self
14327            .last_focused_descendant
14328            .take()
14329            .and_then(|descendant| descendant.upgrade())
14330        {
14331            window.focus(&descendant);
14332        } else {
14333            if let Some(blame) = self.blame.as_ref() {
14334                blame.update(cx, GitBlame::focus)
14335            }
14336
14337            self.blink_manager.update(cx, BlinkManager::enable);
14338            self.show_cursor_names(window, cx);
14339            self.buffer.update(cx, |buffer, cx| {
14340                buffer.finalize_last_transaction(cx);
14341                if self.leader_peer_id.is_none() {
14342                    buffer.set_active_selections(
14343                        &self.selections.disjoint_anchors(),
14344                        self.selections.line_mode,
14345                        self.cursor_shape,
14346                        cx,
14347                    );
14348                }
14349            });
14350        }
14351    }
14352
14353    fn handle_focus_in(&mut self, _: &mut Window, cx: &mut Context<Self>) {
14354        cx.emit(EditorEvent::FocusedIn)
14355    }
14356
14357    fn handle_focus_out(
14358        &mut self,
14359        event: FocusOutEvent,
14360        _window: &mut Window,
14361        _cx: &mut Context<Self>,
14362    ) {
14363        if event.blurred != self.focus_handle {
14364            self.last_focused_descendant = Some(event.blurred);
14365        }
14366    }
14367
14368    pub fn handle_blur(&mut self, window: &mut Window, cx: &mut Context<Self>) {
14369        self.blink_manager.update(cx, BlinkManager::disable);
14370        self.buffer
14371            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
14372
14373        if let Some(blame) = self.blame.as_ref() {
14374            blame.update(cx, GitBlame::blur)
14375        }
14376        if !self.hover_state.focused(window, cx) {
14377            hide_hover(self, cx);
14378        }
14379
14380        self.hide_context_menu(window, cx);
14381        cx.emit(EditorEvent::Blurred);
14382        cx.notify();
14383    }
14384
14385    pub fn register_action<A: Action>(
14386        &mut self,
14387        listener: impl Fn(&A, &mut Window, &mut App) + 'static,
14388    ) -> Subscription {
14389        let id = self.next_editor_action_id.post_inc();
14390        let listener = Arc::new(listener);
14391        self.editor_actions.borrow_mut().insert(
14392            id,
14393            Box::new(move |window, _| {
14394                let listener = listener.clone();
14395                window.on_action(TypeId::of::<A>(), move |action, phase, window, cx| {
14396                    let action = action.downcast_ref().unwrap();
14397                    if phase == DispatchPhase::Bubble {
14398                        listener(action, window, cx)
14399                    }
14400                })
14401            }),
14402        );
14403
14404        let editor_actions = self.editor_actions.clone();
14405        Subscription::new(move || {
14406            editor_actions.borrow_mut().remove(&id);
14407        })
14408    }
14409
14410    pub fn file_header_size(&self) -> u32 {
14411        FILE_HEADER_HEIGHT
14412    }
14413
14414    pub fn revert(
14415        &mut self,
14416        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
14417        window: &mut Window,
14418        cx: &mut Context<Self>,
14419    ) {
14420        self.buffer().update(cx, |multi_buffer, cx| {
14421            for (buffer_id, changes) in revert_changes {
14422                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
14423                    buffer.update(cx, |buffer, cx| {
14424                        buffer.edit(
14425                            changes.into_iter().map(|(range, text)| {
14426                                (range, text.to_string().map(Arc::<str>::from))
14427                            }),
14428                            None,
14429                            cx,
14430                        );
14431                    });
14432                }
14433            }
14434        });
14435        self.change_selections(None, window, cx, |selections| selections.refresh());
14436    }
14437
14438    pub fn to_pixel_point(
14439        &self,
14440        source: multi_buffer::Anchor,
14441        editor_snapshot: &EditorSnapshot,
14442        window: &mut Window,
14443    ) -> Option<gpui::Point<Pixels>> {
14444        let source_point = source.to_display_point(editor_snapshot);
14445        self.display_to_pixel_point(source_point, editor_snapshot, window)
14446    }
14447
14448    pub fn display_to_pixel_point(
14449        &self,
14450        source: DisplayPoint,
14451        editor_snapshot: &EditorSnapshot,
14452        window: &mut Window,
14453    ) -> Option<gpui::Point<Pixels>> {
14454        let line_height = self.style()?.text.line_height_in_pixels(window.rem_size());
14455        let text_layout_details = self.text_layout_details(window);
14456        let scroll_top = text_layout_details
14457            .scroll_anchor
14458            .scroll_position(editor_snapshot)
14459            .y;
14460
14461        if source.row().as_f32() < scroll_top.floor() {
14462            return None;
14463        }
14464        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
14465        let source_y = line_height * (source.row().as_f32() - scroll_top);
14466        Some(gpui::Point::new(source_x, source_y))
14467    }
14468
14469    pub fn has_visible_completions_menu(&self) -> bool {
14470        !self.previewing_inline_completion
14471            && self.context_menu.borrow().as_ref().map_or(false, |menu| {
14472                menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
14473            })
14474    }
14475
14476    pub fn register_addon<T: Addon>(&mut self, instance: T) {
14477        self.addons
14478            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
14479    }
14480
14481    pub fn unregister_addon<T: Addon>(&mut self) {
14482        self.addons.remove(&std::any::TypeId::of::<T>());
14483    }
14484
14485    pub fn addon<T: Addon>(&self) -> Option<&T> {
14486        let type_id = std::any::TypeId::of::<T>();
14487        self.addons
14488            .get(&type_id)
14489            .and_then(|item| item.to_any().downcast_ref::<T>())
14490    }
14491
14492    fn character_size(&self, window: &mut Window) -> gpui::Size<Pixels> {
14493        let text_layout_details = self.text_layout_details(window);
14494        let style = &text_layout_details.editor_style;
14495        let font_id = window.text_system().resolve_font(&style.text.font());
14496        let font_size = style.text.font_size.to_pixels(window.rem_size());
14497        let line_height = style.text.line_height_in_pixels(window.rem_size());
14498        let em_width = window.text_system().em_width(font_id, font_size).unwrap();
14499
14500        gpui::Size::new(em_width, line_height)
14501    }
14502}
14503
14504fn get_uncommitted_diff_for_buffer(
14505    project: &Entity<Project>,
14506    buffers: impl IntoIterator<Item = Entity<Buffer>>,
14507    buffer: Entity<MultiBuffer>,
14508    cx: &mut App,
14509) {
14510    let mut tasks = Vec::new();
14511    project.update(cx, |project, cx| {
14512        for buffer in buffers {
14513            tasks.push(project.open_uncommitted_diff(buffer.clone(), cx))
14514        }
14515    });
14516    cx.spawn(|mut cx| async move {
14517        let diffs = futures::future::join_all(tasks).await;
14518        buffer
14519            .update(&mut cx, |buffer, cx| {
14520                for diff in diffs.into_iter().flatten() {
14521                    buffer.add_diff(diff, cx);
14522                }
14523            })
14524            .ok();
14525    })
14526    .detach();
14527}
14528
14529fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
14530    let tab_size = tab_size.get() as usize;
14531    let mut width = offset;
14532
14533    for ch in text.chars() {
14534        width += if ch == '\t' {
14535            tab_size - (width % tab_size)
14536        } else {
14537            1
14538        };
14539    }
14540
14541    width - offset
14542}
14543
14544#[cfg(test)]
14545mod tests {
14546    use super::*;
14547
14548    #[test]
14549    fn test_string_size_with_expanded_tabs() {
14550        let nz = |val| NonZeroU32::new(val).unwrap();
14551        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
14552        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
14553        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
14554        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
14555        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
14556        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
14557        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
14558        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
14559    }
14560}
14561
14562/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
14563struct WordBreakingTokenizer<'a> {
14564    input: &'a str,
14565}
14566
14567impl<'a> WordBreakingTokenizer<'a> {
14568    fn new(input: &'a str) -> Self {
14569        Self { input }
14570    }
14571}
14572
14573fn is_char_ideographic(ch: char) -> bool {
14574    use unicode_script::Script::*;
14575    use unicode_script::UnicodeScript;
14576    matches!(ch.script(), Han | Tangut | Yi)
14577}
14578
14579fn is_grapheme_ideographic(text: &str) -> bool {
14580    text.chars().any(is_char_ideographic)
14581}
14582
14583fn is_grapheme_whitespace(text: &str) -> bool {
14584    text.chars().any(|x| x.is_whitespace())
14585}
14586
14587fn should_stay_with_preceding_ideograph(text: &str) -> bool {
14588    text.chars().next().map_or(false, |ch| {
14589        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
14590    })
14591}
14592
14593#[derive(PartialEq, Eq, Debug, Clone, Copy)]
14594struct WordBreakToken<'a> {
14595    token: &'a str,
14596    grapheme_len: usize,
14597    is_whitespace: bool,
14598}
14599
14600impl<'a> Iterator for WordBreakingTokenizer<'a> {
14601    /// Yields a span, the count of graphemes in the token, and whether it was
14602    /// whitespace. Note that it also breaks at word boundaries.
14603    type Item = WordBreakToken<'a>;
14604
14605    fn next(&mut self) -> Option<Self::Item> {
14606        use unicode_segmentation::UnicodeSegmentation;
14607        if self.input.is_empty() {
14608            return None;
14609        }
14610
14611        let mut iter = self.input.graphemes(true).peekable();
14612        let mut offset = 0;
14613        let mut graphemes = 0;
14614        if let Some(first_grapheme) = iter.next() {
14615            let is_whitespace = is_grapheme_whitespace(first_grapheme);
14616            offset += first_grapheme.len();
14617            graphemes += 1;
14618            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
14619                if let Some(grapheme) = iter.peek().copied() {
14620                    if should_stay_with_preceding_ideograph(grapheme) {
14621                        offset += grapheme.len();
14622                        graphemes += 1;
14623                    }
14624                }
14625            } else {
14626                let mut words = self.input[offset..].split_word_bound_indices().peekable();
14627                let mut next_word_bound = words.peek().copied();
14628                if next_word_bound.map_or(false, |(i, _)| i == 0) {
14629                    next_word_bound = words.next();
14630                }
14631                while let Some(grapheme) = iter.peek().copied() {
14632                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
14633                        break;
14634                    };
14635                    if is_grapheme_whitespace(grapheme) != is_whitespace {
14636                        break;
14637                    };
14638                    offset += grapheme.len();
14639                    graphemes += 1;
14640                    iter.next();
14641                }
14642            }
14643            let token = &self.input[..offset];
14644            self.input = &self.input[offset..];
14645            if is_whitespace {
14646                Some(WordBreakToken {
14647                    token: " ",
14648                    grapheme_len: 1,
14649                    is_whitespace: true,
14650                })
14651            } else {
14652                Some(WordBreakToken {
14653                    token,
14654                    grapheme_len: graphemes,
14655                    is_whitespace: false,
14656                })
14657            }
14658        } else {
14659            None
14660        }
14661    }
14662}
14663
14664#[test]
14665fn test_word_breaking_tokenizer() {
14666    let tests: &[(&str, &[(&str, usize, bool)])] = &[
14667        ("", &[]),
14668        ("  ", &[(" ", 1, true)]),
14669        ("Ʒ", &[("Ʒ", 1, false)]),
14670        ("Ǽ", &[("Ǽ", 1, false)]),
14671        ("", &[("", 1, false)]),
14672        ("⋑⋑", &[("⋑⋑", 2, false)]),
14673        (
14674            "原理,进而",
14675            &[
14676                ("", 1, false),
14677                ("理,", 2, false),
14678                ("", 1, false),
14679                ("", 1, false),
14680            ],
14681        ),
14682        (
14683            "hello world",
14684            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
14685        ),
14686        (
14687            "hello, world",
14688            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
14689        ),
14690        (
14691            "  hello world",
14692            &[
14693                (" ", 1, true),
14694                ("hello", 5, false),
14695                (" ", 1, true),
14696                ("world", 5, false),
14697            ],
14698        ),
14699        (
14700            "这是什么 \n 钢笔",
14701            &[
14702                ("", 1, false),
14703                ("", 1, false),
14704                ("", 1, false),
14705                ("", 1, false),
14706                (" ", 1, true),
14707                ("", 1, false),
14708                ("", 1, false),
14709            ],
14710        ),
14711        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
14712    ];
14713
14714    for (input, result) in tests {
14715        assert_eq!(
14716            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
14717            result
14718                .iter()
14719                .copied()
14720                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
14721                    token,
14722                    grapheme_len,
14723                    is_whitespace,
14724                })
14725                .collect::<Vec<_>>()
14726        );
14727    }
14728}
14729
14730fn wrap_with_prefix(
14731    line_prefix: String,
14732    unwrapped_text: String,
14733    wrap_column: usize,
14734    tab_size: NonZeroU32,
14735) -> String {
14736    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
14737    let mut wrapped_text = String::new();
14738    let mut current_line = line_prefix.clone();
14739
14740    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
14741    let mut current_line_len = line_prefix_len;
14742    for WordBreakToken {
14743        token,
14744        grapheme_len,
14745        is_whitespace,
14746    } in tokenizer
14747    {
14748        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
14749            wrapped_text.push_str(current_line.trim_end());
14750            wrapped_text.push('\n');
14751            current_line.truncate(line_prefix.len());
14752            current_line_len = line_prefix_len;
14753            if !is_whitespace {
14754                current_line.push_str(token);
14755                current_line_len += grapheme_len;
14756            }
14757        } else if !is_whitespace {
14758            current_line.push_str(token);
14759            current_line_len += grapheme_len;
14760        } else if current_line_len != line_prefix_len {
14761            current_line.push(' ');
14762            current_line_len += 1;
14763        }
14764    }
14765
14766    if !current_line.is_empty() {
14767        wrapped_text.push_str(&current_line);
14768    }
14769    wrapped_text
14770}
14771
14772#[test]
14773fn test_wrap_with_prefix() {
14774    assert_eq!(
14775        wrap_with_prefix(
14776            "# ".to_string(),
14777            "abcdefg".to_string(),
14778            4,
14779            NonZeroU32::new(4).unwrap()
14780        ),
14781        "# abcdefg"
14782    );
14783    assert_eq!(
14784        wrap_with_prefix(
14785            "".to_string(),
14786            "\thello world".to_string(),
14787            8,
14788            NonZeroU32::new(4).unwrap()
14789        ),
14790        "hello\nworld"
14791    );
14792    assert_eq!(
14793        wrap_with_prefix(
14794            "// ".to_string(),
14795            "xx \nyy zz aa bb cc".to_string(),
14796            12,
14797            NonZeroU32::new(4).unwrap()
14798        ),
14799        "// xx yy zz\n// aa bb cc"
14800    );
14801    assert_eq!(
14802        wrap_with_prefix(
14803            String::new(),
14804            "这是什么 \n 钢笔".to_string(),
14805            3,
14806            NonZeroU32::new(4).unwrap()
14807        ),
14808        "这是什\n么 钢\n"
14809    );
14810}
14811
14812pub trait CollaborationHub {
14813    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator>;
14814    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex>;
14815    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString>;
14816}
14817
14818impl CollaborationHub for Entity<Project> {
14819    fn collaborators<'a>(&self, cx: &'a App) -> &'a HashMap<PeerId, Collaborator> {
14820        self.read(cx).collaborators()
14821    }
14822
14823    fn user_participant_indices<'a>(&self, cx: &'a App) -> &'a HashMap<u64, ParticipantIndex> {
14824        self.read(cx).user_store().read(cx).participant_indices()
14825    }
14826
14827    fn user_names(&self, cx: &App) -> HashMap<u64, SharedString> {
14828        let this = self.read(cx);
14829        let user_ids = this.collaborators().values().map(|c| c.user_id);
14830        this.user_store().read_with(cx, |user_store, cx| {
14831            user_store.participant_names(user_ids, cx)
14832        })
14833    }
14834}
14835
14836pub trait SemanticsProvider {
14837    fn hover(
14838        &self,
14839        buffer: &Entity<Buffer>,
14840        position: text::Anchor,
14841        cx: &mut App,
14842    ) -> Option<Task<Vec<project::Hover>>>;
14843
14844    fn inlay_hints(
14845        &self,
14846        buffer_handle: Entity<Buffer>,
14847        range: Range<text::Anchor>,
14848        cx: &mut App,
14849    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
14850
14851    fn resolve_inlay_hint(
14852        &self,
14853        hint: InlayHint,
14854        buffer_handle: Entity<Buffer>,
14855        server_id: LanguageServerId,
14856        cx: &mut App,
14857    ) -> Option<Task<anyhow::Result<InlayHint>>>;
14858
14859    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool;
14860
14861    fn document_highlights(
14862        &self,
14863        buffer: &Entity<Buffer>,
14864        position: text::Anchor,
14865        cx: &mut App,
14866    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
14867
14868    fn definitions(
14869        &self,
14870        buffer: &Entity<Buffer>,
14871        position: text::Anchor,
14872        kind: GotoDefinitionKind,
14873        cx: &mut App,
14874    ) -> Option<Task<Result<Vec<LocationLink>>>>;
14875
14876    fn range_for_rename(
14877        &self,
14878        buffer: &Entity<Buffer>,
14879        position: text::Anchor,
14880        cx: &mut App,
14881    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
14882
14883    fn perform_rename(
14884        &self,
14885        buffer: &Entity<Buffer>,
14886        position: text::Anchor,
14887        new_name: String,
14888        cx: &mut App,
14889    ) -> Option<Task<Result<ProjectTransaction>>>;
14890}
14891
14892pub trait CompletionProvider {
14893    fn completions(
14894        &self,
14895        buffer: &Entity<Buffer>,
14896        buffer_position: text::Anchor,
14897        trigger: CompletionContext,
14898        window: &mut Window,
14899        cx: &mut Context<Editor>,
14900    ) -> Task<Result<Vec<Completion>>>;
14901
14902    fn resolve_completions(
14903        &self,
14904        buffer: Entity<Buffer>,
14905        completion_indices: Vec<usize>,
14906        completions: Rc<RefCell<Box<[Completion]>>>,
14907        cx: &mut Context<Editor>,
14908    ) -> Task<Result<bool>>;
14909
14910    fn apply_additional_edits_for_completion(
14911        &self,
14912        _buffer: Entity<Buffer>,
14913        _completions: Rc<RefCell<Box<[Completion]>>>,
14914        _completion_index: usize,
14915        _push_to_history: bool,
14916        _cx: &mut Context<Editor>,
14917    ) -> Task<Result<Option<language::Transaction>>> {
14918        Task::ready(Ok(None))
14919    }
14920
14921    fn is_completion_trigger(
14922        &self,
14923        buffer: &Entity<Buffer>,
14924        position: language::Anchor,
14925        text: &str,
14926        trigger_in_words: bool,
14927        cx: &mut Context<Editor>,
14928    ) -> bool;
14929
14930    fn sort_completions(&self) -> bool {
14931        true
14932    }
14933}
14934
14935pub trait CodeActionProvider {
14936    fn id(&self) -> Arc<str>;
14937
14938    fn code_actions(
14939        &self,
14940        buffer: &Entity<Buffer>,
14941        range: Range<text::Anchor>,
14942        window: &mut Window,
14943        cx: &mut App,
14944    ) -> Task<Result<Vec<CodeAction>>>;
14945
14946    fn apply_code_action(
14947        &self,
14948        buffer_handle: Entity<Buffer>,
14949        action: CodeAction,
14950        excerpt_id: ExcerptId,
14951        push_to_history: bool,
14952        window: &mut Window,
14953        cx: &mut App,
14954    ) -> Task<Result<ProjectTransaction>>;
14955}
14956
14957impl CodeActionProvider for Entity<Project> {
14958    fn id(&self) -> Arc<str> {
14959        "project".into()
14960    }
14961
14962    fn code_actions(
14963        &self,
14964        buffer: &Entity<Buffer>,
14965        range: Range<text::Anchor>,
14966        _window: &mut Window,
14967        cx: &mut App,
14968    ) -> Task<Result<Vec<CodeAction>>> {
14969        self.update(cx, |project, cx| {
14970            project.code_actions(buffer, range, None, cx)
14971        })
14972    }
14973
14974    fn apply_code_action(
14975        &self,
14976        buffer_handle: Entity<Buffer>,
14977        action: CodeAction,
14978        _excerpt_id: ExcerptId,
14979        push_to_history: bool,
14980        _window: &mut Window,
14981        cx: &mut App,
14982    ) -> Task<Result<ProjectTransaction>> {
14983        self.update(cx, |project, cx| {
14984            project.apply_code_action(buffer_handle, action, push_to_history, cx)
14985        })
14986    }
14987}
14988
14989fn snippet_completions(
14990    project: &Project,
14991    buffer: &Entity<Buffer>,
14992    buffer_position: text::Anchor,
14993    cx: &mut App,
14994) -> Task<Result<Vec<Completion>>> {
14995    let language = buffer.read(cx).language_at(buffer_position);
14996    let language_name = language.as_ref().map(|language| language.lsp_id());
14997    let snippet_store = project.snippets().read(cx);
14998    let snippets = snippet_store.snippets_for(language_name, cx);
14999
15000    if snippets.is_empty() {
15001        return Task::ready(Ok(vec![]));
15002    }
15003    let snapshot = buffer.read(cx).text_snapshot();
15004    let chars: String = snapshot
15005        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
15006        .collect();
15007
15008    let scope = language.map(|language| language.default_scope());
15009    let executor = cx.background_executor().clone();
15010
15011    cx.background_executor().spawn(async move {
15012        let classifier = CharClassifier::new(scope).for_completion(true);
15013        let mut last_word = chars
15014            .chars()
15015            .take_while(|c| classifier.is_word(*c))
15016            .collect::<String>();
15017        last_word = last_word.chars().rev().collect();
15018
15019        if last_word.is_empty() {
15020            return Ok(vec![]);
15021        }
15022
15023        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
15024        let to_lsp = |point: &text::Anchor| {
15025            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
15026            point_to_lsp(end)
15027        };
15028        let lsp_end = to_lsp(&buffer_position);
15029
15030        let candidates = snippets
15031            .iter()
15032            .enumerate()
15033            .flat_map(|(ix, snippet)| {
15034                snippet
15035                    .prefix
15036                    .iter()
15037                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
15038            })
15039            .collect::<Vec<StringMatchCandidate>>();
15040
15041        let mut matches = fuzzy::match_strings(
15042            &candidates,
15043            &last_word,
15044            last_word.chars().any(|c| c.is_uppercase()),
15045            100,
15046            &Default::default(),
15047            executor,
15048        )
15049        .await;
15050
15051        // Remove all candidates where the query's start does not match the start of any word in the candidate
15052        if let Some(query_start) = last_word.chars().next() {
15053            matches.retain(|string_match| {
15054                split_words(&string_match.string).any(|word| {
15055                    // Check that the first codepoint of the word as lowercase matches the first
15056                    // codepoint of the query as lowercase
15057                    word.chars()
15058                        .flat_map(|codepoint| codepoint.to_lowercase())
15059                        .zip(query_start.to_lowercase())
15060                        .all(|(word_cp, query_cp)| word_cp == query_cp)
15061                })
15062            });
15063        }
15064
15065        let matched_strings = matches
15066            .into_iter()
15067            .map(|m| m.string)
15068            .collect::<HashSet<_>>();
15069
15070        let result: Vec<Completion> = snippets
15071            .into_iter()
15072            .filter_map(|snippet| {
15073                let matching_prefix = snippet
15074                    .prefix
15075                    .iter()
15076                    .find(|prefix| matched_strings.contains(*prefix))?;
15077                let start = as_offset - last_word.len();
15078                let start = snapshot.anchor_before(start);
15079                let range = start..buffer_position;
15080                let lsp_start = to_lsp(&start);
15081                let lsp_range = lsp::Range {
15082                    start: lsp_start,
15083                    end: lsp_end,
15084                };
15085                Some(Completion {
15086                    old_range: range,
15087                    new_text: snippet.body.clone(),
15088                    resolved: false,
15089                    label: CodeLabel {
15090                        text: matching_prefix.clone(),
15091                        runs: vec![],
15092                        filter_range: 0..matching_prefix.len(),
15093                    },
15094                    server_id: LanguageServerId(usize::MAX),
15095                    documentation: snippet
15096                        .description
15097                        .clone()
15098                        .map(CompletionDocumentation::SingleLine),
15099                    lsp_completion: lsp::CompletionItem {
15100                        label: snippet.prefix.first().unwrap().clone(),
15101                        kind: Some(CompletionItemKind::SNIPPET),
15102                        label_details: snippet.description.as_ref().map(|description| {
15103                            lsp::CompletionItemLabelDetails {
15104                                detail: Some(description.clone()),
15105                                description: None,
15106                            }
15107                        }),
15108                        insert_text_format: Some(InsertTextFormat::SNIPPET),
15109                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
15110                            lsp::InsertReplaceEdit {
15111                                new_text: snippet.body.clone(),
15112                                insert: lsp_range,
15113                                replace: lsp_range,
15114                            },
15115                        )),
15116                        filter_text: Some(snippet.body.clone()),
15117                        sort_text: Some(char::MAX.to_string()),
15118                        ..Default::default()
15119                    },
15120                    confirm: None,
15121                })
15122            })
15123            .collect();
15124
15125        Ok(result)
15126    })
15127}
15128
15129impl CompletionProvider for Entity<Project> {
15130    fn completions(
15131        &self,
15132        buffer: &Entity<Buffer>,
15133        buffer_position: text::Anchor,
15134        options: CompletionContext,
15135        _window: &mut Window,
15136        cx: &mut Context<Editor>,
15137    ) -> Task<Result<Vec<Completion>>> {
15138        self.update(cx, |project, cx| {
15139            let snippets = snippet_completions(project, buffer, buffer_position, cx);
15140            let project_completions = project.completions(buffer, buffer_position, options, cx);
15141            cx.background_executor().spawn(async move {
15142                let mut completions = project_completions.await?;
15143                let snippets_completions = snippets.await?;
15144                completions.extend(snippets_completions);
15145                Ok(completions)
15146            })
15147        })
15148    }
15149
15150    fn resolve_completions(
15151        &self,
15152        buffer: Entity<Buffer>,
15153        completion_indices: Vec<usize>,
15154        completions: Rc<RefCell<Box<[Completion]>>>,
15155        cx: &mut Context<Editor>,
15156    ) -> Task<Result<bool>> {
15157        self.update(cx, |project, cx| {
15158            project.lsp_store().update(cx, |lsp_store, cx| {
15159                lsp_store.resolve_completions(buffer, completion_indices, completions, cx)
15160            })
15161        })
15162    }
15163
15164    fn apply_additional_edits_for_completion(
15165        &self,
15166        buffer: Entity<Buffer>,
15167        completions: Rc<RefCell<Box<[Completion]>>>,
15168        completion_index: usize,
15169        push_to_history: bool,
15170        cx: &mut Context<Editor>,
15171    ) -> Task<Result<Option<language::Transaction>>> {
15172        self.update(cx, |project, cx| {
15173            project.lsp_store().update(cx, |lsp_store, cx| {
15174                lsp_store.apply_additional_edits_for_completion(
15175                    buffer,
15176                    completions,
15177                    completion_index,
15178                    push_to_history,
15179                    cx,
15180                )
15181            })
15182        })
15183    }
15184
15185    fn is_completion_trigger(
15186        &self,
15187        buffer: &Entity<Buffer>,
15188        position: language::Anchor,
15189        text: &str,
15190        trigger_in_words: bool,
15191        cx: &mut Context<Editor>,
15192    ) -> bool {
15193        let mut chars = text.chars();
15194        let char = if let Some(char) = chars.next() {
15195            char
15196        } else {
15197            return false;
15198        };
15199        if chars.next().is_some() {
15200            return false;
15201        }
15202
15203        let buffer = buffer.read(cx);
15204        let snapshot = buffer.snapshot();
15205        if !snapshot.settings_at(position, cx).show_completions_on_input {
15206            return false;
15207        }
15208        let classifier = snapshot.char_classifier_at(position).for_completion(true);
15209        if trigger_in_words && classifier.is_word(char) {
15210            return true;
15211        }
15212
15213        buffer.completion_triggers().contains(text)
15214    }
15215}
15216
15217impl SemanticsProvider for Entity<Project> {
15218    fn hover(
15219        &self,
15220        buffer: &Entity<Buffer>,
15221        position: text::Anchor,
15222        cx: &mut App,
15223    ) -> Option<Task<Vec<project::Hover>>> {
15224        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
15225    }
15226
15227    fn document_highlights(
15228        &self,
15229        buffer: &Entity<Buffer>,
15230        position: text::Anchor,
15231        cx: &mut App,
15232    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
15233        Some(self.update(cx, |project, cx| {
15234            project.document_highlights(buffer, position, cx)
15235        }))
15236    }
15237
15238    fn definitions(
15239        &self,
15240        buffer: &Entity<Buffer>,
15241        position: text::Anchor,
15242        kind: GotoDefinitionKind,
15243        cx: &mut App,
15244    ) -> Option<Task<Result<Vec<LocationLink>>>> {
15245        Some(self.update(cx, |project, cx| match kind {
15246            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
15247            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
15248            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
15249            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
15250        }))
15251    }
15252
15253    fn supports_inlay_hints(&self, buffer: &Entity<Buffer>, cx: &App) -> bool {
15254        // TODO: make this work for remote projects
15255        self.read(cx)
15256            .language_servers_for_local_buffer(buffer.read(cx), cx)
15257            .any(
15258                |(_, server)| match server.capabilities().inlay_hint_provider {
15259                    Some(lsp::OneOf::Left(enabled)) => enabled,
15260                    Some(lsp::OneOf::Right(_)) => true,
15261                    None => false,
15262                },
15263            )
15264    }
15265
15266    fn inlay_hints(
15267        &self,
15268        buffer_handle: Entity<Buffer>,
15269        range: Range<text::Anchor>,
15270        cx: &mut App,
15271    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
15272        Some(self.update(cx, |project, cx| {
15273            project.inlay_hints(buffer_handle, range, cx)
15274        }))
15275    }
15276
15277    fn resolve_inlay_hint(
15278        &self,
15279        hint: InlayHint,
15280        buffer_handle: Entity<Buffer>,
15281        server_id: LanguageServerId,
15282        cx: &mut App,
15283    ) -> Option<Task<anyhow::Result<InlayHint>>> {
15284        Some(self.update(cx, |project, cx| {
15285            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
15286        }))
15287    }
15288
15289    fn range_for_rename(
15290        &self,
15291        buffer: &Entity<Buffer>,
15292        position: text::Anchor,
15293        cx: &mut App,
15294    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
15295        Some(self.update(cx, |project, cx| {
15296            let buffer = buffer.clone();
15297            let task = project.prepare_rename(buffer.clone(), position, cx);
15298            cx.spawn(|_, mut cx| async move {
15299                Ok(match task.await? {
15300                    PrepareRenameResponse::Success(range) => Some(range),
15301                    PrepareRenameResponse::InvalidPosition => None,
15302                    PrepareRenameResponse::OnlyUnpreparedRenameSupported => {
15303                        // Fallback on using TreeSitter info to determine identifier range
15304                        buffer.update(&mut cx, |buffer, _| {
15305                            let snapshot = buffer.snapshot();
15306                            let (range, kind) = snapshot.surrounding_word(position);
15307                            if kind != Some(CharKind::Word) {
15308                                return None;
15309                            }
15310                            Some(
15311                                snapshot.anchor_before(range.start)
15312                                    ..snapshot.anchor_after(range.end),
15313                            )
15314                        })?
15315                    }
15316                })
15317            })
15318        }))
15319    }
15320
15321    fn perform_rename(
15322        &self,
15323        buffer: &Entity<Buffer>,
15324        position: text::Anchor,
15325        new_name: String,
15326        cx: &mut App,
15327    ) -> Option<Task<Result<ProjectTransaction>>> {
15328        Some(self.update(cx, |project, cx| {
15329            project.perform_rename(buffer.clone(), position, new_name, cx)
15330        }))
15331    }
15332}
15333
15334fn inlay_hint_settings(
15335    location: Anchor,
15336    snapshot: &MultiBufferSnapshot,
15337    cx: &mut Context<Editor>,
15338) -> InlayHintSettings {
15339    let file = snapshot.file_at(location);
15340    let language = snapshot.language_at(location).map(|l| l.name());
15341    language_settings(language, file, cx).inlay_hints
15342}
15343
15344fn consume_contiguous_rows(
15345    contiguous_row_selections: &mut Vec<Selection<Point>>,
15346    selection: &Selection<Point>,
15347    display_map: &DisplaySnapshot,
15348    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
15349) -> (MultiBufferRow, MultiBufferRow) {
15350    contiguous_row_selections.push(selection.clone());
15351    let start_row = MultiBufferRow(selection.start.row);
15352    let mut end_row = ending_row(selection, display_map);
15353
15354    while let Some(next_selection) = selections.peek() {
15355        if next_selection.start.row <= end_row.0 {
15356            end_row = ending_row(next_selection, display_map);
15357            contiguous_row_selections.push(selections.next().unwrap().clone());
15358        } else {
15359            break;
15360        }
15361    }
15362    (start_row, end_row)
15363}
15364
15365fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
15366    if next_selection.end.column > 0 || next_selection.is_empty() {
15367        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
15368    } else {
15369        MultiBufferRow(next_selection.end.row)
15370    }
15371}
15372
15373impl EditorSnapshot {
15374    pub fn remote_selections_in_range<'a>(
15375        &'a self,
15376        range: &'a Range<Anchor>,
15377        collaboration_hub: &dyn CollaborationHub,
15378        cx: &'a App,
15379    ) -> impl 'a + Iterator<Item = RemoteSelection> {
15380        let participant_names = collaboration_hub.user_names(cx);
15381        let participant_indices = collaboration_hub.user_participant_indices(cx);
15382        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
15383        let collaborators_by_replica_id = collaborators_by_peer_id
15384            .iter()
15385            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
15386            .collect::<HashMap<_, _>>();
15387        self.buffer_snapshot
15388            .selections_in_range(range, false)
15389            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
15390                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
15391                let participant_index = participant_indices.get(&collaborator.user_id).copied();
15392                let user_name = participant_names.get(&collaborator.user_id).cloned();
15393                Some(RemoteSelection {
15394                    replica_id,
15395                    selection,
15396                    cursor_shape,
15397                    line_mode,
15398                    participant_index,
15399                    peer_id: collaborator.peer_id,
15400                    user_name,
15401                })
15402            })
15403    }
15404
15405    pub fn hunks_for_ranges(
15406        &self,
15407        ranges: impl Iterator<Item = Range<Point>>,
15408    ) -> Vec<MultiBufferDiffHunk> {
15409        let mut hunks = Vec::new();
15410        let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
15411            HashMap::default();
15412        for query_range in ranges {
15413            let query_rows =
15414                MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
15415            for hunk in self.buffer_snapshot.diff_hunks_in_range(
15416                Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
15417            ) {
15418                // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
15419                // when the caret is just above or just below the deleted hunk.
15420                let allow_adjacent = hunk.status() == DiffHunkStatus::Removed;
15421                let related_to_selection = if allow_adjacent {
15422                    hunk.row_range.overlaps(&query_rows)
15423                        || hunk.row_range.start == query_rows.end
15424                        || hunk.row_range.end == query_rows.start
15425                } else {
15426                    hunk.row_range.overlaps(&query_rows)
15427                };
15428                if related_to_selection {
15429                    if !processed_buffer_rows
15430                        .entry(hunk.buffer_id)
15431                        .or_default()
15432                        .insert(hunk.buffer_range.start..hunk.buffer_range.end)
15433                    {
15434                        continue;
15435                    }
15436                    hunks.push(hunk);
15437                }
15438            }
15439        }
15440
15441        hunks
15442    }
15443
15444    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
15445        self.display_snapshot.buffer_snapshot.language_at(position)
15446    }
15447
15448    pub fn is_focused(&self) -> bool {
15449        self.is_focused
15450    }
15451
15452    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
15453        self.placeholder_text.as_ref()
15454    }
15455
15456    pub fn scroll_position(&self) -> gpui::Point<f32> {
15457        self.scroll_anchor.scroll_position(&self.display_snapshot)
15458    }
15459
15460    fn gutter_dimensions(
15461        &self,
15462        font_id: FontId,
15463        font_size: Pixels,
15464        max_line_number_width: Pixels,
15465        cx: &App,
15466    ) -> Option<GutterDimensions> {
15467        if !self.show_gutter {
15468            return None;
15469        }
15470
15471        let descent = cx.text_system().descent(font_id, font_size);
15472        let em_width = cx.text_system().em_width(font_id, font_size).log_err()?;
15473        let em_advance = cx.text_system().em_advance(font_id, font_size).log_err()?;
15474
15475        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
15476            matches!(
15477                ProjectSettings::get_global(cx).git.git_gutter,
15478                Some(GitGutterSetting::TrackedFiles)
15479            )
15480        });
15481        let gutter_settings = EditorSettings::get_global(cx).gutter;
15482        let show_line_numbers = self
15483            .show_line_numbers
15484            .unwrap_or(gutter_settings.line_numbers);
15485        let line_gutter_width = if show_line_numbers {
15486            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
15487            let min_width_for_number_on_gutter = em_advance * 4.0;
15488            max_line_number_width.max(min_width_for_number_on_gutter)
15489        } else {
15490            0.0.into()
15491        };
15492
15493        let show_code_actions = self
15494            .show_code_actions
15495            .unwrap_or(gutter_settings.code_actions);
15496
15497        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
15498
15499        let git_blame_entries_width =
15500            self.git_blame_gutter_max_author_length
15501                .map(|max_author_length| {
15502                    const MAX_RELATIVE_TIMESTAMP: &str = "60 minutes ago";
15503
15504                    /// The number of characters to dedicate to gaps and margins.
15505                    const SPACING_WIDTH: usize = 4;
15506
15507                    let max_char_count = max_author_length
15508                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
15509                        + ::git::SHORT_SHA_LENGTH
15510                        + MAX_RELATIVE_TIMESTAMP.len()
15511                        + SPACING_WIDTH;
15512
15513                    em_advance * max_char_count
15514                });
15515
15516        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
15517        left_padding += if show_code_actions || show_runnables {
15518            em_width * 3.0
15519        } else if show_git_gutter && show_line_numbers {
15520            em_width * 2.0
15521        } else if show_git_gutter || show_line_numbers {
15522            em_width
15523        } else {
15524            px(0.)
15525        };
15526
15527        let right_padding = if gutter_settings.folds && show_line_numbers {
15528            em_width * 4.0
15529        } else if gutter_settings.folds {
15530            em_width * 3.0
15531        } else if show_line_numbers {
15532            em_width
15533        } else {
15534            px(0.)
15535        };
15536
15537        Some(GutterDimensions {
15538            left_padding,
15539            right_padding,
15540            width: line_gutter_width + left_padding + right_padding,
15541            margin: -descent,
15542            git_blame_entries_width,
15543        })
15544    }
15545
15546    pub fn render_crease_toggle(
15547        &self,
15548        buffer_row: MultiBufferRow,
15549        row_contains_cursor: bool,
15550        editor: Entity<Editor>,
15551        window: &mut Window,
15552        cx: &mut App,
15553    ) -> Option<AnyElement> {
15554        let folded = self.is_line_folded(buffer_row);
15555        let mut is_foldable = false;
15556
15557        if let Some(crease) = self
15558            .crease_snapshot
15559            .query_row(buffer_row, &self.buffer_snapshot)
15560        {
15561            is_foldable = true;
15562            match crease {
15563                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
15564                    if let Some(render_toggle) = render_toggle {
15565                        let toggle_callback =
15566                            Arc::new(move |folded, window: &mut Window, cx: &mut App| {
15567                                if folded {
15568                                    editor.update(cx, |editor, cx| {
15569                                        editor.fold_at(&crate::FoldAt { buffer_row }, window, cx)
15570                                    });
15571                                } else {
15572                                    editor.update(cx, |editor, cx| {
15573                                        editor.unfold_at(
15574                                            &crate::UnfoldAt { buffer_row },
15575                                            window,
15576                                            cx,
15577                                        )
15578                                    });
15579                                }
15580                            });
15581                        return Some((render_toggle)(
15582                            buffer_row,
15583                            folded,
15584                            toggle_callback,
15585                            window,
15586                            cx,
15587                        ));
15588                    }
15589                }
15590            }
15591        }
15592
15593        is_foldable |= self.starts_indent(buffer_row);
15594
15595        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
15596            Some(
15597                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
15598                    .toggle_state(folded)
15599                    .on_click(window.listener_for(&editor, move |this, _e, window, cx| {
15600                        if folded {
15601                            this.unfold_at(&UnfoldAt { buffer_row }, window, cx);
15602                        } else {
15603                            this.fold_at(&FoldAt { buffer_row }, window, cx);
15604                        }
15605                    }))
15606                    .into_any_element(),
15607            )
15608        } else {
15609            None
15610        }
15611    }
15612
15613    pub fn render_crease_trailer(
15614        &self,
15615        buffer_row: MultiBufferRow,
15616        window: &mut Window,
15617        cx: &mut App,
15618    ) -> Option<AnyElement> {
15619        let folded = self.is_line_folded(buffer_row);
15620        if let Crease::Inline { render_trailer, .. } = self
15621            .crease_snapshot
15622            .query_row(buffer_row, &self.buffer_snapshot)?
15623        {
15624            let render_trailer = render_trailer.as_ref()?;
15625            Some(render_trailer(buffer_row, folded, window, cx))
15626        } else {
15627            None
15628        }
15629    }
15630}
15631
15632impl Deref for EditorSnapshot {
15633    type Target = DisplaySnapshot;
15634
15635    fn deref(&self) -> &Self::Target {
15636        &self.display_snapshot
15637    }
15638}
15639
15640#[derive(Clone, Debug, PartialEq, Eq)]
15641pub enum EditorEvent {
15642    InputIgnored {
15643        text: Arc<str>,
15644    },
15645    InputHandled {
15646        utf16_range_to_replace: Option<Range<isize>>,
15647        text: Arc<str>,
15648    },
15649    ExcerptsAdded {
15650        buffer: Entity<Buffer>,
15651        predecessor: ExcerptId,
15652        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
15653    },
15654    ExcerptsRemoved {
15655        ids: Vec<ExcerptId>,
15656    },
15657    BufferFoldToggled {
15658        ids: Vec<ExcerptId>,
15659        folded: bool,
15660    },
15661    ExcerptsEdited {
15662        ids: Vec<ExcerptId>,
15663    },
15664    ExcerptsExpanded {
15665        ids: Vec<ExcerptId>,
15666    },
15667    BufferEdited,
15668    Edited {
15669        transaction_id: clock::Lamport,
15670    },
15671    Reparsed(BufferId),
15672    Focused,
15673    FocusedIn,
15674    Blurred,
15675    DirtyChanged,
15676    Saved,
15677    TitleChanged,
15678    DiffBaseChanged,
15679    SelectionsChanged {
15680        local: bool,
15681    },
15682    ScrollPositionChanged {
15683        local: bool,
15684        autoscroll: bool,
15685    },
15686    Closed,
15687    TransactionUndone {
15688        transaction_id: clock::Lamport,
15689    },
15690    TransactionBegun {
15691        transaction_id: clock::Lamport,
15692    },
15693    Reloaded,
15694    CursorShapeChanged,
15695}
15696
15697impl EventEmitter<EditorEvent> for Editor {}
15698
15699impl Focusable for Editor {
15700    fn focus_handle(&self, _cx: &App) -> FocusHandle {
15701        self.focus_handle.clone()
15702    }
15703}
15704
15705impl Render for Editor {
15706    fn render<'a>(&mut self, _: &mut Window, cx: &mut Context<'a, Self>) -> impl IntoElement {
15707        let settings = ThemeSettings::get_global(cx);
15708
15709        let mut text_style = match self.mode {
15710            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
15711                color: cx.theme().colors().editor_foreground,
15712                font_family: settings.ui_font.family.clone(),
15713                font_features: settings.ui_font.features.clone(),
15714                font_fallbacks: settings.ui_font.fallbacks.clone(),
15715                font_size: rems(0.875).into(),
15716                font_weight: settings.ui_font.weight,
15717                line_height: relative(settings.buffer_line_height.value()),
15718                ..Default::default()
15719            },
15720            EditorMode::Full => TextStyle {
15721                color: cx.theme().colors().editor_foreground,
15722                font_family: settings.buffer_font.family.clone(),
15723                font_features: settings.buffer_font.features.clone(),
15724                font_fallbacks: settings.buffer_font.fallbacks.clone(),
15725                font_size: settings.buffer_font_size().into(),
15726                font_weight: settings.buffer_font.weight,
15727                line_height: relative(settings.buffer_line_height.value()),
15728                ..Default::default()
15729            },
15730        };
15731        if let Some(text_style_refinement) = &self.text_style_refinement {
15732            text_style.refine(text_style_refinement)
15733        }
15734
15735        let background = match self.mode {
15736            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
15737            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
15738            EditorMode::Full => cx.theme().colors().editor_background,
15739        };
15740
15741        EditorElement::new(
15742            &cx.entity(),
15743            EditorStyle {
15744                background,
15745                local_player: cx.theme().players().local(),
15746                text: text_style,
15747                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
15748                syntax: cx.theme().syntax().clone(),
15749                status: cx.theme().status().clone(),
15750                inlay_hints_style: make_inlay_hints_style(cx),
15751                inline_completion_styles: make_suggestion_styles(cx),
15752                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
15753            },
15754        )
15755    }
15756}
15757
15758impl EntityInputHandler for Editor {
15759    fn text_for_range(
15760        &mut self,
15761        range_utf16: Range<usize>,
15762        adjusted_range: &mut Option<Range<usize>>,
15763        _: &mut Window,
15764        cx: &mut Context<Self>,
15765    ) -> Option<String> {
15766        let snapshot = self.buffer.read(cx).read(cx);
15767        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
15768        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
15769        if (start.0..end.0) != range_utf16 {
15770            adjusted_range.replace(start.0..end.0);
15771        }
15772        Some(snapshot.text_for_range(start..end).collect())
15773    }
15774
15775    fn selected_text_range(
15776        &mut self,
15777        ignore_disabled_input: bool,
15778        _: &mut Window,
15779        cx: &mut Context<Self>,
15780    ) -> Option<UTF16Selection> {
15781        // Prevent the IME menu from appearing when holding down an alphabetic key
15782        // while input is disabled.
15783        if !ignore_disabled_input && !self.input_enabled {
15784            return None;
15785        }
15786
15787        let selection = self.selections.newest::<OffsetUtf16>(cx);
15788        let range = selection.range();
15789
15790        Some(UTF16Selection {
15791            range: range.start.0..range.end.0,
15792            reversed: selection.reversed,
15793        })
15794    }
15795
15796    fn marked_text_range(&self, _: &mut Window, cx: &mut Context<Self>) -> Option<Range<usize>> {
15797        let snapshot = self.buffer.read(cx).read(cx);
15798        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
15799        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
15800    }
15801
15802    fn unmark_text(&mut self, _: &mut Window, cx: &mut Context<Self>) {
15803        self.clear_highlights::<InputComposition>(cx);
15804        self.ime_transaction.take();
15805    }
15806
15807    fn replace_text_in_range(
15808        &mut self,
15809        range_utf16: Option<Range<usize>>,
15810        text: &str,
15811        window: &mut Window,
15812        cx: &mut Context<Self>,
15813    ) {
15814        if !self.input_enabled {
15815            cx.emit(EditorEvent::InputIgnored { text: text.into() });
15816            return;
15817        }
15818
15819        self.transact(window, cx, |this, window, cx| {
15820            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
15821                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15822                Some(this.selection_replacement_ranges(range_utf16, cx))
15823            } else {
15824                this.marked_text_ranges(cx)
15825            };
15826
15827            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
15828                let newest_selection_id = this.selections.newest_anchor().id;
15829                this.selections
15830                    .all::<OffsetUtf16>(cx)
15831                    .iter()
15832                    .zip(ranges_to_replace.iter())
15833                    .find_map(|(selection, range)| {
15834                        if selection.id == newest_selection_id {
15835                            Some(
15836                                (range.start.0 as isize - selection.head().0 as isize)
15837                                    ..(range.end.0 as isize - selection.head().0 as isize),
15838                            )
15839                        } else {
15840                            None
15841                        }
15842                    })
15843            });
15844
15845            cx.emit(EditorEvent::InputHandled {
15846                utf16_range_to_replace: range_to_replace,
15847                text: text.into(),
15848            });
15849
15850            if let Some(new_selected_ranges) = new_selected_ranges {
15851                this.change_selections(None, window, cx, |selections| {
15852                    selections.select_ranges(new_selected_ranges)
15853                });
15854                this.backspace(&Default::default(), window, cx);
15855            }
15856
15857            this.handle_input(text, window, cx);
15858        });
15859
15860        if let Some(transaction) = self.ime_transaction {
15861            self.buffer.update(cx, |buffer, cx| {
15862                buffer.group_until_transaction(transaction, cx);
15863            });
15864        }
15865
15866        self.unmark_text(window, cx);
15867    }
15868
15869    fn replace_and_mark_text_in_range(
15870        &mut self,
15871        range_utf16: Option<Range<usize>>,
15872        text: &str,
15873        new_selected_range_utf16: Option<Range<usize>>,
15874        window: &mut Window,
15875        cx: &mut Context<Self>,
15876    ) {
15877        if !self.input_enabled {
15878            return;
15879        }
15880
15881        let transaction = self.transact(window, cx, |this, window, cx| {
15882            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
15883                let snapshot = this.buffer.read(cx).read(cx);
15884                if let Some(relative_range_utf16) = range_utf16.as_ref() {
15885                    for marked_range in &mut marked_ranges {
15886                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
15887                        marked_range.start.0 += relative_range_utf16.start;
15888                        marked_range.start =
15889                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
15890                        marked_range.end =
15891                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
15892                    }
15893                }
15894                Some(marked_ranges)
15895            } else if let Some(range_utf16) = range_utf16 {
15896                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
15897                Some(this.selection_replacement_ranges(range_utf16, cx))
15898            } else {
15899                None
15900            };
15901
15902            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
15903                let newest_selection_id = this.selections.newest_anchor().id;
15904                this.selections
15905                    .all::<OffsetUtf16>(cx)
15906                    .iter()
15907                    .zip(ranges_to_replace.iter())
15908                    .find_map(|(selection, range)| {
15909                        if selection.id == newest_selection_id {
15910                            Some(
15911                                (range.start.0 as isize - selection.head().0 as isize)
15912                                    ..(range.end.0 as isize - selection.head().0 as isize),
15913                            )
15914                        } else {
15915                            None
15916                        }
15917                    })
15918            });
15919
15920            cx.emit(EditorEvent::InputHandled {
15921                utf16_range_to_replace: range_to_replace,
15922                text: text.into(),
15923            });
15924
15925            if let Some(ranges) = ranges_to_replace {
15926                this.change_selections(None, window, cx, |s| s.select_ranges(ranges));
15927            }
15928
15929            let marked_ranges = {
15930                let snapshot = this.buffer.read(cx).read(cx);
15931                this.selections
15932                    .disjoint_anchors()
15933                    .iter()
15934                    .map(|selection| {
15935                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
15936                    })
15937                    .collect::<Vec<_>>()
15938            };
15939
15940            if text.is_empty() {
15941                this.unmark_text(window, cx);
15942            } else {
15943                this.highlight_text::<InputComposition>(
15944                    marked_ranges.clone(),
15945                    HighlightStyle {
15946                        underline: Some(UnderlineStyle {
15947                            thickness: px(1.),
15948                            color: None,
15949                            wavy: false,
15950                        }),
15951                        ..Default::default()
15952                    },
15953                    cx,
15954                );
15955            }
15956
15957            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
15958            let use_autoclose = this.use_autoclose;
15959            let use_auto_surround = this.use_auto_surround;
15960            this.set_use_autoclose(false);
15961            this.set_use_auto_surround(false);
15962            this.handle_input(text, window, cx);
15963            this.set_use_autoclose(use_autoclose);
15964            this.set_use_auto_surround(use_auto_surround);
15965
15966            if let Some(new_selected_range) = new_selected_range_utf16 {
15967                let snapshot = this.buffer.read(cx).read(cx);
15968                let new_selected_ranges = marked_ranges
15969                    .into_iter()
15970                    .map(|marked_range| {
15971                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
15972                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
15973                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
15974                        snapshot.clip_offset_utf16(new_start, Bias::Left)
15975                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
15976                    })
15977                    .collect::<Vec<_>>();
15978
15979                drop(snapshot);
15980                this.change_selections(None, window, cx, |selections| {
15981                    selections.select_ranges(new_selected_ranges)
15982                });
15983            }
15984        });
15985
15986        self.ime_transaction = self.ime_transaction.or(transaction);
15987        if let Some(transaction) = self.ime_transaction {
15988            self.buffer.update(cx, |buffer, cx| {
15989                buffer.group_until_transaction(transaction, cx);
15990            });
15991        }
15992
15993        if self.text_highlights::<InputComposition>(cx).is_none() {
15994            self.ime_transaction.take();
15995        }
15996    }
15997
15998    fn bounds_for_range(
15999        &mut self,
16000        range_utf16: Range<usize>,
16001        element_bounds: gpui::Bounds<Pixels>,
16002        window: &mut Window,
16003        cx: &mut Context<Self>,
16004    ) -> Option<gpui::Bounds<Pixels>> {
16005        let text_layout_details = self.text_layout_details(window);
16006        let gpui::Size {
16007            width: em_width,
16008            height: line_height,
16009        } = self.character_size(window);
16010
16011        let snapshot = self.snapshot(window, cx);
16012        let scroll_position = snapshot.scroll_position();
16013        let scroll_left = scroll_position.x * em_width;
16014
16015        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
16016        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
16017            + self.gutter_dimensions.width
16018            + self.gutter_dimensions.margin;
16019        let y = line_height * (start.row().as_f32() - scroll_position.y);
16020
16021        Some(Bounds {
16022            origin: element_bounds.origin + point(x, y),
16023            size: size(em_width, line_height),
16024        })
16025    }
16026
16027    fn character_index_for_point(
16028        &mut self,
16029        point: gpui::Point<Pixels>,
16030        _window: &mut Window,
16031        _cx: &mut Context<Self>,
16032    ) -> Option<usize> {
16033        let position_map = self.last_position_map.as_ref()?;
16034        if !position_map.text_hitbox.contains(&point) {
16035            return None;
16036        }
16037        let display_point = position_map.point_for_position(point).previous_valid;
16038        let anchor = position_map
16039            .snapshot
16040            .display_point_to_anchor(display_point, Bias::Left);
16041        let utf16_offset = anchor.to_offset_utf16(&position_map.snapshot.buffer_snapshot);
16042        Some(utf16_offset.0)
16043    }
16044}
16045
16046trait SelectionExt {
16047    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
16048    fn spanned_rows(
16049        &self,
16050        include_end_if_at_line_start: bool,
16051        map: &DisplaySnapshot,
16052    ) -> Range<MultiBufferRow>;
16053}
16054
16055impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
16056    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
16057        let start = self
16058            .start
16059            .to_point(&map.buffer_snapshot)
16060            .to_display_point(map);
16061        let end = self
16062            .end
16063            .to_point(&map.buffer_snapshot)
16064            .to_display_point(map);
16065        if self.reversed {
16066            end..start
16067        } else {
16068            start..end
16069        }
16070    }
16071
16072    fn spanned_rows(
16073        &self,
16074        include_end_if_at_line_start: bool,
16075        map: &DisplaySnapshot,
16076    ) -> Range<MultiBufferRow> {
16077        let start = self.start.to_point(&map.buffer_snapshot);
16078        let mut end = self.end.to_point(&map.buffer_snapshot);
16079        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
16080            end.row -= 1;
16081        }
16082
16083        let buffer_start = map.prev_line_boundary(start).0;
16084        let buffer_end = map.next_line_boundary(end).0;
16085        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
16086    }
16087}
16088
16089impl<T: InvalidationRegion> InvalidationStack<T> {
16090    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
16091    where
16092        S: Clone + ToOffset,
16093    {
16094        while let Some(region) = self.last() {
16095            let all_selections_inside_invalidation_ranges =
16096                if selections.len() == region.ranges().len() {
16097                    selections
16098                        .iter()
16099                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
16100                        .all(|(selection, invalidation_range)| {
16101                            let head = selection.head().to_offset(buffer);
16102                            invalidation_range.start <= head && invalidation_range.end >= head
16103                        })
16104                } else {
16105                    false
16106                };
16107
16108            if all_selections_inside_invalidation_ranges {
16109                break;
16110            } else {
16111                self.pop();
16112            }
16113        }
16114    }
16115}
16116
16117impl<T> Default for InvalidationStack<T> {
16118    fn default() -> Self {
16119        Self(Default::default())
16120    }
16121}
16122
16123impl<T> Deref for InvalidationStack<T> {
16124    type Target = Vec<T>;
16125
16126    fn deref(&self) -> &Self::Target {
16127        &self.0
16128    }
16129}
16130
16131impl<T> DerefMut for InvalidationStack<T> {
16132    fn deref_mut(&mut self) -> &mut Self::Target {
16133        &mut self.0
16134    }
16135}
16136
16137impl InvalidationRegion for SnippetState {
16138    fn ranges(&self) -> &[Range<Anchor>] {
16139        &self.ranges[self.active_index]
16140    }
16141}
16142
16143pub fn diagnostic_block_renderer(
16144    diagnostic: Diagnostic,
16145    max_message_rows: Option<u8>,
16146    allow_closing: bool,
16147    _is_valid: bool,
16148) -> RenderBlock {
16149    let (text_without_backticks, code_ranges) =
16150        highlight_diagnostic_message(&diagnostic, max_message_rows);
16151
16152    Arc::new(move |cx: &mut BlockContext| {
16153        let group_id: SharedString = cx.block_id.to_string().into();
16154
16155        let mut text_style = cx.window.text_style().clone();
16156        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
16157        let theme_settings = ThemeSettings::get_global(cx);
16158        text_style.font_family = theme_settings.buffer_font.family.clone();
16159        text_style.font_style = theme_settings.buffer_font.style;
16160        text_style.font_features = theme_settings.buffer_font.features.clone();
16161        text_style.font_weight = theme_settings.buffer_font.weight;
16162
16163        let multi_line_diagnostic = diagnostic.message.contains('\n');
16164
16165        let buttons = |diagnostic: &Diagnostic| {
16166            if multi_line_diagnostic {
16167                v_flex()
16168            } else {
16169                h_flex()
16170            }
16171            .when(allow_closing, |div| {
16172                div.children(diagnostic.is_primary.then(|| {
16173                    IconButton::new("close-block", IconName::XCircle)
16174                        .icon_color(Color::Muted)
16175                        .size(ButtonSize::Compact)
16176                        .style(ButtonStyle::Transparent)
16177                        .visible_on_hover(group_id.clone())
16178                        .on_click(move |_click, window, cx| {
16179                            window.dispatch_action(Box::new(Cancel), cx)
16180                        })
16181                        .tooltip(|window, cx| {
16182                            Tooltip::for_action("Close Diagnostics", &Cancel, window, cx)
16183                        })
16184                }))
16185            })
16186            .child(
16187                IconButton::new("copy-block", IconName::Copy)
16188                    .icon_color(Color::Muted)
16189                    .size(ButtonSize::Compact)
16190                    .style(ButtonStyle::Transparent)
16191                    .visible_on_hover(group_id.clone())
16192                    .on_click({
16193                        let message = diagnostic.message.clone();
16194                        move |_click, _, cx| {
16195                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
16196                        }
16197                    })
16198                    .tooltip(Tooltip::text("Copy diagnostic message")),
16199            )
16200        };
16201
16202        let icon_size = buttons(&diagnostic).into_any_element().layout_as_root(
16203            AvailableSpace::min_size(),
16204            cx.window,
16205            cx.app,
16206        );
16207
16208        h_flex()
16209            .id(cx.block_id)
16210            .group(group_id.clone())
16211            .relative()
16212            .size_full()
16213            .block_mouse_down()
16214            .pl(cx.gutter_dimensions.width)
16215            .w(cx.max_width - cx.gutter_dimensions.full_width())
16216            .child(
16217                div()
16218                    .flex()
16219                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
16220                    .flex_shrink(),
16221            )
16222            .child(buttons(&diagnostic))
16223            .child(div().flex().flex_shrink_0().child(
16224                StyledText::new(text_without_backticks.clone()).with_highlights(
16225                    &text_style,
16226                    code_ranges.iter().map(|range| {
16227                        (
16228                            range.clone(),
16229                            HighlightStyle {
16230                                font_weight: Some(FontWeight::BOLD),
16231                                ..Default::default()
16232                            },
16233                        )
16234                    }),
16235                ),
16236            ))
16237            .into_any_element()
16238    })
16239}
16240
16241fn inline_completion_edit_text(
16242    current_snapshot: &BufferSnapshot,
16243    edits: &[(Range<Anchor>, String)],
16244    edit_preview: &EditPreview,
16245    include_deletions: bool,
16246    cx: &App,
16247) -> HighlightedText {
16248    let edits = edits
16249        .iter()
16250        .map(|(anchor, text)| {
16251            (
16252                anchor.start.text_anchor..anchor.end.text_anchor,
16253                text.clone(),
16254            )
16255        })
16256        .collect::<Vec<_>>();
16257
16258    edit_preview.highlight_edits(current_snapshot, &edits, include_deletions, cx)
16259}
16260
16261pub fn highlight_diagnostic_message(
16262    diagnostic: &Diagnostic,
16263    mut max_message_rows: Option<u8>,
16264) -> (SharedString, Vec<Range<usize>>) {
16265    let mut text_without_backticks = String::new();
16266    let mut code_ranges = Vec::new();
16267
16268    if let Some(source) = &diagnostic.source {
16269        text_without_backticks.push_str(source);
16270        code_ranges.push(0..source.len());
16271        text_without_backticks.push_str(": ");
16272    }
16273
16274    let mut prev_offset = 0;
16275    let mut in_code_block = false;
16276    let has_row_limit = max_message_rows.is_some();
16277    let mut newline_indices = diagnostic
16278        .message
16279        .match_indices('\n')
16280        .filter(|_| has_row_limit)
16281        .map(|(ix, _)| ix)
16282        .fuse()
16283        .peekable();
16284
16285    for (quote_ix, _) in diagnostic
16286        .message
16287        .match_indices('`')
16288        .chain([(diagnostic.message.len(), "")])
16289    {
16290        let mut first_newline_ix = None;
16291        let mut last_newline_ix = None;
16292        while let Some(newline_ix) = newline_indices.peek() {
16293            if *newline_ix < quote_ix {
16294                if first_newline_ix.is_none() {
16295                    first_newline_ix = Some(*newline_ix);
16296                }
16297                last_newline_ix = Some(*newline_ix);
16298
16299                if let Some(rows_left) = &mut max_message_rows {
16300                    if *rows_left == 0 {
16301                        break;
16302                    } else {
16303                        *rows_left -= 1;
16304                    }
16305                }
16306                let _ = newline_indices.next();
16307            } else {
16308                break;
16309            }
16310        }
16311        let prev_len = text_without_backticks.len();
16312        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
16313        text_without_backticks.push_str(new_text);
16314        if in_code_block {
16315            code_ranges.push(prev_len..text_without_backticks.len());
16316        }
16317        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
16318        in_code_block = !in_code_block;
16319        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
16320            text_without_backticks.push_str("...");
16321            break;
16322        }
16323    }
16324
16325    (text_without_backticks.into(), code_ranges)
16326}
16327
16328fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
16329    match severity {
16330        DiagnosticSeverity::ERROR => colors.error,
16331        DiagnosticSeverity::WARNING => colors.warning,
16332        DiagnosticSeverity::INFORMATION => colors.info,
16333        DiagnosticSeverity::HINT => colors.info,
16334        _ => colors.ignored,
16335    }
16336}
16337
16338pub fn styled_runs_for_code_label<'a>(
16339    label: &'a CodeLabel,
16340    syntax_theme: &'a theme::SyntaxTheme,
16341) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
16342    let fade_out = HighlightStyle {
16343        fade_out: Some(0.35),
16344        ..Default::default()
16345    };
16346
16347    let mut prev_end = label.filter_range.end;
16348    label
16349        .runs
16350        .iter()
16351        .enumerate()
16352        .flat_map(move |(ix, (range, highlight_id))| {
16353            let style = if let Some(style) = highlight_id.style(syntax_theme) {
16354                style
16355            } else {
16356                return Default::default();
16357            };
16358            let mut muted_style = style;
16359            muted_style.highlight(fade_out);
16360
16361            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
16362            if range.start >= label.filter_range.end {
16363                if range.start > prev_end {
16364                    runs.push((prev_end..range.start, fade_out));
16365                }
16366                runs.push((range.clone(), muted_style));
16367            } else if range.end <= label.filter_range.end {
16368                runs.push((range.clone(), style));
16369            } else {
16370                runs.push((range.start..label.filter_range.end, style));
16371                runs.push((label.filter_range.end..range.end, muted_style));
16372            }
16373            prev_end = cmp::max(prev_end, range.end);
16374
16375            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
16376                runs.push((prev_end..label.text.len(), fade_out));
16377            }
16378
16379            runs
16380        })
16381}
16382
16383pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
16384    let mut prev_index = 0;
16385    let mut prev_codepoint: Option<char> = None;
16386    text.char_indices()
16387        .chain([(text.len(), '\0')])
16388        .filter_map(move |(index, codepoint)| {
16389            let prev_codepoint = prev_codepoint.replace(codepoint)?;
16390            let is_boundary = index == text.len()
16391                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
16392                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
16393            if is_boundary {
16394                let chunk = &text[prev_index..index];
16395                prev_index = index;
16396                Some(chunk)
16397            } else {
16398                None
16399            }
16400        })
16401}
16402
16403pub trait RangeToAnchorExt: Sized {
16404    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
16405
16406    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
16407        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
16408        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
16409    }
16410}
16411
16412impl<T: ToOffset> RangeToAnchorExt for Range<T> {
16413    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
16414        let start_offset = self.start.to_offset(snapshot);
16415        let end_offset = self.end.to_offset(snapshot);
16416        if start_offset == end_offset {
16417            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
16418        } else {
16419            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
16420        }
16421    }
16422}
16423
16424pub trait RowExt {
16425    fn as_f32(&self) -> f32;
16426
16427    fn next_row(&self) -> Self;
16428
16429    fn previous_row(&self) -> Self;
16430
16431    fn minus(&self, other: Self) -> u32;
16432}
16433
16434impl RowExt for DisplayRow {
16435    fn as_f32(&self) -> f32 {
16436        self.0 as f32
16437    }
16438
16439    fn next_row(&self) -> Self {
16440        Self(self.0 + 1)
16441    }
16442
16443    fn previous_row(&self) -> Self {
16444        Self(self.0.saturating_sub(1))
16445    }
16446
16447    fn minus(&self, other: Self) -> u32 {
16448        self.0 - other.0
16449    }
16450}
16451
16452impl RowExt for MultiBufferRow {
16453    fn as_f32(&self) -> f32 {
16454        self.0 as f32
16455    }
16456
16457    fn next_row(&self) -> Self {
16458        Self(self.0 + 1)
16459    }
16460
16461    fn previous_row(&self) -> Self {
16462        Self(self.0.saturating_sub(1))
16463    }
16464
16465    fn minus(&self, other: Self) -> u32 {
16466        self.0 - other.0
16467    }
16468}
16469
16470trait RowRangeExt {
16471    type Row;
16472
16473    fn len(&self) -> usize;
16474
16475    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
16476}
16477
16478impl RowRangeExt for Range<MultiBufferRow> {
16479    type Row = MultiBufferRow;
16480
16481    fn len(&self) -> usize {
16482        (self.end.0 - self.start.0) as usize
16483    }
16484
16485    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
16486        (self.start.0..self.end.0).map(MultiBufferRow)
16487    }
16488}
16489
16490impl RowRangeExt for Range<DisplayRow> {
16491    type Row = DisplayRow;
16492
16493    fn len(&self) -> usize {
16494        (self.end.0 - self.start.0) as usize
16495    }
16496
16497    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
16498        (self.start.0..self.end.0).map(DisplayRow)
16499    }
16500}
16501
16502/// If select range has more than one line, we
16503/// just point the cursor to range.start.
16504fn collapse_multiline_range(range: Range<Point>) -> Range<Point> {
16505    if range.start.row == range.end.row {
16506        range
16507    } else {
16508        range.start..range.start
16509    }
16510}
16511pub struct KillRing(ClipboardItem);
16512impl Global for KillRing {}
16513
16514const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);
16515
16516fn all_edits_insertions_or_deletions(
16517    edits: &Vec<(Range<Anchor>, String)>,
16518    snapshot: &MultiBufferSnapshot,
16519) -> bool {
16520    let mut all_insertions = true;
16521    let mut all_deletions = true;
16522
16523    for (range, new_text) in edits.iter() {
16524        let range_is_empty = range.to_offset(&snapshot).is_empty();
16525        let text_is_empty = new_text.is_empty();
16526
16527        if range_is_empty != text_is_empty {
16528            if range_is_empty {
16529                all_deletions = false;
16530            } else {
16531                all_insertions = false;
16532            }
16533        } else {
16534            return false;
16535        }
16536
16537        if !all_insertions && !all_deletions {
16538            return false;
16539        }
16540    }
16541    all_insertions || all_deletions
16542}