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 hunk_diff;
   29mod indent_guides;
   30mod inlay_hint_cache;
   31pub mod items;
   32mod linked_editing_ranges;
   33mod lsp_ext;
   34mod mouse_context_menu;
   35pub mod movement;
   36mod persistence;
   37mod proposed_changes_editor;
   38mod rust_analyzer_ext;
   39pub mod scroll;
   40mod selections_collection;
   41pub mod tasks;
   42
   43#[cfg(test)]
   44mod editor_tests;
   45#[cfg(test)]
   46mod inline_completion_tests;
   47mod signature_help;
   48#[cfg(any(test, feature = "test-support"))]
   49pub mod test;
   50
   51use ::git::diff::DiffHunkStatus;
   52pub(crate) use actions::*;
   53pub use actions::{OpenExcerpts, OpenExcerptsSplit};
   54use aho_corasick::AhoCorasick;
   55use anyhow::{anyhow, Context as _, Result};
   56use blink_manager::BlinkManager;
   57use client::{Collaborator, ParticipantIndex};
   58use clock::ReplicaId;
   59use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
   60use convert_case::{Case, Casing};
   61use display_map::*;
   62pub use display_map::{DisplayPoint, FoldPlaceholder};
   63pub use editor_settings::{
   64    CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
   65};
   66pub use editor_settings_controls::*;
   67use element::LineWithInvisibles;
   68pub use element::{
   69    CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
   70};
   71use futures::{future, FutureExt};
   72use fuzzy::StringMatchCandidate;
   73
   74use code_context_menus::{
   75    AvailableCodeAction, CodeActionContents, CodeActionsItem, CodeActionsMenu, CodeContextMenu,
   76    CompletionEntry, CompletionsMenu, ContextMenuOrigin,
   77};
   78use git::blame::GitBlame;
   79use gpui::{
   80    div, impl_actions, point, prelude::*, px, relative, size, Action, AnyElement, AppContext,
   81    AsyncWindowContext, AvailableSpace, Bounds, ClipboardEntry, ClipboardItem, Context,
   82    DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent, FocusableView, FontId,
   83    FontWeight, Global, HighlightStyle, Hsla, InteractiveText, KeyContext, Model, ModelContext,
   84    MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString, Size, Styled, StyledText,
   85    Subscription, Task, TextStyle, TextStyleRefinement, UTF16Selection, UnderlineStyle,
   86    UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle,
   87    WeakView, WindowContext,
   88};
   89use highlight_matching_bracket::refresh_matching_bracket_highlights;
   90use hover_popover::{hide_hover, HoverState};
   91pub(crate) use hunk_diff::HoveredHunk;
   92use hunk_diff::{diff_hunk_to_display, DiffMap, DiffMapSnapshot};
   93use indent_guides::ActiveIndentGuidesState;
   94use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
   95pub use inline_completion::Direction;
   96use inline_completion::{InlineCompletionProvider, InlineCompletionProviderHandle};
   97pub use items::MAX_TAB_TITLE_LEN;
   98use itertools::Itertools;
   99use language::{
  100    language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
  101    markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
  102    CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
  103    Point, Selection, SelectionGoal, TransactionId,
  104};
  105use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
  106use linked_editing_ranges::refresh_linked_ranges;
  107use mouse_context_menu::MouseContextMenu;
  108pub use proposed_changes_editor::{
  109    ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
  110};
  111use similar::{ChangeTag, TextDiff};
  112use std::iter::Peekable;
  113use task::{ResolvedTask, TaskTemplate, TaskVariables};
  114
  115use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
  116pub use lsp::CompletionContext;
  117use lsp::{
  118    CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
  119    LanguageServerId, LanguageServerName,
  120};
  121
  122use movement::TextLayoutDetails;
  123pub use multi_buffer::{
  124    Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
  125    ToPoint,
  126};
  127use multi_buffer::{
  128    ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
  129};
  130use project::{
  131    lsp_store::{FormatTarget, FormatTrigger, OpenLspBufferHandle},
  132    project_settings::{GitGutterSetting, ProjectSettings},
  133    CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Location, LocationLink,
  134    LspStore, 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::{
  163    observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
  164    ThemeColors, ThemeSettings,
  165};
  166use ui::{
  167    h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
  168    PopoverMenuHandle, Tooltip,
  169};
  170use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
  171use workspace::item::{ItemHandle, PreviewTabsSettings};
  172use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
  173use workspace::{
  174    searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
  175};
  176use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
  177
  178use crate::hover_links::{find_url, find_url_from_range};
  179use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
  180
  181pub const FILE_HEADER_HEIGHT: u32 = 2;
  182pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
  183pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
  184pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
  185const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
  186const MAX_LINE_LEN: usize = 1024;
  187const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
  188const MAX_SELECTION_HISTORY_LEN: usize = 1024;
  189pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
  190#[doc(hidden)]
  191pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
  192
  193pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
  194pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
  195
  196pub fn render_parsed_markdown(
  197    element_id: impl Into<ElementId>,
  198    parsed: &language::ParsedMarkdown,
  199    editor_style: &EditorStyle,
  200    workspace: Option<WeakView<Workspace>>,
  201    cx: &mut WindowContext,
  202) -> InteractiveText {
  203    let code_span_background_color = cx
  204        .theme()
  205        .colors()
  206        .editor_document_highlight_read_background;
  207
  208    let highlights = gpui::combine_highlights(
  209        parsed.highlights.iter().filter_map(|(range, highlight)| {
  210            let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
  211            Some((range.clone(), highlight))
  212        }),
  213        parsed
  214            .regions
  215            .iter()
  216            .zip(&parsed.region_ranges)
  217            .filter_map(|(region, range)| {
  218                if region.code {
  219                    Some((
  220                        range.clone(),
  221                        HighlightStyle {
  222                            background_color: Some(code_span_background_color),
  223                            ..Default::default()
  224                        },
  225                    ))
  226                } else {
  227                    None
  228                }
  229            }),
  230    );
  231
  232    let mut links = Vec::new();
  233    let mut link_ranges = Vec::new();
  234    for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
  235        if let Some(link) = region.link.clone() {
  236            links.push(link);
  237            link_ranges.push(range.clone());
  238        }
  239    }
  240
  241    InteractiveText::new(
  242        element_id,
  243        StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
  244    )
  245    .on_click(link_ranges, move |clicked_range_ix, cx| {
  246        match &links[clicked_range_ix] {
  247            markdown::Link::Web { url } => cx.open_url(url),
  248            markdown::Link::Path { path } => {
  249                if let Some(workspace) = &workspace {
  250                    _ = workspace.update(cx, |workspace, cx| {
  251                        workspace.open_abs_path(path.clone(), false, cx).detach();
  252                    });
  253                }
  254            }
  255        }
  256    })
  257}
  258
  259#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
  260pub(crate) 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 DiffRowHighlight {}
  275enum DocumentHighlightRead {}
  276enum DocumentHighlightWrite {}
  277enum InputComposition {}
  278
  279#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  280pub enum Navigated {
  281    Yes,
  282    No,
  283}
  284
  285impl Navigated {
  286    pub fn from_bool(yes: bool) -> Navigated {
  287        if yes {
  288            Navigated::Yes
  289        } else {
  290            Navigated::No
  291        }
  292    }
  293}
  294
  295pub fn init_settings(cx: &mut AppContext) {
  296    EditorSettings::register(cx);
  297}
  298
  299pub fn init(cx: &mut AppContext) {
  300    init_settings(cx);
  301
  302    workspace::register_project_item::<Editor>(cx);
  303    workspace::FollowableViewRegistry::register::<Editor>(cx);
  304    workspace::register_serializable_item::<Editor>(cx);
  305
  306    cx.observe_new_views(
  307        |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
  308            workspace.register_action(Editor::new_file);
  309            workspace.register_action(Editor::new_file_vertical);
  310            workspace.register_action(Editor::new_file_horizontal);
  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(Default::default(), app_state, cx, |workspace, cx| {
  319                Editor::new_file(workspace, &Default::default(), cx)
  320            })
  321            .detach();
  322        }
  323    });
  324    cx.on_action(move |_: &workspace::NewWindow, cx| {
  325        let app_state = workspace::AppState::global(cx);
  326        if let Some(app_state) = app_state.upgrade() {
  327            workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
  328                Editor::new_file(workspace, &Default::default(), cx)
  329            })
  330            .detach();
  331        }
  332    });
  333    git::project_diff::init(cx);
  334}
  335
  336pub struct SearchWithinRange;
  337
  338trait InvalidationRegion {
  339    fn ranges(&self) -> &[Range<Anchor>];
  340}
  341
  342#[derive(Clone, Debug, PartialEq)]
  343pub enum SelectPhase {
  344    Begin {
  345        position: DisplayPoint,
  346        add: bool,
  347        click_count: usize,
  348    },
  349    BeginColumnar {
  350        position: DisplayPoint,
  351        reset: bool,
  352        goal_column: u32,
  353    },
  354    Extend {
  355        position: DisplayPoint,
  356        click_count: usize,
  357    },
  358    Update {
  359        position: DisplayPoint,
  360        goal_column: u32,
  361        scroll_delta: gpui::Point<f32>,
  362    },
  363    End,
  364}
  365
  366#[derive(Clone, Debug)]
  367pub enum SelectMode {
  368    Character,
  369    Word(Range<Anchor>),
  370    Line(Range<Anchor>),
  371    All,
  372}
  373
  374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
  375pub enum EditorMode {
  376    SingleLine { auto_width: bool },
  377    AutoHeight { max_lines: usize },
  378    Full,
  379}
  380
  381#[derive(Copy, Clone, Debug)]
  382pub enum SoftWrap {
  383    /// Prefer not to wrap at all.
  384    ///
  385    /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
  386    /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
  387    GitDiff,
  388    /// Prefer a single line generally, unless an overly long line is encountered.
  389    None,
  390    /// Soft wrap lines that exceed the editor width.
  391    EditorWidth,
  392    /// Soft wrap lines at the preferred line length.
  393    Column(u32),
  394    /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
  395    Bounded(u32),
  396}
  397
  398#[derive(Clone)]
  399pub struct EditorStyle {
  400    pub background: Hsla,
  401    pub local_player: PlayerColor,
  402    pub text: TextStyle,
  403    pub scrollbar_width: Pixels,
  404    pub syntax: Arc<SyntaxTheme>,
  405    pub status: StatusColors,
  406    pub inlay_hints_style: HighlightStyle,
  407    pub inline_completion_styles: InlineCompletionStyles,
  408    pub unnecessary_code_fade: f32,
  409}
  410
  411impl Default for EditorStyle {
  412    fn default() -> Self {
  413        Self {
  414            background: Hsla::default(),
  415            local_player: PlayerColor::default(),
  416            text: TextStyle::default(),
  417            scrollbar_width: Pixels::default(),
  418            syntax: Default::default(),
  419            // HACK: Status colors don't have a real default.
  420            // We should look into removing the status colors from the editor
  421            // style and retrieve them directly from the theme.
  422            status: StatusColors::dark(),
  423            inlay_hints_style: HighlightStyle::default(),
  424            inline_completion_styles: InlineCompletionStyles {
  425                insertion: HighlightStyle::default(),
  426                whitespace: HighlightStyle::default(),
  427            },
  428            unnecessary_code_fade: Default::default(),
  429        }
  430    }
  431}
  432
  433pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
  434    let show_background = language_settings::language_settings(None, None, cx)
  435        .inlay_hints
  436        .show_background;
  437
  438    HighlightStyle {
  439        color: Some(cx.theme().status().hint),
  440        background_color: show_background.then(|| cx.theme().status().hint_background),
  441        ..HighlightStyle::default()
  442    }
  443}
  444
  445pub fn make_suggestion_styles(cx: &WindowContext) -> InlineCompletionStyles {
  446    InlineCompletionStyles {
  447        insertion: HighlightStyle {
  448            color: Some(cx.theme().status().predictive),
  449            ..HighlightStyle::default()
  450        },
  451        whitespace: HighlightStyle {
  452            background_color: Some(cx.theme().status().created_background),
  453            ..HighlightStyle::default()
  454        },
  455    }
  456}
  457
  458type CompletionId = usize;
  459
  460#[derive(Debug, Clone)]
  461struct InlineCompletionMenuHint {
  462    provider_name: &'static str,
  463    text: InlineCompletionText,
  464}
  465
  466#[derive(Clone, Debug)]
  467enum InlineCompletionText {
  468    Move(SharedString),
  469    Edit {
  470        text: SharedString,
  471        highlights: Vec<(Range<usize>, HighlightStyle)>,
  472    },
  473}
  474
  475enum InlineCompletion {
  476    Edit(Vec<(Range<Anchor>, String)>),
  477    Move(Anchor),
  478}
  479
  480struct InlineCompletionState {
  481    inlay_ids: Vec<InlayId>,
  482    completion: InlineCompletion,
  483    invalidation_range: Range<Anchor>,
  484}
  485
  486enum InlineCompletionHighlight {}
  487
  488#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
  489struct EditorActionId(usize);
  490
  491impl EditorActionId {
  492    pub fn post_inc(&mut self) -> Self {
  493        let answer = self.0;
  494
  495        *self = Self(answer + 1);
  496
  497        Self(answer)
  498    }
  499}
  500
  501// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
  502// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
  503
  504type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
  505type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
  506
  507#[derive(Default)]
  508struct ScrollbarMarkerState {
  509    scrollbar_size: Size<Pixels>,
  510    dirty: bool,
  511    markers: Arc<[PaintQuad]>,
  512    pending_refresh: Option<Task<Result<()>>>,
  513}
  514
  515impl ScrollbarMarkerState {
  516    fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
  517        self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
  518    }
  519}
  520
  521#[derive(Clone, Debug)]
  522struct RunnableTasks {
  523    templates: Vec<(TaskSourceKind, TaskTemplate)>,
  524    offset: MultiBufferOffset,
  525    // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
  526    column: u32,
  527    // Values of all named captures, including those starting with '_'
  528    extra_variables: HashMap<String, String>,
  529    // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
  530    context_range: Range<BufferOffset>,
  531}
  532
  533impl RunnableTasks {
  534    fn resolve<'a>(
  535        &'a self,
  536        cx: &'a task::TaskContext,
  537    ) -> impl Iterator<Item = (TaskSourceKind, ResolvedTask)> + 'a {
  538        self.templates.iter().filter_map(|(kind, template)| {
  539            template
  540                .resolve_task(&kind.to_id_base(), cx)
  541                .map(|task| (kind.clone(), task))
  542        })
  543    }
  544}
  545
  546#[derive(Clone)]
  547struct ResolvedTasks {
  548    templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
  549    position: Anchor,
  550}
  551#[derive(Copy, Clone, Debug)]
  552struct MultiBufferOffset(usize);
  553#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
  554struct BufferOffset(usize);
  555
  556// Addons allow storing per-editor state in other crates (e.g. Vim)
  557pub trait Addon: 'static {
  558    fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
  559
  560    fn to_any(&self) -> &dyn std::any::Any;
  561}
  562
  563#[derive(Debug, Copy, Clone, PartialEq, Eq)]
  564pub enum IsVimMode {
  565    Yes,
  566    No,
  567}
  568
  569/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
  570///
  571/// See the [module level documentation](self) for more information.
  572pub struct Editor {
  573    focus_handle: FocusHandle,
  574    last_focused_descendant: Option<WeakFocusHandle>,
  575    /// The text buffer being edited
  576    buffer: Model<MultiBuffer>,
  577    /// Map of how text in the buffer should be displayed.
  578    /// Handles soft wraps, folds, fake inlay text insertions, etc.
  579    pub display_map: Model<DisplayMap>,
  580    pub selections: SelectionsCollection,
  581    pub scroll_manager: ScrollManager,
  582    /// When inline assist editors are linked, they all render cursors because
  583    /// typing enters text into each of them, even the ones that aren't focused.
  584    pub(crate) show_cursor_when_unfocused: bool,
  585    columnar_selection_tail: Option<Anchor>,
  586    add_selections_state: Option<AddSelectionsState>,
  587    select_next_state: Option<SelectNextState>,
  588    select_prev_state: Option<SelectNextState>,
  589    selection_history: SelectionHistory,
  590    autoclose_regions: Vec<AutocloseRegion>,
  591    snippet_stack: InvalidationStack<SnippetState>,
  592    select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
  593    ime_transaction: Option<TransactionId>,
  594    active_diagnostics: Option<ActiveDiagnosticGroup>,
  595    soft_wrap_mode_override: Option<language_settings::SoftWrap>,
  596
  597    project: Option<Model<Project>>,
  598    semantics_provider: Option<Rc<dyn SemanticsProvider>>,
  599    completion_provider: Option<Box<dyn CompletionProvider>>,
  600    collaboration_hub: Option<Box<dyn CollaborationHub>>,
  601    blink_manager: Model<BlinkManager>,
  602    show_cursor_names: bool,
  603    hovered_cursors: HashMap<HoveredCursor, Task<()>>,
  604    pub show_local_selections: bool,
  605    mode: EditorMode,
  606    show_breadcrumbs: bool,
  607    show_gutter: bool,
  608    show_line_numbers: Option<bool>,
  609    use_relative_line_numbers: Option<bool>,
  610    show_git_diff_gutter: Option<bool>,
  611    show_code_actions: Option<bool>,
  612    show_runnables: Option<bool>,
  613    show_wrap_guides: Option<bool>,
  614    show_indent_guides: Option<bool>,
  615    placeholder_text: Option<Arc<str>>,
  616    highlight_order: usize,
  617    highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
  618    background_highlights: TreeMap<TypeId, BackgroundHighlight>,
  619    gutter_highlights: TreeMap<TypeId, GutterHighlight>,
  620    scrollbar_marker_state: ScrollbarMarkerState,
  621    active_indent_guides_state: ActiveIndentGuidesState,
  622    nav_history: Option<ItemNavHistory>,
  623    context_menu: RefCell<Option<CodeContextMenu>>,
  624    mouse_context_menu: Option<MouseContextMenu>,
  625    hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
  626    completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
  627    signature_help_state: SignatureHelpState,
  628    auto_signature_help: Option<bool>,
  629    find_all_references_task_sources: Vec<Anchor>,
  630    next_completion_id: CompletionId,
  631    available_code_actions: Option<(Location, Rc<[AvailableCodeAction]>)>,
  632    code_actions_task: Option<Task<Result<()>>>,
  633    document_highlights_task: Option<Task<()>>,
  634    linked_editing_range_task: Option<Task<Option<()>>>,
  635    linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
  636    pending_rename: Option<RenameState>,
  637    searchable: bool,
  638    cursor_shape: CursorShape,
  639    current_line_highlight: Option<CurrentLineHighlight>,
  640    collapse_matches: bool,
  641    autoindent_mode: Option<AutoindentMode>,
  642    workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
  643    input_enabled: bool,
  644    use_modal_editing: bool,
  645    read_only: bool,
  646    leader_peer_id: Option<PeerId>,
  647    remote_id: Option<ViewId>,
  648    hover_state: HoverState,
  649    gutter_hovered: bool,
  650    hovered_link_state: Option<HoveredLinkState>,
  651    inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
  652    code_action_providers: Vec<Rc<dyn CodeActionProvider>>,
  653    active_inline_completion: Option<InlineCompletionState>,
  654    // enable_inline_completions is a switch that Vim can use to disable
  655    // inline completions based on its mode.
  656    enable_inline_completions: bool,
  657    show_inline_completions_override: Option<bool>,
  658    inlay_hint_cache: InlayHintCache,
  659    diff_map: DiffMap,
  660    next_inlay_id: usize,
  661    _subscriptions: Vec<Subscription>,
  662    pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
  663    gutter_dimensions: GutterDimensions,
  664    style: Option<EditorStyle>,
  665    text_style_refinement: Option<TextStyleRefinement>,
  666    next_editor_action_id: EditorActionId,
  667    editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
  668    use_autoclose: bool,
  669    use_auto_surround: bool,
  670    auto_replace_emoji_shortcode: bool,
  671    show_git_blame_gutter: bool,
  672    show_git_blame_inline: bool,
  673    show_git_blame_inline_delay_task: Option<Task<()>>,
  674    git_blame_inline_enabled: bool,
  675    serialize_dirty_buffers: bool,
  676    show_selection_menu: Option<bool>,
  677    blame: Option<Model<GitBlame>>,
  678    blame_subscription: Option<Subscription>,
  679    custom_context_menu: Option<
  680        Box<
  681            dyn 'static
  682                + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
  683        >,
  684    >,
  685    last_bounds: Option<Bounds<Pixels>>,
  686    expect_bounds_change: Option<Bounds<Pixels>>,
  687    tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
  688    tasks_update_task: Option<Task<()>>,
  689    previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
  690    breadcrumb_header: Option<String>,
  691    focused_block: Option<FocusedBlock>,
  692    next_scroll_position: NextScrollCursorCenterTopBottom,
  693    addons: HashMap<TypeId, Box<dyn Addon>>,
  694    registered_buffers: HashMap<BufferId, OpenLspBufferHandle>,
  695    toggle_fold_multiple_buffers: Task<()>,
  696    _scroll_cursor_center_top_bottom_task: Task<()>,
  697}
  698
  699#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
  700enum NextScrollCursorCenterTopBottom {
  701    #[default]
  702    Center,
  703    Top,
  704    Bottom,
  705}
  706
  707impl NextScrollCursorCenterTopBottom {
  708    fn next(&self) -> Self {
  709        match self {
  710            Self::Center => Self::Top,
  711            Self::Top => Self::Bottom,
  712            Self::Bottom => Self::Center,
  713        }
  714    }
  715}
  716
  717#[derive(Clone)]
  718pub struct EditorSnapshot {
  719    pub mode: EditorMode,
  720    show_gutter: bool,
  721    show_line_numbers: Option<bool>,
  722    show_git_diff_gutter: Option<bool>,
  723    show_code_actions: Option<bool>,
  724    show_runnables: Option<bool>,
  725    git_blame_gutter_max_author_length: Option<usize>,
  726    pub display_snapshot: DisplaySnapshot,
  727    pub placeholder_text: Option<Arc<str>>,
  728    diff_map: DiffMapSnapshot,
  729    is_focused: bool,
  730    scroll_anchor: ScrollAnchor,
  731    ongoing_scroll: OngoingScroll,
  732    current_line_highlight: CurrentLineHighlight,
  733    gutter_hovered: bool,
  734}
  735
  736const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
  737
  738#[derive(Default, Debug, Clone, Copy)]
  739pub struct GutterDimensions {
  740    pub left_padding: Pixels,
  741    pub right_padding: Pixels,
  742    pub width: Pixels,
  743    pub margin: Pixels,
  744    pub git_blame_entries_width: Option<Pixels>,
  745}
  746
  747impl GutterDimensions {
  748    /// The full width of the space taken up by the gutter.
  749    pub fn full_width(&self) -> Pixels {
  750        self.margin + self.width
  751    }
  752
  753    /// The width of the space reserved for the fold indicators,
  754    /// use alongside 'justify_end' and `gutter_width` to
  755    /// right align content with the line numbers
  756    pub fn fold_area_width(&self) -> Pixels {
  757        self.margin + self.right_padding
  758    }
  759}
  760
  761#[derive(Debug)]
  762pub struct RemoteSelection {
  763    pub replica_id: ReplicaId,
  764    pub selection: Selection<Anchor>,
  765    pub cursor_shape: CursorShape,
  766    pub peer_id: PeerId,
  767    pub line_mode: bool,
  768    pub participant_index: Option<ParticipantIndex>,
  769    pub user_name: Option<SharedString>,
  770}
  771
  772#[derive(Clone, Debug)]
  773struct SelectionHistoryEntry {
  774    selections: Arc<[Selection<Anchor>]>,
  775    select_next_state: Option<SelectNextState>,
  776    select_prev_state: Option<SelectNextState>,
  777    add_selections_state: Option<AddSelectionsState>,
  778}
  779
  780enum SelectionHistoryMode {
  781    Normal,
  782    Undoing,
  783    Redoing,
  784}
  785
  786#[derive(Clone, PartialEq, Eq, Hash)]
  787struct HoveredCursor {
  788    replica_id: u16,
  789    selection_id: usize,
  790}
  791
  792impl Default for SelectionHistoryMode {
  793    fn default() -> Self {
  794        Self::Normal
  795    }
  796}
  797
  798#[derive(Default)]
  799struct SelectionHistory {
  800    #[allow(clippy::type_complexity)]
  801    selections_by_transaction:
  802        HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
  803    mode: SelectionHistoryMode,
  804    undo_stack: VecDeque<SelectionHistoryEntry>,
  805    redo_stack: VecDeque<SelectionHistoryEntry>,
  806}
  807
  808impl SelectionHistory {
  809    fn insert_transaction(
  810        &mut self,
  811        transaction_id: TransactionId,
  812        selections: Arc<[Selection<Anchor>]>,
  813    ) {
  814        self.selections_by_transaction
  815            .insert(transaction_id, (selections, None));
  816    }
  817
  818    #[allow(clippy::type_complexity)]
  819    fn transaction(
  820        &self,
  821        transaction_id: TransactionId,
  822    ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  823        self.selections_by_transaction.get(&transaction_id)
  824    }
  825
  826    #[allow(clippy::type_complexity)]
  827    fn transaction_mut(
  828        &mut self,
  829        transaction_id: TransactionId,
  830    ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
  831        self.selections_by_transaction.get_mut(&transaction_id)
  832    }
  833
  834    fn push(&mut self, entry: SelectionHistoryEntry) {
  835        if !entry.selections.is_empty() {
  836            match self.mode {
  837                SelectionHistoryMode::Normal => {
  838                    self.push_undo(entry);
  839                    self.redo_stack.clear();
  840                }
  841                SelectionHistoryMode::Undoing => self.push_redo(entry),
  842                SelectionHistoryMode::Redoing => self.push_undo(entry),
  843            }
  844        }
  845    }
  846
  847    fn push_undo(&mut self, entry: SelectionHistoryEntry) {
  848        if self
  849            .undo_stack
  850            .back()
  851            .map_or(true, |e| e.selections != entry.selections)
  852        {
  853            self.undo_stack.push_back(entry);
  854            if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  855                self.undo_stack.pop_front();
  856            }
  857        }
  858    }
  859
  860    fn push_redo(&mut self, entry: SelectionHistoryEntry) {
  861        if self
  862            .redo_stack
  863            .back()
  864            .map_or(true, |e| e.selections != entry.selections)
  865        {
  866            self.redo_stack.push_back(entry);
  867            if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
  868                self.redo_stack.pop_front();
  869            }
  870        }
  871    }
  872}
  873
  874struct RowHighlight {
  875    index: usize,
  876    range: Range<Anchor>,
  877    color: Hsla,
  878    should_autoscroll: bool,
  879}
  880
  881#[derive(Clone, Debug)]
  882struct AddSelectionsState {
  883    above: bool,
  884    stack: Vec<usize>,
  885}
  886
  887#[derive(Clone)]
  888struct SelectNextState {
  889    query: AhoCorasick,
  890    wordwise: bool,
  891    done: bool,
  892}
  893
  894impl std::fmt::Debug for SelectNextState {
  895    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  896        f.debug_struct(std::any::type_name::<Self>())
  897            .field("wordwise", &self.wordwise)
  898            .field("done", &self.done)
  899            .finish()
  900    }
  901}
  902
  903#[derive(Debug)]
  904struct AutocloseRegion {
  905    selection_id: usize,
  906    range: Range<Anchor>,
  907    pair: BracketPair,
  908}
  909
  910#[derive(Debug)]
  911struct SnippetState {
  912    ranges: Vec<Vec<Range<Anchor>>>,
  913    active_index: usize,
  914    choices: Vec<Option<Vec<String>>>,
  915}
  916
  917#[doc(hidden)]
  918pub struct RenameState {
  919    pub range: Range<Anchor>,
  920    pub old_name: Arc<str>,
  921    pub editor: View<Editor>,
  922    block_id: CustomBlockId,
  923}
  924
  925struct InvalidationStack<T>(Vec<T>);
  926
  927struct RegisteredInlineCompletionProvider {
  928    provider: Arc<dyn InlineCompletionProviderHandle>,
  929    _subscription: Subscription,
  930}
  931
  932#[derive(Debug)]
  933struct ActiveDiagnosticGroup {
  934    primary_range: Range<Anchor>,
  935    primary_message: String,
  936    group_id: usize,
  937    blocks: HashMap<CustomBlockId, Diagnostic>,
  938    is_valid: bool,
  939}
  940
  941#[derive(Serialize, Deserialize, Clone, Debug)]
  942pub struct ClipboardSelection {
  943    pub len: usize,
  944    pub is_entire_line: bool,
  945    pub first_line_indent: u32,
  946}
  947
  948#[derive(Debug)]
  949pub(crate) struct NavigationData {
  950    cursor_anchor: Anchor,
  951    cursor_position: Point,
  952    scroll_anchor: ScrollAnchor,
  953    scroll_top_row: u32,
  954}
  955
  956#[derive(Debug, Clone, Copy, PartialEq, Eq)]
  957pub enum GotoDefinitionKind {
  958    Symbol,
  959    Declaration,
  960    Type,
  961    Implementation,
  962}
  963
  964#[derive(Debug, Clone)]
  965enum InlayHintRefreshReason {
  966    Toggle(bool),
  967    SettingsChange(InlayHintSettings),
  968    NewLinesShown,
  969    BufferEdited(HashSet<Arc<Language>>),
  970    RefreshRequested,
  971    ExcerptsRemoved(Vec<ExcerptId>),
  972}
  973
  974impl InlayHintRefreshReason {
  975    fn description(&self) -> &'static str {
  976        match self {
  977            Self::Toggle(_) => "toggle",
  978            Self::SettingsChange(_) => "settings change",
  979            Self::NewLinesShown => "new lines shown",
  980            Self::BufferEdited(_) => "buffer edited",
  981            Self::RefreshRequested => "refresh requested",
  982            Self::ExcerptsRemoved(_) => "excerpts removed",
  983        }
  984    }
  985}
  986
  987pub(crate) struct FocusedBlock {
  988    id: BlockId,
  989    focus_handle: WeakFocusHandle,
  990}
  991
  992#[derive(Clone)]
  993struct JumpData {
  994    excerpt_id: ExcerptId,
  995    position: Point,
  996    anchor: text::Anchor,
  997    path: Option<project::ProjectPath>,
  998    line_offset_from_top: u32,
  999}
 1000
 1001impl Editor {
 1002    pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
 1003        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1004        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1005        Self::new(
 1006            EditorMode::SingleLine { auto_width: false },
 1007            buffer,
 1008            None,
 1009            false,
 1010            cx,
 1011        )
 1012    }
 1013
 1014    pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
 1015        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1016        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1017        Self::new(EditorMode::Full, buffer, None, false, cx)
 1018    }
 1019
 1020    pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
 1021        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1022        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1023        Self::new(
 1024            EditorMode::SingleLine { auto_width: true },
 1025            buffer,
 1026            None,
 1027            false,
 1028            cx,
 1029        )
 1030    }
 1031
 1032    pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
 1033        let buffer = cx.new_model(|cx| Buffer::local("", cx));
 1034        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1035        Self::new(
 1036            EditorMode::AutoHeight { max_lines },
 1037            buffer,
 1038            None,
 1039            false,
 1040            cx,
 1041        )
 1042    }
 1043
 1044    pub fn for_buffer(
 1045        buffer: Model<Buffer>,
 1046        project: Option<Model<Project>>,
 1047        cx: &mut ViewContext<Self>,
 1048    ) -> Self {
 1049        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
 1050        Self::new(EditorMode::Full, buffer, project, false, cx)
 1051    }
 1052
 1053    pub fn for_multibuffer(
 1054        buffer: Model<MultiBuffer>,
 1055        project: Option<Model<Project>>,
 1056        show_excerpt_controls: bool,
 1057        cx: &mut ViewContext<Self>,
 1058    ) -> Self {
 1059        Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
 1060    }
 1061
 1062    pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
 1063        let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
 1064        let mut clone = Self::new(
 1065            self.mode,
 1066            self.buffer.clone(),
 1067            self.project.clone(),
 1068            show_excerpt_controls,
 1069            cx,
 1070        );
 1071        self.display_map.update(cx, |display_map, cx| {
 1072            let snapshot = display_map.snapshot(cx);
 1073            clone.display_map.update(cx, |display_map, cx| {
 1074                display_map.set_state(&snapshot, cx);
 1075            });
 1076        });
 1077        clone.selections.clone_state(&self.selections);
 1078        clone.scroll_manager.clone_state(&self.scroll_manager);
 1079        clone.searchable = self.searchable;
 1080        clone
 1081    }
 1082
 1083    pub fn new(
 1084        mode: EditorMode,
 1085        buffer: Model<MultiBuffer>,
 1086        project: Option<Model<Project>>,
 1087        show_excerpt_controls: bool,
 1088        cx: &mut ViewContext<Self>,
 1089    ) -> Self {
 1090        let style = cx.text_style();
 1091        let font_size = style.font_size.to_pixels(cx.rem_size());
 1092        let editor = cx.view().downgrade();
 1093        let fold_placeholder = FoldPlaceholder {
 1094            constrain_width: true,
 1095            render: Arc::new(move |fold_id, fold_range, cx| {
 1096                let editor = editor.clone();
 1097                div()
 1098                    .id(fold_id)
 1099                    .bg(cx.theme().colors().ghost_element_background)
 1100                    .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
 1101                    .active(|style| style.bg(cx.theme().colors().ghost_element_active))
 1102                    .rounded_sm()
 1103                    .size_full()
 1104                    .cursor_pointer()
 1105                    .child("")
 1106                    .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
 1107                    .on_click(move |_, cx| {
 1108                        editor
 1109                            .update(cx, |editor, cx| {
 1110                                editor.unfold_ranges(
 1111                                    &[fold_range.start..fold_range.end],
 1112                                    true,
 1113                                    false,
 1114                                    cx,
 1115                                );
 1116                                cx.stop_propagation();
 1117                            })
 1118                            .ok();
 1119                    })
 1120                    .into_any()
 1121            }),
 1122            merge_adjacent: true,
 1123            ..Default::default()
 1124        };
 1125        let display_map = cx.new_model(|cx| {
 1126            DisplayMap::new(
 1127                buffer.clone(),
 1128                style.font(),
 1129                font_size,
 1130                None,
 1131                show_excerpt_controls,
 1132                FILE_HEADER_HEIGHT,
 1133                MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
 1134                MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
 1135                fold_placeholder,
 1136                cx,
 1137            )
 1138        });
 1139
 1140        let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
 1141
 1142        let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
 1143
 1144        let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
 1145            .then(|| language_settings::SoftWrap::None);
 1146
 1147        let mut project_subscriptions = Vec::new();
 1148        if mode == EditorMode::Full {
 1149            if let Some(project) = project.as_ref() {
 1150                if buffer.read(cx).is_singleton() {
 1151                    project_subscriptions.push(cx.observe(project, |_, _, cx| {
 1152                        cx.emit(EditorEvent::TitleChanged);
 1153                    }));
 1154                }
 1155                project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
 1156                    if let project::Event::RefreshInlayHints = event {
 1157                        editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
 1158                    } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
 1159                        if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
 1160                            let focus_handle = editor.focus_handle(cx);
 1161                            if focus_handle.is_focused(cx) {
 1162                                let snapshot = buffer.read(cx).snapshot();
 1163                                for (range, snippet) in snippet_edits {
 1164                                    let editor_range =
 1165                                        language::range_from_lsp(*range).to_offset(&snapshot);
 1166                                    editor
 1167                                        .insert_snippet(&[editor_range], snippet.clone(), cx)
 1168                                        .ok();
 1169                                }
 1170                            }
 1171                        }
 1172                    }
 1173                }));
 1174                if let Some(task_inventory) = project
 1175                    .read(cx)
 1176                    .task_store()
 1177                    .read(cx)
 1178                    .task_inventory()
 1179                    .cloned()
 1180                {
 1181                    project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
 1182                        editor.tasks_update_task = Some(editor.refresh_runnables(cx));
 1183                    }));
 1184                }
 1185            }
 1186        }
 1187
 1188        let buffer_snapshot = buffer.read(cx).snapshot(cx);
 1189
 1190        let inlay_hint_settings =
 1191            inlay_hint_settings(selections.newest_anchor().head(), &buffer_snapshot, cx);
 1192        let focus_handle = cx.focus_handle();
 1193        cx.on_focus(&focus_handle, Self::handle_focus).detach();
 1194        cx.on_focus_in(&focus_handle, Self::handle_focus_in)
 1195            .detach();
 1196        cx.on_focus_out(&focus_handle, Self::handle_focus_out)
 1197            .detach();
 1198        cx.on_blur(&focus_handle, Self::handle_blur).detach();
 1199
 1200        let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
 1201            Some(false)
 1202        } else {
 1203            None
 1204        };
 1205
 1206        let mut code_action_providers = Vec::new();
 1207        if let Some(project) = project.clone() {
 1208            get_unstaged_changes_for_buffers(&project, buffer.read(cx).all_buffers(), cx);
 1209            code_action_providers.push(Rc::new(project) as Rc<_>);
 1210        }
 1211
 1212        let mut this = Self {
 1213            focus_handle,
 1214            show_cursor_when_unfocused: false,
 1215            last_focused_descendant: None,
 1216            buffer: buffer.clone(),
 1217            display_map: display_map.clone(),
 1218            selections,
 1219            scroll_manager: ScrollManager::new(cx),
 1220            columnar_selection_tail: None,
 1221            add_selections_state: None,
 1222            select_next_state: None,
 1223            select_prev_state: None,
 1224            selection_history: Default::default(),
 1225            autoclose_regions: Default::default(),
 1226            snippet_stack: Default::default(),
 1227            select_larger_syntax_node_stack: Vec::new(),
 1228            ime_transaction: Default::default(),
 1229            active_diagnostics: None,
 1230            soft_wrap_mode_override,
 1231            completion_provider: project.clone().map(|project| Box::new(project) as _),
 1232            semantics_provider: project.clone().map(|project| Rc::new(project) as _),
 1233            collaboration_hub: project.clone().map(|project| Box::new(project) as _),
 1234            project,
 1235            blink_manager: blink_manager.clone(),
 1236            show_local_selections: true,
 1237            mode,
 1238            show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
 1239            show_gutter: mode == EditorMode::Full,
 1240            show_line_numbers: None,
 1241            use_relative_line_numbers: None,
 1242            show_git_diff_gutter: None,
 1243            show_code_actions: None,
 1244            show_runnables: None,
 1245            show_wrap_guides: None,
 1246            show_indent_guides,
 1247            placeholder_text: None,
 1248            highlight_order: 0,
 1249            highlighted_rows: HashMap::default(),
 1250            background_highlights: Default::default(),
 1251            gutter_highlights: TreeMap::default(),
 1252            scrollbar_marker_state: ScrollbarMarkerState::default(),
 1253            active_indent_guides_state: ActiveIndentGuidesState::default(),
 1254            nav_history: None,
 1255            context_menu: RefCell::new(None),
 1256            mouse_context_menu: None,
 1257            hunk_controls_menu_handle: PopoverMenuHandle::default(),
 1258            completion_tasks: Default::default(),
 1259            signature_help_state: SignatureHelpState::default(),
 1260            auto_signature_help: None,
 1261            find_all_references_task_sources: Vec::new(),
 1262            next_completion_id: 0,
 1263            next_inlay_id: 0,
 1264            code_action_providers,
 1265            available_code_actions: Default::default(),
 1266            code_actions_task: Default::default(),
 1267            document_highlights_task: Default::default(),
 1268            linked_editing_range_task: Default::default(),
 1269            pending_rename: Default::default(),
 1270            searchable: true,
 1271            cursor_shape: EditorSettings::get_global(cx)
 1272                .cursor_shape
 1273                .unwrap_or_default(),
 1274            current_line_highlight: None,
 1275            autoindent_mode: Some(AutoindentMode::EachLine),
 1276            collapse_matches: false,
 1277            workspace: None,
 1278            input_enabled: true,
 1279            use_modal_editing: mode == EditorMode::Full,
 1280            read_only: false,
 1281            use_autoclose: true,
 1282            use_auto_surround: true,
 1283            auto_replace_emoji_shortcode: false,
 1284            leader_peer_id: None,
 1285            remote_id: None,
 1286            hover_state: Default::default(),
 1287            hovered_link_state: Default::default(),
 1288            inline_completion_provider: None,
 1289            active_inline_completion: None,
 1290            inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
 1291            diff_map: DiffMap::default(),
 1292            gutter_hovered: false,
 1293            pixel_position_of_newest_cursor: None,
 1294            last_bounds: None,
 1295            expect_bounds_change: None,
 1296            gutter_dimensions: GutterDimensions::default(),
 1297            style: None,
 1298            show_cursor_names: false,
 1299            hovered_cursors: Default::default(),
 1300            next_editor_action_id: EditorActionId::default(),
 1301            editor_actions: Rc::default(),
 1302            show_inline_completions_override: None,
 1303            enable_inline_completions: true,
 1304            custom_context_menu: None,
 1305            show_git_blame_gutter: false,
 1306            show_git_blame_inline: false,
 1307            show_selection_menu: None,
 1308            show_git_blame_inline_delay_task: None,
 1309            git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
 1310            serialize_dirty_buffers: ProjectSettings::get_global(cx)
 1311                .session
 1312                .restore_unsaved_buffers,
 1313            blame: None,
 1314            blame_subscription: None,
 1315            tasks: Default::default(),
 1316            _subscriptions: vec![
 1317                cx.observe(&buffer, Self::on_buffer_changed),
 1318                cx.subscribe(&buffer, Self::on_buffer_event),
 1319                cx.observe(&display_map, Self::on_display_map_changed),
 1320                cx.observe(&blink_manager, |_, _, cx| cx.notify()),
 1321                cx.observe_global::<SettingsStore>(Self::settings_changed),
 1322                observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
 1323                cx.observe_window_activation(|editor, cx| {
 1324                    let active = cx.is_window_active();
 1325                    editor.blink_manager.update(cx, |blink_manager, cx| {
 1326                        if active {
 1327                            blink_manager.enable(cx);
 1328                        } else {
 1329                            blink_manager.disable(cx);
 1330                        }
 1331                    });
 1332                }),
 1333            ],
 1334            tasks_update_task: None,
 1335            linked_edit_ranges: Default::default(),
 1336            previous_search_ranges: None,
 1337            breadcrumb_header: None,
 1338            focused_block: None,
 1339            next_scroll_position: NextScrollCursorCenterTopBottom::default(),
 1340            addons: HashMap::default(),
 1341            registered_buffers: HashMap::default(),
 1342            _scroll_cursor_center_top_bottom_task: Task::ready(()),
 1343            toggle_fold_multiple_buffers: Task::ready(()),
 1344            text_style_refinement: None,
 1345        };
 1346        this.tasks_update_task = Some(this.refresh_runnables(cx));
 1347        this._subscriptions.extend(project_subscriptions);
 1348
 1349        this.end_selection(cx);
 1350        this.scroll_manager.show_scrollbar(cx);
 1351
 1352        if mode == EditorMode::Full {
 1353            let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
 1354            cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
 1355
 1356            if this.git_blame_inline_enabled {
 1357                this.git_blame_inline_enabled = true;
 1358                this.start_git_blame_inline(false, cx);
 1359            }
 1360
 1361            if let Some(buffer) = buffer.read(cx).as_singleton() {
 1362                if let Some(project) = this.project.as_ref() {
 1363                    let lsp_store = project.read(cx).lsp_store();
 1364                    let handle = lsp_store.update(cx, |lsp_store, cx| {
 1365                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1366                    });
 1367                    this.registered_buffers
 1368                        .insert(buffer.read(cx).remote_id(), handle);
 1369                }
 1370            }
 1371        }
 1372
 1373        this.report_editor_event("Editor Opened", None, cx);
 1374        this
 1375    }
 1376
 1377    pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
 1378        self.mouse_context_menu
 1379            .as_ref()
 1380            .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
 1381    }
 1382
 1383    fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
 1384        let mut key_context = KeyContext::new_with_defaults();
 1385        key_context.add("Editor");
 1386        let mode = match self.mode {
 1387            EditorMode::SingleLine { .. } => "single_line",
 1388            EditorMode::AutoHeight { .. } => "auto_height",
 1389            EditorMode::Full => "full",
 1390        };
 1391
 1392        if EditorSettings::jupyter_enabled(cx) {
 1393            key_context.add("jupyter");
 1394        }
 1395
 1396        key_context.set("mode", mode);
 1397        if self.pending_rename.is_some() {
 1398            key_context.add("renaming");
 1399        }
 1400        match self.context_menu.borrow().as_ref() {
 1401            Some(CodeContextMenu::Completions(_)) => {
 1402                key_context.add("menu");
 1403                key_context.add("showing_completions")
 1404            }
 1405            Some(CodeContextMenu::CodeActions(_)) => {
 1406                key_context.add("menu");
 1407                key_context.add("showing_code_actions")
 1408            }
 1409            None => {}
 1410        }
 1411
 1412        // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
 1413        if !self.focus_handle(cx).contains_focused(cx)
 1414            || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
 1415        {
 1416            for addon in self.addons.values() {
 1417                addon.extend_key_context(&mut key_context, cx)
 1418            }
 1419        }
 1420
 1421        if let Some(extension) = self
 1422            .buffer
 1423            .read(cx)
 1424            .as_singleton()
 1425            .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
 1426        {
 1427            key_context.set("extension", extension.to_string());
 1428        }
 1429
 1430        if self.has_active_inline_completion() {
 1431            key_context.add("copilot_suggestion");
 1432            key_context.add("inline_completion");
 1433        }
 1434
 1435        if !self
 1436            .selections
 1437            .disjoint
 1438            .iter()
 1439            .all(|selection| selection.start == selection.end)
 1440        {
 1441            key_context.add("selection");
 1442        }
 1443
 1444        key_context
 1445    }
 1446
 1447    pub fn new_file(
 1448        workspace: &mut Workspace,
 1449        _: &workspace::NewFile,
 1450        cx: &mut ViewContext<Workspace>,
 1451    ) {
 1452        Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
 1453            "Failed to create buffer",
 1454            cx,
 1455            |e, _| match e.error_code() {
 1456                ErrorCode::RemoteUpgradeRequired => Some(format!(
 1457                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1458                e.error_tag("required").unwrap_or("the latest version")
 1459            )),
 1460                _ => None,
 1461            },
 1462        );
 1463    }
 1464
 1465    pub fn new_in_workspace(
 1466        workspace: &mut Workspace,
 1467        cx: &mut ViewContext<Workspace>,
 1468    ) -> Task<Result<View<Editor>>> {
 1469        let project = workspace.project().clone();
 1470        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1471
 1472        cx.spawn(|workspace, mut cx| async move {
 1473            let buffer = create.await?;
 1474            workspace.update(&mut cx, |workspace, cx| {
 1475                let editor =
 1476                    cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
 1477                workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 1478                editor
 1479            })
 1480        })
 1481    }
 1482
 1483    fn new_file_vertical(
 1484        workspace: &mut Workspace,
 1485        _: &workspace::NewFileSplitVertical,
 1486        cx: &mut ViewContext<Workspace>,
 1487    ) {
 1488        Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
 1489    }
 1490
 1491    fn new_file_horizontal(
 1492        workspace: &mut Workspace,
 1493        _: &workspace::NewFileSplitHorizontal,
 1494        cx: &mut ViewContext<Workspace>,
 1495    ) {
 1496        Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
 1497    }
 1498
 1499    fn new_file_in_direction(
 1500        workspace: &mut Workspace,
 1501        direction: SplitDirection,
 1502        cx: &mut ViewContext<Workspace>,
 1503    ) {
 1504        let project = workspace.project().clone();
 1505        let create = project.update(cx, |project, cx| project.create_buffer(cx));
 1506
 1507        cx.spawn(|workspace, mut cx| async move {
 1508            let buffer = create.await?;
 1509            workspace.update(&mut cx, move |workspace, cx| {
 1510                workspace.split_item(
 1511                    direction,
 1512                    Box::new(
 1513                        cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
 1514                    ),
 1515                    cx,
 1516                )
 1517            })?;
 1518            anyhow::Ok(())
 1519        })
 1520        .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
 1521            ErrorCode::RemoteUpgradeRequired => Some(format!(
 1522                "The remote instance of Zed does not support this yet. It must be upgraded to {}",
 1523                e.error_tag("required").unwrap_or("the latest version")
 1524            )),
 1525            _ => None,
 1526        });
 1527    }
 1528
 1529    pub fn leader_peer_id(&self) -> Option<PeerId> {
 1530        self.leader_peer_id
 1531    }
 1532
 1533    pub fn buffer(&self) -> &Model<MultiBuffer> {
 1534        &self.buffer
 1535    }
 1536
 1537    pub fn workspace(&self) -> Option<View<Workspace>> {
 1538        self.workspace.as_ref()?.0.upgrade()
 1539    }
 1540
 1541    pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
 1542        self.buffer().read(cx).title(cx)
 1543    }
 1544
 1545    pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
 1546        let git_blame_gutter_max_author_length = self
 1547            .render_git_blame_gutter(cx)
 1548            .then(|| {
 1549                if let Some(blame) = self.blame.as_ref() {
 1550                    let max_author_length =
 1551                        blame.update(cx, |blame, cx| blame.max_author_length(cx));
 1552                    Some(max_author_length)
 1553                } else {
 1554                    None
 1555                }
 1556            })
 1557            .flatten();
 1558
 1559        EditorSnapshot {
 1560            mode: self.mode,
 1561            show_gutter: self.show_gutter,
 1562            show_line_numbers: self.show_line_numbers,
 1563            show_git_diff_gutter: self.show_git_diff_gutter,
 1564            show_code_actions: self.show_code_actions,
 1565            show_runnables: self.show_runnables,
 1566            git_blame_gutter_max_author_length,
 1567            display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
 1568            scroll_anchor: self.scroll_manager.anchor(),
 1569            ongoing_scroll: self.scroll_manager.ongoing_scroll(),
 1570            placeholder_text: self.placeholder_text.clone(),
 1571            diff_map: self.diff_map.snapshot(),
 1572            is_focused: self.focus_handle.is_focused(cx),
 1573            current_line_highlight: self
 1574                .current_line_highlight
 1575                .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
 1576            gutter_hovered: self.gutter_hovered,
 1577        }
 1578    }
 1579
 1580    pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
 1581        self.buffer.read(cx).language_at(point, cx)
 1582    }
 1583
 1584    pub fn file_at<T: ToOffset>(
 1585        &self,
 1586        point: T,
 1587        cx: &AppContext,
 1588    ) -> Option<Arc<dyn language::File>> {
 1589        self.buffer.read(cx).read(cx).file_at(point).cloned()
 1590    }
 1591
 1592    pub fn active_excerpt(
 1593        &self,
 1594        cx: &AppContext,
 1595    ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
 1596        self.buffer
 1597            .read(cx)
 1598            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 1599    }
 1600
 1601    pub fn mode(&self) -> EditorMode {
 1602        self.mode
 1603    }
 1604
 1605    pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
 1606        self.collaboration_hub.as_deref()
 1607    }
 1608
 1609    pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
 1610        self.collaboration_hub = Some(hub);
 1611    }
 1612
 1613    pub fn set_custom_context_menu(
 1614        &mut self,
 1615        f: impl 'static
 1616            + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
 1617    ) {
 1618        self.custom_context_menu = Some(Box::new(f))
 1619    }
 1620
 1621    pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
 1622        self.completion_provider = provider;
 1623    }
 1624
 1625    pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
 1626        self.semantics_provider.clone()
 1627    }
 1628
 1629    pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
 1630        self.semantics_provider = provider;
 1631    }
 1632
 1633    pub fn set_inline_completion_provider<T>(
 1634        &mut self,
 1635        provider: Option<Model<T>>,
 1636        cx: &mut ViewContext<Self>,
 1637    ) where
 1638        T: InlineCompletionProvider,
 1639    {
 1640        self.inline_completion_provider =
 1641            provider.map(|provider| RegisteredInlineCompletionProvider {
 1642                _subscription: cx.observe(&provider, |this, _, cx| {
 1643                    if this.focus_handle.is_focused(cx) {
 1644                        this.update_visible_inline_completion(cx);
 1645                    }
 1646                }),
 1647                provider: Arc::new(provider),
 1648            });
 1649        self.refresh_inline_completion(false, false, cx);
 1650    }
 1651
 1652    pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
 1653        self.placeholder_text.as_deref()
 1654    }
 1655
 1656    pub fn set_placeholder_text(
 1657        &mut self,
 1658        placeholder_text: impl Into<Arc<str>>,
 1659        cx: &mut ViewContext<Self>,
 1660    ) {
 1661        let placeholder_text = Some(placeholder_text.into());
 1662        if self.placeholder_text != placeholder_text {
 1663            self.placeholder_text = placeholder_text;
 1664            cx.notify();
 1665        }
 1666    }
 1667
 1668    pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
 1669        self.cursor_shape = cursor_shape;
 1670
 1671        // Disrupt blink for immediate user feedback that the cursor shape has changed
 1672        self.blink_manager.update(cx, BlinkManager::show_cursor);
 1673
 1674        cx.notify();
 1675    }
 1676
 1677    pub fn set_current_line_highlight(
 1678        &mut self,
 1679        current_line_highlight: Option<CurrentLineHighlight>,
 1680    ) {
 1681        self.current_line_highlight = current_line_highlight;
 1682    }
 1683
 1684    pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
 1685        self.collapse_matches = collapse_matches;
 1686    }
 1687
 1688    pub fn register_buffers_with_language_servers(&mut self, cx: &mut ViewContext<Self>) {
 1689        let buffers = self.buffer.read(cx).all_buffers();
 1690        let Some(lsp_store) = self.lsp_store(cx) else {
 1691            return;
 1692        };
 1693        lsp_store.update(cx, |lsp_store, cx| {
 1694            for buffer in buffers {
 1695                self.registered_buffers
 1696                    .entry(buffer.read(cx).remote_id())
 1697                    .or_insert_with(|| {
 1698                        lsp_store.register_buffer_with_language_servers(&buffer, cx)
 1699                    });
 1700            }
 1701        })
 1702    }
 1703
 1704    pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
 1705        if self.collapse_matches {
 1706            return range.start..range.start;
 1707        }
 1708        range.clone()
 1709    }
 1710
 1711    pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
 1712        if self.display_map.read(cx).clip_at_line_ends != clip {
 1713            self.display_map
 1714                .update(cx, |map, _| map.clip_at_line_ends = clip);
 1715        }
 1716    }
 1717
 1718    pub fn set_input_enabled(&mut self, input_enabled: bool) {
 1719        self.input_enabled = input_enabled;
 1720    }
 1721
 1722    pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
 1723        self.enable_inline_completions = enabled;
 1724    }
 1725
 1726    pub fn set_autoindent(&mut self, autoindent: bool) {
 1727        if autoindent {
 1728            self.autoindent_mode = Some(AutoindentMode::EachLine);
 1729        } else {
 1730            self.autoindent_mode = None;
 1731        }
 1732    }
 1733
 1734    pub fn read_only(&self, cx: &AppContext) -> bool {
 1735        self.read_only || self.buffer.read(cx).read_only()
 1736    }
 1737
 1738    pub fn set_read_only(&mut self, read_only: bool) {
 1739        self.read_only = read_only;
 1740    }
 1741
 1742    pub fn set_use_autoclose(&mut self, autoclose: bool) {
 1743        self.use_autoclose = autoclose;
 1744    }
 1745
 1746    pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
 1747        self.use_auto_surround = auto_surround;
 1748    }
 1749
 1750    pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
 1751        self.auto_replace_emoji_shortcode = auto_replace;
 1752    }
 1753
 1754    pub fn toggle_inline_completions(
 1755        &mut self,
 1756        _: &ToggleInlineCompletions,
 1757        cx: &mut ViewContext<Self>,
 1758    ) {
 1759        if self.show_inline_completions_override.is_some() {
 1760            self.set_show_inline_completions(None, cx);
 1761        } else {
 1762            let cursor = self.selections.newest_anchor().head();
 1763            if let Some((buffer, cursor_buffer_position)) =
 1764                self.buffer.read(cx).text_anchor_for_position(cursor, cx)
 1765            {
 1766                let show_inline_completions =
 1767                    !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
 1768                self.set_show_inline_completions(Some(show_inline_completions), cx);
 1769            }
 1770        }
 1771    }
 1772
 1773    pub fn set_show_inline_completions(
 1774        &mut self,
 1775        show_inline_completions: Option<bool>,
 1776        cx: &mut ViewContext<Self>,
 1777    ) {
 1778        self.show_inline_completions_override = show_inline_completions;
 1779        self.refresh_inline_completion(false, true, cx);
 1780    }
 1781
 1782    fn should_show_inline_completions(
 1783        &self,
 1784        buffer: &Model<Buffer>,
 1785        buffer_position: language::Anchor,
 1786        cx: &AppContext,
 1787    ) -> bool {
 1788        if !self.snippet_stack.is_empty() {
 1789            return false;
 1790        }
 1791
 1792        if self.inline_completions_disabled_in_scope(buffer, buffer_position, cx) {
 1793            return false;
 1794        }
 1795
 1796        if let Some(provider) = self.inline_completion_provider() {
 1797            if let Some(show_inline_completions) = self.show_inline_completions_override {
 1798                show_inline_completions
 1799            } else {
 1800                self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
 1801            }
 1802        } else {
 1803            false
 1804        }
 1805    }
 1806
 1807    fn inline_completions_disabled_in_scope(
 1808        &self,
 1809        buffer: &Model<Buffer>,
 1810        buffer_position: language::Anchor,
 1811        cx: &AppContext,
 1812    ) -> bool {
 1813        let snapshot = buffer.read(cx).snapshot();
 1814        let settings = snapshot.settings_at(buffer_position, cx);
 1815
 1816        let Some(scope) = snapshot.language_scope_at(buffer_position) else {
 1817            return false;
 1818        };
 1819
 1820        scope.override_name().map_or(false, |scope_name| {
 1821            settings
 1822                .inline_completions_disabled_in
 1823                .iter()
 1824                .any(|s| s == scope_name)
 1825        })
 1826    }
 1827
 1828    pub fn set_use_modal_editing(&mut self, to: bool) {
 1829        self.use_modal_editing = to;
 1830    }
 1831
 1832    pub fn use_modal_editing(&self) -> bool {
 1833        self.use_modal_editing
 1834    }
 1835
 1836    fn selections_did_change(
 1837        &mut self,
 1838        local: bool,
 1839        old_cursor_position: &Anchor,
 1840        show_completions: bool,
 1841        cx: &mut ViewContext<Self>,
 1842    ) {
 1843        cx.invalidate_character_coordinates();
 1844
 1845        // Copy selections to primary selection buffer
 1846        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 1847        if local {
 1848            let selections = self.selections.all::<usize>(cx);
 1849            let buffer_handle = self.buffer.read(cx).read(cx);
 1850
 1851            let mut text = String::new();
 1852            for (index, selection) in selections.iter().enumerate() {
 1853                let text_for_selection = buffer_handle
 1854                    .text_for_range(selection.start..selection.end)
 1855                    .collect::<String>();
 1856
 1857                text.push_str(&text_for_selection);
 1858                if index != selections.len() - 1 {
 1859                    text.push('\n');
 1860                }
 1861            }
 1862
 1863            if !text.is_empty() {
 1864                cx.write_to_primary(ClipboardItem::new_string(text));
 1865            }
 1866        }
 1867
 1868        if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
 1869            self.buffer.update(cx, |buffer, cx| {
 1870                buffer.set_active_selections(
 1871                    &self.selections.disjoint_anchors(),
 1872                    self.selections.line_mode,
 1873                    self.cursor_shape,
 1874                    cx,
 1875                )
 1876            });
 1877        }
 1878        let display_map = self
 1879            .display_map
 1880            .update(cx, |display_map, cx| display_map.snapshot(cx));
 1881        let buffer = &display_map.buffer_snapshot;
 1882        self.add_selections_state = None;
 1883        self.select_next_state = None;
 1884        self.select_prev_state = None;
 1885        self.select_larger_syntax_node_stack.clear();
 1886        self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
 1887        self.snippet_stack
 1888            .invalidate(&self.selections.disjoint_anchors(), buffer);
 1889        self.take_rename(false, cx);
 1890
 1891        let new_cursor_position = self.selections.newest_anchor().head();
 1892
 1893        self.push_to_nav_history(
 1894            *old_cursor_position,
 1895            Some(new_cursor_position.to_point(buffer)),
 1896            cx,
 1897        );
 1898
 1899        if local {
 1900            let new_cursor_position = self.selections.newest_anchor().head();
 1901            let mut context_menu = self.context_menu.borrow_mut();
 1902            let completion_menu = match context_menu.as_ref() {
 1903                Some(CodeContextMenu::Completions(menu)) => Some(menu),
 1904                _ => {
 1905                    *context_menu = None;
 1906                    None
 1907                }
 1908            };
 1909
 1910            if let Some(completion_menu) = completion_menu {
 1911                let cursor_position = new_cursor_position.to_offset(buffer);
 1912                let (word_range, kind) =
 1913                    buffer.surrounding_word(completion_menu.initial_position, true);
 1914                if kind == Some(CharKind::Word)
 1915                    && word_range.to_inclusive().contains(&cursor_position)
 1916                {
 1917                    let mut completion_menu = completion_menu.clone();
 1918                    drop(context_menu);
 1919
 1920                    let query = Self::completion_query(buffer, cursor_position);
 1921                    cx.spawn(move |this, mut cx| async move {
 1922                        completion_menu
 1923                            .filter(query.as_deref(), cx.background_executor().clone())
 1924                            .await;
 1925
 1926                        this.update(&mut cx, |this, cx| {
 1927                            let mut context_menu = this.context_menu.borrow_mut();
 1928                            let Some(CodeContextMenu::Completions(menu)) = context_menu.as_ref()
 1929                            else {
 1930                                return;
 1931                            };
 1932
 1933                            if menu.id > completion_menu.id {
 1934                                return;
 1935                            }
 1936
 1937                            *context_menu = Some(CodeContextMenu::Completions(completion_menu));
 1938                            drop(context_menu);
 1939                            cx.notify();
 1940                        })
 1941                    })
 1942                    .detach();
 1943
 1944                    if show_completions {
 1945                        self.show_completions(&ShowCompletions { trigger: None }, cx);
 1946                    }
 1947                } else {
 1948                    drop(context_menu);
 1949                    self.hide_context_menu(cx);
 1950                }
 1951            } else {
 1952                drop(context_menu);
 1953            }
 1954
 1955            hide_hover(self, cx);
 1956
 1957            if old_cursor_position.to_display_point(&display_map).row()
 1958                != new_cursor_position.to_display_point(&display_map).row()
 1959            {
 1960                self.available_code_actions.take();
 1961            }
 1962            self.refresh_code_actions(cx);
 1963            self.refresh_document_highlights(cx);
 1964            refresh_matching_bracket_highlights(self, cx);
 1965            self.update_visible_inline_completion(cx);
 1966            linked_editing_ranges::refresh_linked_ranges(self, cx);
 1967            if self.git_blame_inline_enabled {
 1968                self.start_inline_blame_timer(cx);
 1969            }
 1970        }
 1971
 1972        self.blink_manager.update(cx, BlinkManager::pause_blinking);
 1973        cx.emit(EditorEvent::SelectionsChanged { local });
 1974
 1975        if self.selections.disjoint_anchors().len() == 1 {
 1976            cx.emit(SearchEvent::ActiveMatchChanged)
 1977        }
 1978        cx.notify();
 1979    }
 1980
 1981    pub fn change_selections<R>(
 1982        &mut self,
 1983        autoscroll: Option<Autoscroll>,
 1984        cx: &mut ViewContext<Self>,
 1985        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1986    ) -> R {
 1987        self.change_selections_inner(autoscroll, true, cx, change)
 1988    }
 1989
 1990    pub fn change_selections_inner<R>(
 1991        &mut self,
 1992        autoscroll: Option<Autoscroll>,
 1993        request_completions: bool,
 1994        cx: &mut ViewContext<Self>,
 1995        change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
 1996    ) -> R {
 1997        let old_cursor_position = self.selections.newest_anchor().head();
 1998        self.push_to_selection_history();
 1999
 2000        let (changed, result) = self.selections.change_with(cx, change);
 2001
 2002        if changed {
 2003            if let Some(autoscroll) = autoscroll {
 2004                self.request_autoscroll(autoscroll, cx);
 2005            }
 2006            self.selections_did_change(true, &old_cursor_position, request_completions, cx);
 2007
 2008            if self.should_open_signature_help_automatically(
 2009                &old_cursor_position,
 2010                self.signature_help_state.backspace_pressed(),
 2011                cx,
 2012            ) {
 2013                self.show_signature_help(&ShowSignatureHelp, cx);
 2014            }
 2015            self.signature_help_state.set_backspace_pressed(false);
 2016        }
 2017
 2018        result
 2019    }
 2020
 2021    pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2022    where
 2023        I: IntoIterator<Item = (Range<S>, T)>,
 2024        S: ToOffset,
 2025        T: Into<Arc<str>>,
 2026    {
 2027        if self.read_only(cx) {
 2028            return;
 2029        }
 2030
 2031        self.buffer
 2032            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 2033    }
 2034
 2035    pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
 2036    where
 2037        I: IntoIterator<Item = (Range<S>, T)>,
 2038        S: ToOffset,
 2039        T: Into<Arc<str>>,
 2040    {
 2041        if self.read_only(cx) {
 2042            return;
 2043        }
 2044
 2045        self.buffer.update(cx, |buffer, cx| {
 2046            buffer.edit(edits, self.autoindent_mode.clone(), cx)
 2047        });
 2048    }
 2049
 2050    pub fn edit_with_block_indent<I, S, T>(
 2051        &mut self,
 2052        edits: I,
 2053        original_indent_columns: Vec<u32>,
 2054        cx: &mut ViewContext<Self>,
 2055    ) where
 2056        I: IntoIterator<Item = (Range<S>, T)>,
 2057        S: ToOffset,
 2058        T: Into<Arc<str>>,
 2059    {
 2060        if self.read_only(cx) {
 2061            return;
 2062        }
 2063
 2064        self.buffer.update(cx, |buffer, cx| {
 2065            buffer.edit(
 2066                edits,
 2067                Some(AutoindentMode::Block {
 2068                    original_indent_columns,
 2069                }),
 2070                cx,
 2071            )
 2072        });
 2073    }
 2074
 2075    fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
 2076        self.hide_context_menu(cx);
 2077
 2078        match phase {
 2079            SelectPhase::Begin {
 2080                position,
 2081                add,
 2082                click_count,
 2083            } => self.begin_selection(position, add, click_count, cx),
 2084            SelectPhase::BeginColumnar {
 2085                position,
 2086                goal_column,
 2087                reset,
 2088            } => self.begin_columnar_selection(position, goal_column, reset, cx),
 2089            SelectPhase::Extend {
 2090                position,
 2091                click_count,
 2092            } => self.extend_selection(position, click_count, cx),
 2093            SelectPhase::Update {
 2094                position,
 2095                goal_column,
 2096                scroll_delta,
 2097            } => self.update_selection(position, goal_column, scroll_delta, cx),
 2098            SelectPhase::End => self.end_selection(cx),
 2099        }
 2100    }
 2101
 2102    fn extend_selection(
 2103        &mut self,
 2104        position: DisplayPoint,
 2105        click_count: usize,
 2106        cx: &mut ViewContext<Self>,
 2107    ) {
 2108        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2109        let tail = self.selections.newest::<usize>(cx).tail();
 2110        self.begin_selection(position, false, click_count, cx);
 2111
 2112        let position = position.to_offset(&display_map, Bias::Left);
 2113        let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
 2114
 2115        let mut pending_selection = self
 2116            .selections
 2117            .pending_anchor()
 2118            .expect("extend_selection not called with pending selection");
 2119        if position >= tail {
 2120            pending_selection.start = tail_anchor;
 2121        } else {
 2122            pending_selection.end = tail_anchor;
 2123            pending_selection.reversed = true;
 2124        }
 2125
 2126        let mut pending_mode = self.selections.pending_mode().unwrap();
 2127        match &mut pending_mode {
 2128            SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
 2129            _ => {}
 2130        }
 2131
 2132        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 2133            s.set_pending(pending_selection, pending_mode)
 2134        });
 2135    }
 2136
 2137    fn begin_selection(
 2138        &mut self,
 2139        position: DisplayPoint,
 2140        add: bool,
 2141        click_count: usize,
 2142        cx: &mut ViewContext<Self>,
 2143    ) {
 2144        if !self.focus_handle.is_focused(cx) {
 2145            self.last_focused_descendant = None;
 2146            cx.focus(&self.focus_handle);
 2147        }
 2148
 2149        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2150        let buffer = &display_map.buffer_snapshot;
 2151        let newest_selection = self.selections.newest_anchor().clone();
 2152        let position = display_map.clip_point(position, Bias::Left);
 2153
 2154        let start;
 2155        let end;
 2156        let mode;
 2157        let mut auto_scroll;
 2158        match click_count {
 2159            1 => {
 2160                start = buffer.anchor_before(position.to_point(&display_map));
 2161                end = start;
 2162                mode = SelectMode::Character;
 2163                auto_scroll = true;
 2164            }
 2165            2 => {
 2166                let range = movement::surrounding_word(&display_map, position);
 2167                start = buffer.anchor_before(range.start.to_point(&display_map));
 2168                end = buffer.anchor_before(range.end.to_point(&display_map));
 2169                mode = SelectMode::Word(start..end);
 2170                auto_scroll = true;
 2171            }
 2172            3 => {
 2173                let position = display_map
 2174                    .clip_point(position, Bias::Left)
 2175                    .to_point(&display_map);
 2176                let line_start = display_map.prev_line_boundary(position).0;
 2177                let next_line_start = buffer.clip_point(
 2178                    display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2179                    Bias::Left,
 2180                );
 2181                start = buffer.anchor_before(line_start);
 2182                end = buffer.anchor_before(next_line_start);
 2183                mode = SelectMode::Line(start..end);
 2184                auto_scroll = true;
 2185            }
 2186            _ => {
 2187                start = buffer.anchor_before(0);
 2188                end = buffer.anchor_before(buffer.len());
 2189                mode = SelectMode::All;
 2190                auto_scroll = false;
 2191            }
 2192        }
 2193        auto_scroll &= EditorSettings::get_global(cx).autoscroll_on_clicks;
 2194
 2195        let point_to_delete: Option<usize> = {
 2196            let selected_points: Vec<Selection<Point>> =
 2197                self.selections.disjoint_in_range(start..end, cx);
 2198
 2199            if !add || click_count > 1 {
 2200                None
 2201            } else if !selected_points.is_empty() {
 2202                Some(selected_points[0].id)
 2203            } else {
 2204                let clicked_point_already_selected =
 2205                    self.selections.disjoint.iter().find(|selection| {
 2206                        selection.start.to_point(buffer) == start.to_point(buffer)
 2207                            || selection.end.to_point(buffer) == end.to_point(buffer)
 2208                    });
 2209
 2210                clicked_point_already_selected.map(|selection| selection.id)
 2211            }
 2212        };
 2213
 2214        let selections_count = self.selections.count();
 2215
 2216        self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
 2217            if let Some(point_to_delete) = point_to_delete {
 2218                s.delete(point_to_delete);
 2219
 2220                if selections_count == 1 {
 2221                    s.set_pending_anchor_range(start..end, mode);
 2222                }
 2223            } else {
 2224                if !add {
 2225                    s.clear_disjoint();
 2226                } else if click_count > 1 {
 2227                    s.delete(newest_selection.id)
 2228                }
 2229
 2230                s.set_pending_anchor_range(start..end, mode);
 2231            }
 2232        });
 2233    }
 2234
 2235    fn begin_columnar_selection(
 2236        &mut self,
 2237        position: DisplayPoint,
 2238        goal_column: u32,
 2239        reset: bool,
 2240        cx: &mut ViewContext<Self>,
 2241    ) {
 2242        if !self.focus_handle.is_focused(cx) {
 2243            self.last_focused_descendant = None;
 2244            cx.focus(&self.focus_handle);
 2245        }
 2246
 2247        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2248
 2249        if reset {
 2250            let pointer_position = display_map
 2251                .buffer_snapshot
 2252                .anchor_before(position.to_point(&display_map));
 2253
 2254            self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 2255                s.clear_disjoint();
 2256                s.set_pending_anchor_range(
 2257                    pointer_position..pointer_position,
 2258                    SelectMode::Character,
 2259                );
 2260            });
 2261        }
 2262
 2263        let tail = self.selections.newest::<Point>(cx).tail();
 2264        self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
 2265
 2266        if !reset {
 2267            self.select_columns(
 2268                tail.to_display_point(&display_map),
 2269                position,
 2270                goal_column,
 2271                &display_map,
 2272                cx,
 2273            );
 2274        }
 2275    }
 2276
 2277    fn update_selection(
 2278        &mut self,
 2279        position: DisplayPoint,
 2280        goal_column: u32,
 2281        scroll_delta: gpui::Point<f32>,
 2282        cx: &mut ViewContext<Self>,
 2283    ) {
 2284        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 2285
 2286        if let Some(tail) = self.columnar_selection_tail.as_ref() {
 2287            let tail = tail.to_display_point(&display_map);
 2288            self.select_columns(tail, position, goal_column, &display_map, cx);
 2289        } else if let Some(mut pending) = self.selections.pending_anchor() {
 2290            let buffer = self.buffer.read(cx).snapshot(cx);
 2291            let head;
 2292            let tail;
 2293            let mode = self.selections.pending_mode().unwrap();
 2294            match &mode {
 2295                SelectMode::Character => {
 2296                    head = position.to_point(&display_map);
 2297                    tail = pending.tail().to_point(&buffer);
 2298                }
 2299                SelectMode::Word(original_range) => {
 2300                    let original_display_range = original_range.start.to_display_point(&display_map)
 2301                        ..original_range.end.to_display_point(&display_map);
 2302                    let original_buffer_range = original_display_range.start.to_point(&display_map)
 2303                        ..original_display_range.end.to_point(&display_map);
 2304                    if movement::is_inside_word(&display_map, position)
 2305                        || original_display_range.contains(&position)
 2306                    {
 2307                        let word_range = movement::surrounding_word(&display_map, position);
 2308                        if word_range.start < original_display_range.start {
 2309                            head = word_range.start.to_point(&display_map);
 2310                        } else {
 2311                            head = word_range.end.to_point(&display_map);
 2312                        }
 2313                    } else {
 2314                        head = position.to_point(&display_map);
 2315                    }
 2316
 2317                    if head <= original_buffer_range.start {
 2318                        tail = original_buffer_range.end;
 2319                    } else {
 2320                        tail = original_buffer_range.start;
 2321                    }
 2322                }
 2323                SelectMode::Line(original_range) => {
 2324                    let original_range = original_range.to_point(&display_map.buffer_snapshot);
 2325
 2326                    let position = display_map
 2327                        .clip_point(position, Bias::Left)
 2328                        .to_point(&display_map);
 2329                    let line_start = display_map.prev_line_boundary(position).0;
 2330                    let next_line_start = buffer.clip_point(
 2331                        display_map.next_line_boundary(position).0 + Point::new(1, 0),
 2332                        Bias::Left,
 2333                    );
 2334
 2335                    if line_start < original_range.start {
 2336                        head = line_start
 2337                    } else {
 2338                        head = next_line_start
 2339                    }
 2340
 2341                    if head <= original_range.start {
 2342                        tail = original_range.end;
 2343                    } else {
 2344                        tail = original_range.start;
 2345                    }
 2346                }
 2347                SelectMode::All => {
 2348                    return;
 2349                }
 2350            };
 2351
 2352            if head < tail {
 2353                pending.start = buffer.anchor_before(head);
 2354                pending.end = buffer.anchor_before(tail);
 2355                pending.reversed = true;
 2356            } else {
 2357                pending.start = buffer.anchor_before(tail);
 2358                pending.end = buffer.anchor_before(head);
 2359                pending.reversed = false;
 2360            }
 2361
 2362            self.change_selections(None, cx, |s| {
 2363                s.set_pending(pending, mode);
 2364            });
 2365        } else {
 2366            log::error!("update_selection dispatched with no pending selection");
 2367            return;
 2368        }
 2369
 2370        self.apply_scroll_delta(scroll_delta, cx);
 2371        cx.notify();
 2372    }
 2373
 2374    fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
 2375        self.columnar_selection_tail.take();
 2376        if self.selections.pending_anchor().is_some() {
 2377            let selections = self.selections.all::<usize>(cx);
 2378            self.change_selections(None, cx, |s| {
 2379                s.select(selections);
 2380                s.clear_pending();
 2381            });
 2382        }
 2383    }
 2384
 2385    fn select_columns(
 2386        &mut self,
 2387        tail: DisplayPoint,
 2388        head: DisplayPoint,
 2389        goal_column: u32,
 2390        display_map: &DisplaySnapshot,
 2391        cx: &mut ViewContext<Self>,
 2392    ) {
 2393        let start_row = cmp::min(tail.row(), head.row());
 2394        let end_row = cmp::max(tail.row(), head.row());
 2395        let start_column = cmp::min(tail.column(), goal_column);
 2396        let end_column = cmp::max(tail.column(), goal_column);
 2397        let reversed = start_column < tail.column();
 2398
 2399        let selection_ranges = (start_row.0..=end_row.0)
 2400            .map(DisplayRow)
 2401            .filter_map(|row| {
 2402                if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
 2403                    let start = display_map
 2404                        .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
 2405                        .to_point(display_map);
 2406                    let end = display_map
 2407                        .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
 2408                        .to_point(display_map);
 2409                    if reversed {
 2410                        Some(end..start)
 2411                    } else {
 2412                        Some(start..end)
 2413                    }
 2414                } else {
 2415                    None
 2416                }
 2417            })
 2418            .collect::<Vec<_>>();
 2419
 2420        self.change_selections(None, cx, |s| {
 2421            s.select_ranges(selection_ranges);
 2422        });
 2423        cx.notify();
 2424    }
 2425
 2426    pub fn has_pending_nonempty_selection(&self) -> bool {
 2427        let pending_nonempty_selection = match self.selections.pending_anchor() {
 2428            Some(Selection { start, end, .. }) => start != end,
 2429            None => false,
 2430        };
 2431
 2432        pending_nonempty_selection
 2433            || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
 2434    }
 2435
 2436    pub fn has_pending_selection(&self) -> bool {
 2437        self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
 2438    }
 2439
 2440    pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
 2441        if self.clear_expanded_diff_hunks(cx) {
 2442            cx.notify();
 2443            return;
 2444        }
 2445        if self.dismiss_menus_and_popups(true, cx) {
 2446            return;
 2447        }
 2448
 2449        if self.mode == EditorMode::Full
 2450            && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
 2451        {
 2452            return;
 2453        }
 2454
 2455        cx.propagate();
 2456    }
 2457
 2458    pub fn dismiss_menus_and_popups(
 2459        &mut self,
 2460        should_report_inline_completion_event: bool,
 2461        cx: &mut ViewContext<Self>,
 2462    ) -> bool {
 2463        if self.take_rename(false, cx).is_some() {
 2464            return true;
 2465        }
 2466
 2467        if hide_hover(self, cx) {
 2468            return true;
 2469        }
 2470
 2471        if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
 2472            return true;
 2473        }
 2474
 2475        if self.hide_context_menu(cx).is_some() {
 2476            if self.has_active_inline_completion() {
 2477                self.update_visible_inline_completion(cx);
 2478            }
 2479            return true;
 2480        }
 2481
 2482        if self.mouse_context_menu.take().is_some() {
 2483            return true;
 2484        }
 2485
 2486        if self.discard_inline_completion(should_report_inline_completion_event, cx) {
 2487            return true;
 2488        }
 2489
 2490        if self.snippet_stack.pop().is_some() {
 2491            return true;
 2492        }
 2493
 2494        if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
 2495            self.dismiss_diagnostics(cx);
 2496            return true;
 2497        }
 2498
 2499        false
 2500    }
 2501
 2502    fn linked_editing_ranges_for(
 2503        &self,
 2504        selection: Range<text::Anchor>,
 2505        cx: &AppContext,
 2506    ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
 2507        if self.linked_edit_ranges.is_empty() {
 2508            return None;
 2509        }
 2510        let ((base_range, linked_ranges), buffer_snapshot, buffer) =
 2511            selection.end.buffer_id.and_then(|end_buffer_id| {
 2512                if selection.start.buffer_id != Some(end_buffer_id) {
 2513                    return None;
 2514                }
 2515                let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
 2516                let snapshot = buffer.read(cx).snapshot();
 2517                self.linked_edit_ranges
 2518                    .get(end_buffer_id, selection.start..selection.end, &snapshot)
 2519                    .map(|ranges| (ranges, snapshot, buffer))
 2520            })?;
 2521        use text::ToOffset as TO;
 2522        // find offset from the start of current range to current cursor position
 2523        let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
 2524
 2525        let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
 2526        let start_difference = start_offset - start_byte_offset;
 2527        let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
 2528        let end_difference = end_offset - start_byte_offset;
 2529        // Current range has associated linked ranges.
 2530        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2531        for range in linked_ranges.iter() {
 2532            let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
 2533            let end_offset = start_offset + end_difference;
 2534            let start_offset = start_offset + start_difference;
 2535            if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
 2536                continue;
 2537            }
 2538            if self.selections.disjoint_anchor_ranges().iter().any(|s| {
 2539                if s.start.buffer_id != selection.start.buffer_id
 2540                    || s.end.buffer_id != selection.end.buffer_id
 2541                {
 2542                    return false;
 2543                }
 2544                TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
 2545                    && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
 2546            }) {
 2547                continue;
 2548            }
 2549            let start = buffer_snapshot.anchor_after(start_offset);
 2550            let end = buffer_snapshot.anchor_after(end_offset);
 2551            linked_edits
 2552                .entry(buffer.clone())
 2553                .or_default()
 2554                .push(start..end);
 2555        }
 2556        Some(linked_edits)
 2557    }
 2558
 2559    pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 2560        let text: Arc<str> = text.into();
 2561
 2562        if self.read_only(cx) {
 2563            return;
 2564        }
 2565
 2566        let selections = self.selections.all_adjusted(cx);
 2567        let mut bracket_inserted = false;
 2568        let mut edits = Vec::new();
 2569        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 2570        let mut new_selections = Vec::with_capacity(selections.len());
 2571        let mut new_autoclose_regions = Vec::new();
 2572        let snapshot = self.buffer.read(cx).read(cx);
 2573
 2574        for (selection, autoclose_region) in
 2575            self.selections_with_autoclose_regions(selections, &snapshot)
 2576        {
 2577            if let Some(scope) = snapshot.language_scope_at(selection.head()) {
 2578                // Determine if the inserted text matches the opening or closing
 2579                // bracket of any of this language's bracket pairs.
 2580                let mut bracket_pair = None;
 2581                let mut is_bracket_pair_start = false;
 2582                let mut is_bracket_pair_end = false;
 2583                if !text.is_empty() {
 2584                    // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
 2585                    //  and they are removing the character that triggered IME popup.
 2586                    for (pair, enabled) in scope.brackets() {
 2587                        if !pair.close && !pair.surround {
 2588                            continue;
 2589                        }
 2590
 2591                        if enabled && pair.start.ends_with(text.as_ref()) {
 2592                            let prefix_len = pair.start.len() - text.len();
 2593                            let preceding_text_matches_prefix = prefix_len == 0
 2594                                || (selection.start.column >= (prefix_len as u32)
 2595                                    && snapshot.contains_str_at(
 2596                                        Point::new(
 2597                                            selection.start.row,
 2598                                            selection.start.column - (prefix_len as u32),
 2599                                        ),
 2600                                        &pair.start[..prefix_len],
 2601                                    ));
 2602                            if preceding_text_matches_prefix {
 2603                                bracket_pair = Some(pair.clone());
 2604                                is_bracket_pair_start = true;
 2605                                break;
 2606                            }
 2607                        }
 2608                        if pair.end.as_str() == text.as_ref() {
 2609                            bracket_pair = Some(pair.clone());
 2610                            is_bracket_pair_end = true;
 2611                            break;
 2612                        }
 2613                    }
 2614                }
 2615
 2616                if let Some(bracket_pair) = bracket_pair {
 2617                    let snapshot_settings = snapshot.settings_at(selection.start, cx);
 2618                    let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
 2619                    let auto_surround =
 2620                        self.use_auto_surround && snapshot_settings.use_auto_surround;
 2621                    if selection.is_empty() {
 2622                        if is_bracket_pair_start {
 2623                            // If the inserted text is a suffix of an opening bracket and the
 2624                            // selection is preceded by the rest of the opening bracket, then
 2625                            // insert the closing bracket.
 2626                            let following_text_allows_autoclose = snapshot
 2627                                .chars_at(selection.start)
 2628                                .next()
 2629                                .map_or(true, |c| scope.should_autoclose_before(c));
 2630
 2631                            let is_closing_quote = if bracket_pair.end == bracket_pair.start
 2632                                && bracket_pair.start.len() == 1
 2633                            {
 2634                                let target = bracket_pair.start.chars().next().unwrap();
 2635                                let current_line_count = snapshot
 2636                                    .reversed_chars_at(selection.start)
 2637                                    .take_while(|&c| c != '\n')
 2638                                    .filter(|&c| c == target)
 2639                                    .count();
 2640                                current_line_count % 2 == 1
 2641                            } else {
 2642                                false
 2643                            };
 2644
 2645                            if autoclose
 2646                                && bracket_pair.close
 2647                                && following_text_allows_autoclose
 2648                                && !is_closing_quote
 2649                            {
 2650                                let anchor = snapshot.anchor_before(selection.end);
 2651                                new_selections.push((selection.map(|_| anchor), text.len()));
 2652                                new_autoclose_regions.push((
 2653                                    anchor,
 2654                                    text.len(),
 2655                                    selection.id,
 2656                                    bracket_pair.clone(),
 2657                                ));
 2658                                edits.push((
 2659                                    selection.range(),
 2660                                    format!("{}{}", text, bracket_pair.end).into(),
 2661                                ));
 2662                                bracket_inserted = true;
 2663                                continue;
 2664                            }
 2665                        }
 2666
 2667                        if let Some(region) = autoclose_region {
 2668                            // If the selection is followed by an auto-inserted closing bracket,
 2669                            // then don't insert that closing bracket again; just move the selection
 2670                            // past the closing bracket.
 2671                            let should_skip = selection.end == region.range.end.to_point(&snapshot)
 2672                                && text.as_ref() == region.pair.end.as_str();
 2673                            if should_skip {
 2674                                let anchor = snapshot.anchor_after(selection.end);
 2675                                new_selections
 2676                                    .push((selection.map(|_| anchor), region.pair.end.len()));
 2677                                continue;
 2678                            }
 2679                        }
 2680
 2681                        let always_treat_brackets_as_autoclosed = snapshot
 2682                            .settings_at(selection.start, cx)
 2683                            .always_treat_brackets_as_autoclosed;
 2684                        if always_treat_brackets_as_autoclosed
 2685                            && is_bracket_pair_end
 2686                            && snapshot.contains_str_at(selection.end, text.as_ref())
 2687                        {
 2688                            // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
 2689                            // and the inserted text is a closing bracket and the selection is followed
 2690                            // by the closing bracket then move the selection past the closing bracket.
 2691                            let anchor = snapshot.anchor_after(selection.end);
 2692                            new_selections.push((selection.map(|_| anchor), text.len()));
 2693                            continue;
 2694                        }
 2695                    }
 2696                    // If an opening bracket is 1 character long and is typed while
 2697                    // text is selected, then surround that text with the bracket pair.
 2698                    else if auto_surround
 2699                        && bracket_pair.surround
 2700                        && is_bracket_pair_start
 2701                        && bracket_pair.start.chars().count() == 1
 2702                    {
 2703                        edits.push((selection.start..selection.start, text.clone()));
 2704                        edits.push((
 2705                            selection.end..selection.end,
 2706                            bracket_pair.end.as_str().into(),
 2707                        ));
 2708                        bracket_inserted = true;
 2709                        new_selections.push((
 2710                            Selection {
 2711                                id: selection.id,
 2712                                start: snapshot.anchor_after(selection.start),
 2713                                end: snapshot.anchor_before(selection.end),
 2714                                reversed: selection.reversed,
 2715                                goal: selection.goal,
 2716                            },
 2717                            0,
 2718                        ));
 2719                        continue;
 2720                    }
 2721                }
 2722            }
 2723
 2724            if self.auto_replace_emoji_shortcode
 2725                && selection.is_empty()
 2726                && text.as_ref().ends_with(':')
 2727            {
 2728                if let Some(possible_emoji_short_code) =
 2729                    Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
 2730                {
 2731                    if !possible_emoji_short_code.is_empty() {
 2732                        if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
 2733                            let emoji_shortcode_start = Point::new(
 2734                                selection.start.row,
 2735                                selection.start.column - possible_emoji_short_code.len() as u32 - 1,
 2736                            );
 2737
 2738                            // Remove shortcode from buffer
 2739                            edits.push((
 2740                                emoji_shortcode_start..selection.start,
 2741                                "".to_string().into(),
 2742                            ));
 2743                            new_selections.push((
 2744                                Selection {
 2745                                    id: selection.id,
 2746                                    start: snapshot.anchor_after(emoji_shortcode_start),
 2747                                    end: snapshot.anchor_before(selection.start),
 2748                                    reversed: selection.reversed,
 2749                                    goal: selection.goal,
 2750                                },
 2751                                0,
 2752                            ));
 2753
 2754                            // Insert emoji
 2755                            let selection_start_anchor = snapshot.anchor_after(selection.start);
 2756                            new_selections.push((selection.map(|_| selection_start_anchor), 0));
 2757                            edits.push((selection.start..selection.end, emoji.to_string().into()));
 2758
 2759                            continue;
 2760                        }
 2761                    }
 2762                }
 2763            }
 2764
 2765            // If not handling any auto-close operation, then just replace the selected
 2766            // text with the given input and move the selection to the end of the
 2767            // newly inserted text.
 2768            let anchor = snapshot.anchor_after(selection.end);
 2769            if !self.linked_edit_ranges.is_empty() {
 2770                let start_anchor = snapshot.anchor_before(selection.start);
 2771
 2772                let is_word_char = text.chars().next().map_or(true, |char| {
 2773                    let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
 2774                    classifier.is_word(char)
 2775                });
 2776
 2777                if is_word_char {
 2778                    if let Some(ranges) = self
 2779                        .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
 2780                    {
 2781                        for (buffer, edits) in ranges {
 2782                            linked_edits
 2783                                .entry(buffer.clone())
 2784                                .or_default()
 2785                                .extend(edits.into_iter().map(|range| (range, text.clone())));
 2786                        }
 2787                    }
 2788                }
 2789            }
 2790
 2791            new_selections.push((selection.map(|_| anchor), 0));
 2792            edits.push((selection.start..selection.end, text.clone()));
 2793        }
 2794
 2795        drop(snapshot);
 2796
 2797        self.transact(cx, |this, cx| {
 2798            this.buffer.update(cx, |buffer, cx| {
 2799                buffer.edit(edits, this.autoindent_mode.clone(), cx);
 2800            });
 2801            for (buffer, edits) in linked_edits {
 2802                buffer.update(cx, |buffer, cx| {
 2803                    let snapshot = buffer.snapshot();
 2804                    let edits = edits
 2805                        .into_iter()
 2806                        .map(|(range, text)| {
 2807                            use text::ToPoint as TP;
 2808                            let end_point = TP::to_point(&range.end, &snapshot);
 2809                            let start_point = TP::to_point(&range.start, &snapshot);
 2810                            (start_point..end_point, text)
 2811                        })
 2812                        .sorted_by_key(|(range, _)| range.start)
 2813                        .collect::<Vec<_>>();
 2814                    buffer.edit(edits, None, cx);
 2815                })
 2816            }
 2817            let new_anchor_selections = new_selections.iter().map(|e| &e.0);
 2818            let new_selection_deltas = new_selections.iter().map(|e| e.1);
 2819            let map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 2820            let new_selections = resolve_selections::<usize, _>(new_anchor_selections, &map)
 2821                .zip(new_selection_deltas)
 2822                .map(|(selection, delta)| Selection {
 2823                    id: selection.id,
 2824                    start: selection.start + delta,
 2825                    end: selection.end + delta,
 2826                    reversed: selection.reversed,
 2827                    goal: SelectionGoal::None,
 2828                })
 2829                .collect::<Vec<_>>();
 2830
 2831            let mut i = 0;
 2832            for (position, delta, selection_id, pair) in new_autoclose_regions {
 2833                let position = position.to_offset(&map.buffer_snapshot) + delta;
 2834                let start = map.buffer_snapshot.anchor_before(position);
 2835                let end = map.buffer_snapshot.anchor_after(position);
 2836                while let Some(existing_state) = this.autoclose_regions.get(i) {
 2837                    match existing_state.range.start.cmp(&start, &map.buffer_snapshot) {
 2838                        Ordering::Less => i += 1,
 2839                        Ordering::Greater => break,
 2840                        Ordering::Equal => {
 2841                            match end.cmp(&existing_state.range.end, &map.buffer_snapshot) {
 2842                                Ordering::Less => i += 1,
 2843                                Ordering::Equal => break,
 2844                                Ordering::Greater => break,
 2845                            }
 2846                        }
 2847                    }
 2848                }
 2849                this.autoclose_regions.insert(
 2850                    i,
 2851                    AutocloseRegion {
 2852                        selection_id,
 2853                        range: start..end,
 2854                        pair,
 2855                    },
 2856                );
 2857            }
 2858
 2859            this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
 2860                s.select(new_selections)
 2861            });
 2862
 2863            if !bracket_inserted {
 2864                if let Some(on_type_format_task) =
 2865                    this.trigger_on_type_formatting(text.to_string(), cx)
 2866                {
 2867                    on_type_format_task.detach_and_log_err(cx);
 2868                }
 2869            }
 2870
 2871            let editor_settings = EditorSettings::get_global(cx);
 2872            if bracket_inserted
 2873                && (editor_settings.auto_signature_help
 2874                    || editor_settings.show_signature_help_after_edits)
 2875            {
 2876                this.show_signature_help(&ShowSignatureHelp, cx);
 2877            }
 2878
 2879            this.trigger_completion_on_input(&text, true, cx);
 2880            linked_editing_ranges::refresh_linked_ranges(this, cx);
 2881            this.refresh_inline_completion(true, false, cx);
 2882        });
 2883    }
 2884
 2885    fn find_possible_emoji_shortcode_at_position(
 2886        snapshot: &MultiBufferSnapshot,
 2887        position: Point,
 2888    ) -> Option<String> {
 2889        let mut chars = Vec::new();
 2890        let mut found_colon = false;
 2891        for char in snapshot.reversed_chars_at(position).take(100) {
 2892            // Found a possible emoji shortcode in the middle of the buffer
 2893            if found_colon {
 2894                if char.is_whitespace() {
 2895                    chars.reverse();
 2896                    return Some(chars.iter().collect());
 2897                }
 2898                // If the previous character is not a whitespace, we are in the middle of a word
 2899                // and we only want to complete the shortcode if the word is made up of other emojis
 2900                let mut containing_word = String::new();
 2901                for ch in snapshot
 2902                    .reversed_chars_at(position)
 2903                    .skip(chars.len() + 1)
 2904                    .take(100)
 2905                {
 2906                    if ch.is_whitespace() {
 2907                        break;
 2908                    }
 2909                    containing_word.push(ch);
 2910                }
 2911                let containing_word = containing_word.chars().rev().collect::<String>();
 2912                if util::word_consists_of_emojis(containing_word.as_str()) {
 2913                    chars.reverse();
 2914                    return Some(chars.iter().collect());
 2915                }
 2916            }
 2917
 2918            if char.is_whitespace() || !char.is_ascii() {
 2919                return None;
 2920            }
 2921            if char == ':' {
 2922                found_colon = true;
 2923            } else {
 2924                chars.push(char);
 2925            }
 2926        }
 2927        // Found a possible emoji shortcode at the beginning of the buffer
 2928        chars.reverse();
 2929        Some(chars.iter().collect())
 2930    }
 2931
 2932    pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
 2933        self.transact(cx, |this, cx| {
 2934            let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
 2935                let selections = this.selections.all::<usize>(cx);
 2936                let multi_buffer = this.buffer.read(cx);
 2937                let buffer = multi_buffer.snapshot(cx);
 2938                selections
 2939                    .iter()
 2940                    .map(|selection| {
 2941                        let start_point = selection.start.to_point(&buffer);
 2942                        let mut indent =
 2943                            buffer.indent_size_for_line(MultiBufferRow(start_point.row));
 2944                        indent.len = cmp::min(indent.len, start_point.column);
 2945                        let start = selection.start;
 2946                        let end = selection.end;
 2947                        let selection_is_empty = start == end;
 2948                        let language_scope = buffer.language_scope_at(start);
 2949                        let (comment_delimiter, insert_extra_newline) = if let Some(language) =
 2950                            &language_scope
 2951                        {
 2952                            let leading_whitespace_len = buffer
 2953                                .reversed_chars_at(start)
 2954                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2955                                .map(|c| c.len_utf8())
 2956                                .sum::<usize>();
 2957
 2958                            let trailing_whitespace_len = buffer
 2959                                .chars_at(end)
 2960                                .take_while(|c| c.is_whitespace() && *c != '\n')
 2961                                .map(|c| c.len_utf8())
 2962                                .sum::<usize>();
 2963
 2964                            let insert_extra_newline =
 2965                                language.brackets().any(|(pair, enabled)| {
 2966                                    let pair_start = pair.start.trim_end();
 2967                                    let pair_end = pair.end.trim_start();
 2968
 2969                                    enabled
 2970                                        && pair.newline
 2971                                        && buffer.contains_str_at(
 2972                                            end + trailing_whitespace_len,
 2973                                            pair_end,
 2974                                        )
 2975                                        && buffer.contains_str_at(
 2976                                            (start - leading_whitespace_len)
 2977                                                .saturating_sub(pair_start.len()),
 2978                                            pair_start,
 2979                                        )
 2980                                });
 2981
 2982                            // Comment extension on newline is allowed only for cursor selections
 2983                            let comment_delimiter = maybe!({
 2984                                if !selection_is_empty {
 2985                                    return None;
 2986                                }
 2987
 2988                                if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
 2989                                    return None;
 2990                                }
 2991
 2992                                let delimiters = language.line_comment_prefixes();
 2993                                let max_len_of_delimiter =
 2994                                    delimiters.iter().map(|delimiter| delimiter.len()).max()?;
 2995                                let (snapshot, range) =
 2996                                    buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
 2997
 2998                                let mut index_of_first_non_whitespace = 0;
 2999                                let comment_candidate = snapshot
 3000                                    .chars_for_range(range)
 3001                                    .skip_while(|c| {
 3002                                        let should_skip = c.is_whitespace();
 3003                                        if should_skip {
 3004                                            index_of_first_non_whitespace += 1;
 3005                                        }
 3006                                        should_skip
 3007                                    })
 3008                                    .take(max_len_of_delimiter)
 3009                                    .collect::<String>();
 3010                                let comment_prefix = delimiters.iter().find(|comment_prefix| {
 3011                                    comment_candidate.starts_with(comment_prefix.as_ref())
 3012                                })?;
 3013                                let cursor_is_placed_after_comment_marker =
 3014                                    index_of_first_non_whitespace + comment_prefix.len()
 3015                                        <= start_point.column as usize;
 3016                                if cursor_is_placed_after_comment_marker {
 3017                                    Some(comment_prefix.clone())
 3018                                } else {
 3019                                    None
 3020                                }
 3021                            });
 3022                            (comment_delimiter, insert_extra_newline)
 3023                        } else {
 3024                            (None, false)
 3025                        };
 3026
 3027                        let capacity_for_delimiter = comment_delimiter
 3028                            .as_deref()
 3029                            .map(str::len)
 3030                            .unwrap_or_default();
 3031                        let mut new_text =
 3032                            String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
 3033                        new_text.push('\n');
 3034                        new_text.extend(indent.chars());
 3035                        if let Some(delimiter) = &comment_delimiter {
 3036                            new_text.push_str(delimiter);
 3037                        }
 3038                        if insert_extra_newline {
 3039                            new_text = new_text.repeat(2);
 3040                        }
 3041
 3042                        let anchor = buffer.anchor_after(end);
 3043                        let new_selection = selection.map(|_| anchor);
 3044                        (
 3045                            (start..end, new_text),
 3046                            (insert_extra_newline, new_selection),
 3047                        )
 3048                    })
 3049                    .unzip()
 3050            };
 3051
 3052            this.edit_with_autoindent(edits, cx);
 3053            let buffer = this.buffer.read(cx).snapshot(cx);
 3054            let new_selections = selection_fixup_info
 3055                .into_iter()
 3056                .map(|(extra_newline_inserted, new_selection)| {
 3057                    let mut cursor = new_selection.end.to_point(&buffer);
 3058                    if extra_newline_inserted {
 3059                        cursor.row -= 1;
 3060                        cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
 3061                    }
 3062                    new_selection.map(|_| cursor)
 3063                })
 3064                .collect();
 3065
 3066            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 3067            this.refresh_inline_completion(true, false, cx);
 3068        });
 3069    }
 3070
 3071    pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
 3072        let buffer = self.buffer.read(cx);
 3073        let snapshot = buffer.snapshot(cx);
 3074
 3075        let mut edits = Vec::new();
 3076        let mut rows = Vec::new();
 3077
 3078        for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
 3079            let cursor = selection.head();
 3080            let row = cursor.row;
 3081
 3082            let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
 3083
 3084            let newline = "\n".to_string();
 3085            edits.push((start_of_line..start_of_line, newline));
 3086
 3087            rows.push(row + rows_inserted as u32);
 3088        }
 3089
 3090        self.transact(cx, |editor, cx| {
 3091            editor.edit(edits, cx);
 3092
 3093            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3094                let mut index = 0;
 3095                s.move_cursors_with(|map, _, _| {
 3096                    let row = rows[index];
 3097                    index += 1;
 3098
 3099                    let point = Point::new(row, 0);
 3100                    let boundary = map.next_line_boundary(point).1;
 3101                    let clipped = map.clip_point(boundary, Bias::Left);
 3102
 3103                    (clipped, SelectionGoal::None)
 3104                });
 3105            });
 3106
 3107            let mut indent_edits = Vec::new();
 3108            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3109            for row in rows {
 3110                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3111                for (row, indent) in indents {
 3112                    if indent.len == 0 {
 3113                        continue;
 3114                    }
 3115
 3116                    let text = match indent.kind {
 3117                        IndentKind::Space => " ".repeat(indent.len as usize),
 3118                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3119                    };
 3120                    let point = Point::new(row.0, 0);
 3121                    indent_edits.push((point..point, text));
 3122                }
 3123            }
 3124            editor.edit(indent_edits, cx);
 3125        });
 3126    }
 3127
 3128    pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
 3129        let buffer = self.buffer.read(cx);
 3130        let snapshot = buffer.snapshot(cx);
 3131
 3132        let mut edits = Vec::new();
 3133        let mut rows = Vec::new();
 3134        let mut rows_inserted = 0;
 3135
 3136        for selection in self.selections.all_adjusted(cx) {
 3137            let cursor = selection.head();
 3138            let row = cursor.row;
 3139
 3140            let point = Point::new(row + 1, 0);
 3141            let start_of_line = snapshot.clip_point(point, Bias::Left);
 3142
 3143            let newline = "\n".to_string();
 3144            edits.push((start_of_line..start_of_line, newline));
 3145
 3146            rows_inserted += 1;
 3147            rows.push(row + rows_inserted);
 3148        }
 3149
 3150        self.transact(cx, |editor, cx| {
 3151            editor.edit(edits, cx);
 3152
 3153            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3154                let mut index = 0;
 3155                s.move_cursors_with(|map, _, _| {
 3156                    let row = rows[index];
 3157                    index += 1;
 3158
 3159                    let point = Point::new(row, 0);
 3160                    let boundary = map.next_line_boundary(point).1;
 3161                    let clipped = map.clip_point(boundary, Bias::Left);
 3162
 3163                    (clipped, SelectionGoal::None)
 3164                });
 3165            });
 3166
 3167            let mut indent_edits = Vec::new();
 3168            let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
 3169            for row in rows {
 3170                let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
 3171                for (row, indent) in indents {
 3172                    if indent.len == 0 {
 3173                        continue;
 3174                    }
 3175
 3176                    let text = match indent.kind {
 3177                        IndentKind::Space => " ".repeat(indent.len as usize),
 3178                        IndentKind::Tab => "\t".repeat(indent.len as usize),
 3179                    };
 3180                    let point = Point::new(row.0, 0);
 3181                    indent_edits.push((point..point, text));
 3182                }
 3183            }
 3184            editor.edit(indent_edits, cx);
 3185        });
 3186    }
 3187
 3188    pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
 3189        let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
 3190            original_indent_columns: Vec::new(),
 3191        });
 3192        self.insert_with_autoindent_mode(text, autoindent, cx);
 3193    }
 3194
 3195    fn insert_with_autoindent_mode(
 3196        &mut self,
 3197        text: &str,
 3198        autoindent_mode: Option<AutoindentMode>,
 3199        cx: &mut ViewContext<Self>,
 3200    ) {
 3201        if self.read_only(cx) {
 3202            return;
 3203        }
 3204
 3205        let text: Arc<str> = text.into();
 3206        self.transact(cx, |this, cx| {
 3207            let old_selections = this.selections.all_adjusted(cx);
 3208            let selection_anchors = this.buffer.update(cx, |buffer, cx| {
 3209                let anchors = {
 3210                    let snapshot = buffer.read(cx);
 3211                    old_selections
 3212                        .iter()
 3213                        .map(|s| {
 3214                            let anchor = snapshot.anchor_after(s.head());
 3215                            s.map(|_| anchor)
 3216                        })
 3217                        .collect::<Vec<_>>()
 3218                };
 3219                buffer.edit(
 3220                    old_selections
 3221                        .iter()
 3222                        .map(|s| (s.start..s.end, text.clone())),
 3223                    autoindent_mode,
 3224                    cx,
 3225                );
 3226                anchors
 3227            });
 3228
 3229            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 3230                s.select_anchors(selection_anchors);
 3231            })
 3232        });
 3233    }
 3234
 3235    fn trigger_completion_on_input(
 3236        &mut self,
 3237        text: &str,
 3238        trigger_in_words: bool,
 3239        cx: &mut ViewContext<Self>,
 3240    ) {
 3241        if self.is_completion_trigger(text, trigger_in_words, cx) {
 3242            self.show_completions(
 3243                &ShowCompletions {
 3244                    trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
 3245                },
 3246                cx,
 3247            );
 3248        } else {
 3249            self.hide_context_menu(cx);
 3250        }
 3251    }
 3252
 3253    fn is_completion_trigger(
 3254        &self,
 3255        text: &str,
 3256        trigger_in_words: bool,
 3257        cx: &mut ViewContext<Self>,
 3258    ) -> bool {
 3259        let position = self.selections.newest_anchor().head();
 3260        let multibuffer = self.buffer.read(cx);
 3261        let Some(buffer) = position
 3262            .buffer_id
 3263            .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
 3264        else {
 3265            return false;
 3266        };
 3267
 3268        if let Some(completion_provider) = &self.completion_provider {
 3269            completion_provider.is_completion_trigger(
 3270                &buffer,
 3271                position.text_anchor,
 3272                text,
 3273                trigger_in_words,
 3274                cx,
 3275            )
 3276        } else {
 3277            false
 3278        }
 3279    }
 3280
 3281    /// If any empty selections is touching the start of its innermost containing autoclose
 3282    /// region, expand it to select the brackets.
 3283    fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
 3284        let selections = self.selections.all::<usize>(cx);
 3285        let buffer = self.buffer.read(cx).read(cx);
 3286        let new_selections = self
 3287            .selections_with_autoclose_regions(selections, &buffer)
 3288            .map(|(mut selection, region)| {
 3289                if !selection.is_empty() {
 3290                    return selection;
 3291                }
 3292
 3293                if let Some(region) = region {
 3294                    let mut range = region.range.to_offset(&buffer);
 3295                    if selection.start == range.start && range.start >= region.pair.start.len() {
 3296                        range.start -= region.pair.start.len();
 3297                        if buffer.contains_str_at(range.start, &region.pair.start)
 3298                            && buffer.contains_str_at(range.end, &region.pair.end)
 3299                        {
 3300                            range.end += region.pair.end.len();
 3301                            selection.start = range.start;
 3302                            selection.end = range.end;
 3303
 3304                            return selection;
 3305                        }
 3306                    }
 3307                }
 3308
 3309                let always_treat_brackets_as_autoclosed = buffer
 3310                    .settings_at(selection.start, cx)
 3311                    .always_treat_brackets_as_autoclosed;
 3312
 3313                if !always_treat_brackets_as_autoclosed {
 3314                    return selection;
 3315                }
 3316
 3317                if let Some(scope) = buffer.language_scope_at(selection.start) {
 3318                    for (pair, enabled) in scope.brackets() {
 3319                        if !enabled || !pair.close {
 3320                            continue;
 3321                        }
 3322
 3323                        if buffer.contains_str_at(selection.start, &pair.end) {
 3324                            let pair_start_len = pair.start.len();
 3325                            if buffer.contains_str_at(
 3326                                selection.start.saturating_sub(pair_start_len),
 3327                                &pair.start,
 3328                            ) {
 3329                                selection.start -= pair_start_len;
 3330                                selection.end += pair.end.len();
 3331
 3332                                return selection;
 3333                            }
 3334                        }
 3335                    }
 3336                }
 3337
 3338                selection
 3339            })
 3340            .collect();
 3341
 3342        drop(buffer);
 3343        self.change_selections(None, cx, |selections| selections.select(new_selections));
 3344    }
 3345
 3346    /// Iterate the given selections, and for each one, find the smallest surrounding
 3347    /// autoclose region. This uses the ordering of the selections and the autoclose
 3348    /// regions to avoid repeated comparisons.
 3349    fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
 3350        &'a self,
 3351        selections: impl IntoIterator<Item = Selection<D>>,
 3352        buffer: &'a MultiBufferSnapshot,
 3353    ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
 3354        let mut i = 0;
 3355        let mut regions = self.autoclose_regions.as_slice();
 3356        selections.into_iter().map(move |selection| {
 3357            let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
 3358
 3359            let mut enclosing = None;
 3360            while let Some(pair_state) = regions.get(i) {
 3361                if pair_state.range.end.to_offset(buffer) < range.start {
 3362                    regions = &regions[i + 1..];
 3363                    i = 0;
 3364                } else if pair_state.range.start.to_offset(buffer) > range.end {
 3365                    break;
 3366                } else {
 3367                    if pair_state.selection_id == selection.id {
 3368                        enclosing = Some(pair_state);
 3369                    }
 3370                    i += 1;
 3371                }
 3372            }
 3373
 3374            (selection, enclosing)
 3375        })
 3376    }
 3377
 3378    /// Remove any autoclose regions that no longer contain their selection.
 3379    fn invalidate_autoclose_regions(
 3380        &mut self,
 3381        mut selections: &[Selection<Anchor>],
 3382        buffer: &MultiBufferSnapshot,
 3383    ) {
 3384        self.autoclose_regions.retain(|state| {
 3385            let mut i = 0;
 3386            while let Some(selection) = selections.get(i) {
 3387                if selection.end.cmp(&state.range.start, buffer).is_lt() {
 3388                    selections = &selections[1..];
 3389                    continue;
 3390                }
 3391                if selection.start.cmp(&state.range.end, buffer).is_gt() {
 3392                    break;
 3393                }
 3394                if selection.id == state.selection_id {
 3395                    return true;
 3396                } else {
 3397                    i += 1;
 3398                }
 3399            }
 3400            false
 3401        });
 3402    }
 3403
 3404    fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
 3405        let offset = position.to_offset(buffer);
 3406        let (word_range, kind) = buffer.surrounding_word(offset, true);
 3407        if offset > word_range.start && kind == Some(CharKind::Word) {
 3408            Some(
 3409                buffer
 3410                    .text_for_range(word_range.start..offset)
 3411                    .collect::<String>(),
 3412            )
 3413        } else {
 3414            None
 3415        }
 3416    }
 3417
 3418    pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
 3419        self.refresh_inlay_hints(
 3420            InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
 3421            cx,
 3422        );
 3423    }
 3424
 3425    pub fn inlay_hints_enabled(&self) -> bool {
 3426        self.inlay_hint_cache.enabled
 3427    }
 3428
 3429    fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
 3430        if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
 3431            return;
 3432        }
 3433
 3434        let reason_description = reason.description();
 3435        let ignore_debounce = matches!(
 3436            reason,
 3437            InlayHintRefreshReason::SettingsChange(_)
 3438                | InlayHintRefreshReason::Toggle(_)
 3439                | InlayHintRefreshReason::ExcerptsRemoved(_)
 3440        );
 3441        let (invalidate_cache, required_languages) = match reason {
 3442            InlayHintRefreshReason::Toggle(enabled) => {
 3443                self.inlay_hint_cache.enabled = enabled;
 3444                if enabled {
 3445                    (InvalidationStrategy::RefreshRequested, None)
 3446                } else {
 3447                    self.inlay_hint_cache.clear();
 3448                    self.splice_inlays(
 3449                        self.visible_inlay_hints(cx)
 3450                            .iter()
 3451                            .map(|inlay| inlay.id)
 3452                            .collect(),
 3453                        Vec::new(),
 3454                        cx,
 3455                    );
 3456                    return;
 3457                }
 3458            }
 3459            InlayHintRefreshReason::SettingsChange(new_settings) => {
 3460                match self.inlay_hint_cache.update_settings(
 3461                    &self.buffer,
 3462                    new_settings,
 3463                    self.visible_inlay_hints(cx),
 3464                    cx,
 3465                ) {
 3466                    ControlFlow::Break(Some(InlaySplice {
 3467                        to_remove,
 3468                        to_insert,
 3469                    })) => {
 3470                        self.splice_inlays(to_remove, to_insert, cx);
 3471                        return;
 3472                    }
 3473                    ControlFlow::Break(None) => return,
 3474                    ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
 3475                }
 3476            }
 3477            InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
 3478                if let Some(InlaySplice {
 3479                    to_remove,
 3480                    to_insert,
 3481                }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
 3482                {
 3483                    self.splice_inlays(to_remove, to_insert, cx);
 3484                }
 3485                return;
 3486            }
 3487            InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
 3488            InlayHintRefreshReason::BufferEdited(buffer_languages) => {
 3489                (InvalidationStrategy::BufferEdited, Some(buffer_languages))
 3490            }
 3491            InlayHintRefreshReason::RefreshRequested => {
 3492                (InvalidationStrategy::RefreshRequested, None)
 3493            }
 3494        };
 3495
 3496        if let Some(InlaySplice {
 3497            to_remove,
 3498            to_insert,
 3499        }) = self.inlay_hint_cache.spawn_hint_refresh(
 3500            reason_description,
 3501            self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
 3502            invalidate_cache,
 3503            ignore_debounce,
 3504            cx,
 3505        ) {
 3506            self.splice_inlays(to_remove, to_insert, cx);
 3507        }
 3508    }
 3509
 3510    fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
 3511        self.display_map
 3512            .read(cx)
 3513            .current_inlays()
 3514            .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
 3515            .cloned()
 3516            .collect()
 3517    }
 3518
 3519    pub fn excerpts_for_inlay_hints_query(
 3520        &self,
 3521        restrict_to_languages: Option<&HashSet<Arc<Language>>>,
 3522        cx: &mut ViewContext<Editor>,
 3523    ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
 3524        let Some(project) = self.project.as_ref() else {
 3525            return HashMap::default();
 3526        };
 3527        let project = project.read(cx);
 3528        let multi_buffer = self.buffer().read(cx);
 3529        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 3530        let multi_buffer_visible_start = self
 3531            .scroll_manager
 3532            .anchor()
 3533            .anchor
 3534            .to_point(&multi_buffer_snapshot);
 3535        let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
 3536            multi_buffer_visible_start
 3537                + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
 3538            Bias::Left,
 3539        );
 3540        let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
 3541        multi_buffer
 3542            .range_to_buffer_ranges(multi_buffer_visible_range, cx)
 3543            .into_iter()
 3544            .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
 3545            .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
 3546                let buffer = buffer_handle.read(cx);
 3547                let buffer_file = project::File::from_dyn(buffer.file())?;
 3548                let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
 3549                let worktree_entry = buffer_worktree
 3550                    .read(cx)
 3551                    .entry_for_id(buffer_file.project_entry_id(cx)?)?;
 3552                if worktree_entry.is_ignored {
 3553                    return None;
 3554                }
 3555
 3556                let language = buffer.language()?;
 3557                if let Some(restrict_to_languages) = restrict_to_languages {
 3558                    if !restrict_to_languages.contains(language) {
 3559                        return None;
 3560                    }
 3561                }
 3562                Some((
 3563                    excerpt_id,
 3564                    (
 3565                        buffer_handle,
 3566                        buffer.version().clone(),
 3567                        excerpt_visible_range,
 3568                    ),
 3569                ))
 3570            })
 3571            .collect()
 3572    }
 3573
 3574    pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
 3575        TextLayoutDetails {
 3576            text_system: cx.text_system().clone(),
 3577            editor_style: self.style.clone().unwrap(),
 3578            rem_size: cx.rem_size(),
 3579            scroll_anchor: self.scroll_manager.anchor(),
 3580            visible_rows: self.visible_line_count(),
 3581            vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
 3582        }
 3583    }
 3584
 3585    fn splice_inlays(
 3586        &self,
 3587        to_remove: Vec<InlayId>,
 3588        to_insert: Vec<Inlay>,
 3589        cx: &mut ViewContext<Self>,
 3590    ) {
 3591        self.display_map.update(cx, |display_map, cx| {
 3592            display_map.splice_inlays(to_remove, to_insert, cx)
 3593        });
 3594        cx.notify();
 3595    }
 3596
 3597    fn trigger_on_type_formatting(
 3598        &self,
 3599        input: String,
 3600        cx: &mut ViewContext<Self>,
 3601    ) -> Option<Task<Result<()>>> {
 3602        if input.len() != 1 {
 3603            return None;
 3604        }
 3605
 3606        let project = self.project.as_ref()?;
 3607        let position = self.selections.newest_anchor().head();
 3608        let (buffer, buffer_position) = self
 3609            .buffer
 3610            .read(cx)
 3611            .text_anchor_for_position(position, cx)?;
 3612
 3613        let settings = language_settings::language_settings(
 3614            buffer
 3615                .read(cx)
 3616                .language_at(buffer_position)
 3617                .map(|l| l.name()),
 3618            buffer.read(cx).file(),
 3619            cx,
 3620        );
 3621        if !settings.use_on_type_format {
 3622            return None;
 3623        }
 3624
 3625        // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
 3626        // hence we do LSP request & edit on host side only — add formats to host's history.
 3627        let push_to_lsp_host_history = true;
 3628        // If this is not the host, append its history with new edits.
 3629        let push_to_client_history = project.read(cx).is_via_collab();
 3630
 3631        let on_type_formatting = project.update(cx, |project, cx| {
 3632            project.on_type_format(
 3633                buffer.clone(),
 3634                buffer_position,
 3635                input,
 3636                push_to_lsp_host_history,
 3637                cx,
 3638            )
 3639        });
 3640        Some(cx.spawn(|editor, mut cx| async move {
 3641            if let Some(transaction) = on_type_formatting.await? {
 3642                if push_to_client_history {
 3643                    buffer
 3644                        .update(&mut cx, |buffer, _| {
 3645                            buffer.push_transaction(transaction, Instant::now());
 3646                        })
 3647                        .ok();
 3648                }
 3649                editor.update(&mut cx, |editor, cx| {
 3650                    editor.refresh_document_highlights(cx);
 3651                })?;
 3652            }
 3653            Ok(())
 3654        }))
 3655    }
 3656
 3657    pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
 3658        if self.pending_rename.is_some() {
 3659            return;
 3660        }
 3661
 3662        let Some(provider) = self.completion_provider.as_ref() else {
 3663            return;
 3664        };
 3665
 3666        if !self.snippet_stack.is_empty() && self.context_menu.borrow().as_ref().is_some() {
 3667            return;
 3668        }
 3669
 3670        let position = self.selections.newest_anchor().head();
 3671        let (buffer, buffer_position) =
 3672            if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
 3673                output
 3674            } else {
 3675                return;
 3676            };
 3677        let show_completion_documentation = buffer
 3678            .read(cx)
 3679            .snapshot()
 3680            .settings_at(buffer_position, cx)
 3681            .show_completion_documentation;
 3682
 3683        let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
 3684
 3685        let trigger_kind = match &options.trigger {
 3686            Some(trigger) if buffer.read(cx).completion_triggers().contains(trigger) => {
 3687                CompletionTriggerKind::TRIGGER_CHARACTER
 3688            }
 3689            _ => CompletionTriggerKind::INVOKED,
 3690        };
 3691        let completion_context = CompletionContext {
 3692            trigger_character: options.trigger.as_ref().and_then(|trigger| {
 3693                if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
 3694                    Some(String::from(trigger))
 3695                } else {
 3696                    None
 3697                }
 3698            }),
 3699            trigger_kind,
 3700        };
 3701        let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
 3702        let sort_completions = provider.sort_completions();
 3703
 3704        let id = post_inc(&mut self.next_completion_id);
 3705        let task = cx.spawn(|editor, mut cx| {
 3706            async move {
 3707                editor.update(&mut cx, |this, _| {
 3708                    this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
 3709                })?;
 3710                let completions = completions.await.log_err();
 3711                let menu = if let Some(completions) = completions {
 3712                    let mut menu = CompletionsMenu::new(
 3713                        id,
 3714                        sort_completions,
 3715                        show_completion_documentation,
 3716                        position,
 3717                        buffer.clone(),
 3718                        completions.into(),
 3719                    );
 3720
 3721                    menu.filter(query.as_deref(), cx.background_executor().clone())
 3722                        .await;
 3723
 3724                    menu.visible().then_some(menu)
 3725                } else {
 3726                    None
 3727                };
 3728
 3729                editor.update(&mut cx, |editor, cx| {
 3730                    match editor.context_menu.borrow().as_ref() {
 3731                        None => {}
 3732                        Some(CodeContextMenu::Completions(prev_menu)) => {
 3733                            if prev_menu.id > id {
 3734                                return;
 3735                            }
 3736                        }
 3737                        _ => return,
 3738                    }
 3739
 3740                    if editor.focus_handle.is_focused(cx) && menu.is_some() {
 3741                        let mut menu = menu.unwrap();
 3742                        menu.resolve_selected_completion(editor.completion_provider.as_deref(), cx);
 3743
 3744                        if let Some(hint) = editor.inline_completion_menu_hint(cx) {
 3745                            editor.hide_active_inline_completion(cx);
 3746                            menu.show_inline_completion_hint(hint);
 3747                        }
 3748
 3749                        *editor.context_menu.borrow_mut() =
 3750                            Some(CodeContextMenu::Completions(menu));
 3751
 3752                        cx.notify();
 3753                    } else if editor.completion_tasks.len() <= 1 {
 3754                        // If there are no more completion tasks and the last menu was
 3755                        // empty, we should hide it. If it was already hidden, we should
 3756                        // also show the copilot completion when available.
 3757                        editor.hide_context_menu(cx);
 3758                    }
 3759                })?;
 3760
 3761                Ok::<_, anyhow::Error>(())
 3762            }
 3763            .log_err()
 3764        });
 3765
 3766        self.completion_tasks.push((id, task));
 3767    }
 3768
 3769    pub fn confirm_completion(
 3770        &mut self,
 3771        action: &ConfirmCompletion,
 3772        cx: &mut ViewContext<Self>,
 3773    ) -> Option<Task<Result<()>>> {
 3774        self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
 3775    }
 3776
 3777    pub fn compose_completion(
 3778        &mut self,
 3779        action: &ComposeCompletion,
 3780        cx: &mut ViewContext<Self>,
 3781    ) -> Option<Task<Result<()>>> {
 3782        self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
 3783    }
 3784
 3785    fn do_completion(
 3786        &mut self,
 3787        item_ix: Option<usize>,
 3788        intent: CompletionIntent,
 3789        cx: &mut ViewContext<Editor>,
 3790    ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
 3791        use language::ToOffset as _;
 3792
 3793        let completions_menu =
 3794            if let CodeContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
 3795                menu
 3796            } else {
 3797                return None;
 3798            };
 3799
 3800        let mat = completions_menu
 3801            .entries
 3802            .get(item_ix.unwrap_or(completions_menu.selected_item))?;
 3803
 3804        let mat = match mat {
 3805            CompletionEntry::InlineCompletionHint { .. } => {
 3806                self.accept_inline_completion(&AcceptInlineCompletion, cx);
 3807                cx.stop_propagation();
 3808                return Some(Task::ready(Ok(())));
 3809            }
 3810            CompletionEntry::Match(mat) => {
 3811                self.discard_inline_completion(true, cx);
 3812                mat
 3813            }
 3814        };
 3815
 3816        let buffer_handle = completions_menu.buffer;
 3817        let completions = completions_menu.completions.borrow_mut();
 3818        let completion = completions.get(mat.candidate_id)?;
 3819        cx.stop_propagation();
 3820
 3821        let snippet;
 3822        let text;
 3823
 3824        if completion.is_snippet() {
 3825            snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
 3826            text = snippet.as_ref().unwrap().text.clone();
 3827        } else {
 3828            snippet = None;
 3829            text = completion.new_text.clone();
 3830        };
 3831        let selections = self.selections.all::<usize>(cx);
 3832        let buffer = buffer_handle.read(cx);
 3833        let old_range = completion.old_range.to_offset(buffer);
 3834        let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
 3835
 3836        let newest_selection = self.selections.newest_anchor();
 3837        if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
 3838            return None;
 3839        }
 3840
 3841        let lookbehind = newest_selection
 3842            .start
 3843            .text_anchor
 3844            .to_offset(buffer)
 3845            .saturating_sub(old_range.start);
 3846        let lookahead = old_range
 3847            .end
 3848            .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
 3849        let mut common_prefix_len = old_text
 3850            .bytes()
 3851            .zip(text.bytes())
 3852            .take_while(|(a, b)| a == b)
 3853            .count();
 3854
 3855        let snapshot = self.buffer.read(cx).snapshot(cx);
 3856        let mut range_to_replace: Option<Range<isize>> = None;
 3857        let mut ranges = Vec::new();
 3858        let mut linked_edits = HashMap::<_, Vec<_>>::default();
 3859        for selection in &selections {
 3860            if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
 3861                let start = selection.start.saturating_sub(lookbehind);
 3862                let end = selection.end + lookahead;
 3863                if selection.id == newest_selection.id {
 3864                    range_to_replace = Some(
 3865                        ((start + common_prefix_len) as isize - selection.start as isize)
 3866                            ..(end as isize - selection.start as isize),
 3867                    );
 3868                }
 3869                ranges.push(start + common_prefix_len..end);
 3870            } else {
 3871                common_prefix_len = 0;
 3872                ranges.clear();
 3873                ranges.extend(selections.iter().map(|s| {
 3874                    if s.id == newest_selection.id {
 3875                        range_to_replace = Some(
 3876                            old_range.start.to_offset_utf16(&snapshot).0 as isize
 3877                                - selection.start as isize
 3878                                ..old_range.end.to_offset_utf16(&snapshot).0 as isize
 3879                                    - selection.start as isize,
 3880                        );
 3881                        old_range.clone()
 3882                    } else {
 3883                        s.start..s.end
 3884                    }
 3885                }));
 3886                break;
 3887            }
 3888            if !self.linked_edit_ranges.is_empty() {
 3889                let start_anchor = snapshot.anchor_before(selection.head());
 3890                let end_anchor = snapshot.anchor_after(selection.tail());
 3891                if let Some(ranges) = self
 3892                    .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
 3893                {
 3894                    for (buffer, edits) in ranges {
 3895                        linked_edits.entry(buffer.clone()).or_default().extend(
 3896                            edits
 3897                                .into_iter()
 3898                                .map(|range| (range, text[common_prefix_len..].to_owned())),
 3899                        );
 3900                    }
 3901                }
 3902            }
 3903        }
 3904        let text = &text[common_prefix_len..];
 3905
 3906        cx.emit(EditorEvent::InputHandled {
 3907            utf16_range_to_replace: range_to_replace,
 3908            text: text.into(),
 3909        });
 3910
 3911        self.transact(cx, |this, cx| {
 3912            if let Some(mut snippet) = snippet {
 3913                snippet.text = text.to_string();
 3914                for tabstop in snippet
 3915                    .tabstops
 3916                    .iter_mut()
 3917                    .flat_map(|tabstop| tabstop.ranges.iter_mut())
 3918                {
 3919                    tabstop.start -= common_prefix_len as isize;
 3920                    tabstop.end -= common_prefix_len as isize;
 3921                }
 3922
 3923                this.insert_snippet(&ranges, snippet, cx).log_err();
 3924            } else {
 3925                this.buffer.update(cx, |buffer, cx| {
 3926                    buffer.edit(
 3927                        ranges.iter().map(|range| (range.clone(), text)),
 3928                        this.autoindent_mode.clone(),
 3929                        cx,
 3930                    );
 3931                });
 3932            }
 3933            for (buffer, edits) in linked_edits {
 3934                buffer.update(cx, |buffer, cx| {
 3935                    let snapshot = buffer.snapshot();
 3936                    let edits = edits
 3937                        .into_iter()
 3938                        .map(|(range, text)| {
 3939                            use text::ToPoint as TP;
 3940                            let end_point = TP::to_point(&range.end, &snapshot);
 3941                            let start_point = TP::to_point(&range.start, &snapshot);
 3942                            (start_point..end_point, text)
 3943                        })
 3944                        .sorted_by_key(|(range, _)| range.start)
 3945                        .collect::<Vec<_>>();
 3946                    buffer.edit(edits, None, cx);
 3947                })
 3948            }
 3949
 3950            this.refresh_inline_completion(true, false, cx);
 3951        });
 3952
 3953        let show_new_completions_on_confirm = completion
 3954            .confirm
 3955            .as_ref()
 3956            .map_or(false, |confirm| confirm(intent, cx));
 3957        if show_new_completions_on_confirm {
 3958            self.show_completions(&ShowCompletions { trigger: None }, cx);
 3959        }
 3960
 3961        let provider = self.completion_provider.as_ref()?;
 3962        let apply_edits = provider.apply_additional_edits_for_completion(
 3963            buffer_handle,
 3964            completion.clone(),
 3965            true,
 3966            cx,
 3967        );
 3968
 3969        let editor_settings = EditorSettings::get_global(cx);
 3970        if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
 3971            // After the code completion is finished, users often want to know what signatures are needed.
 3972            // so we should automatically call signature_help
 3973            self.show_signature_help(&ShowSignatureHelp, cx);
 3974        }
 3975
 3976        Some(cx.foreground_executor().spawn(async move {
 3977            apply_edits.await?;
 3978            Ok(())
 3979        }))
 3980    }
 3981
 3982    pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
 3983        let mut context_menu = self.context_menu.borrow_mut();
 3984        if let Some(CodeContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
 3985            if code_actions.deployed_from_indicator == action.deployed_from_indicator {
 3986                // Toggle if we're selecting the same one
 3987                *context_menu = None;
 3988                cx.notify();
 3989                return;
 3990            } else {
 3991                // Otherwise, clear it and start a new one
 3992                *context_menu = None;
 3993                cx.notify();
 3994            }
 3995        }
 3996        drop(context_menu);
 3997        let snapshot = self.snapshot(cx);
 3998        let deployed_from_indicator = action.deployed_from_indicator;
 3999        let mut task = self.code_actions_task.take();
 4000        let action = action.clone();
 4001        cx.spawn(|editor, mut cx| async move {
 4002            while let Some(prev_task) = task {
 4003                prev_task.await.log_err();
 4004                task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
 4005            }
 4006
 4007            let spawned_test_task = editor.update(&mut cx, |editor, cx| {
 4008                if editor.focus_handle.is_focused(cx) {
 4009                    let multibuffer_point = action
 4010                        .deployed_from_indicator
 4011                        .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
 4012                        .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
 4013                    let (buffer, buffer_row) = snapshot
 4014                        .buffer_snapshot
 4015                        .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
 4016                        .and_then(|(buffer_snapshot, range)| {
 4017                            editor
 4018                                .buffer
 4019                                .read(cx)
 4020                                .buffer(buffer_snapshot.remote_id())
 4021                                .map(|buffer| (buffer, range.start.row))
 4022                        })?;
 4023                    let (_, code_actions) = editor
 4024                        .available_code_actions
 4025                        .clone()
 4026                        .and_then(|(location, code_actions)| {
 4027                            let snapshot = location.buffer.read(cx).snapshot();
 4028                            let point_range = location.range.to_point(&snapshot);
 4029                            let point_range = point_range.start.row..=point_range.end.row;
 4030                            if point_range.contains(&buffer_row) {
 4031                                Some((location, code_actions))
 4032                            } else {
 4033                                None
 4034                            }
 4035                        })
 4036                        .unzip();
 4037                    let buffer_id = buffer.read(cx).remote_id();
 4038                    let tasks = editor
 4039                        .tasks
 4040                        .get(&(buffer_id, buffer_row))
 4041                        .map(|t| Arc::new(t.to_owned()));
 4042                    if tasks.is_none() && code_actions.is_none() {
 4043                        return None;
 4044                    }
 4045
 4046                    editor.completion_tasks.clear();
 4047                    editor.discard_inline_completion(false, cx);
 4048                    let task_context =
 4049                        tasks
 4050                            .as_ref()
 4051                            .zip(editor.project.clone())
 4052                            .map(|(tasks, project)| {
 4053                                Self::build_tasks_context(&project, &buffer, buffer_row, tasks, cx)
 4054                            });
 4055
 4056                    Some(cx.spawn(|editor, mut cx| async move {
 4057                        let task_context = match task_context {
 4058                            Some(task_context) => task_context.await,
 4059                            None => None,
 4060                        };
 4061                        let resolved_tasks =
 4062                            tasks.zip(task_context).map(|(tasks, task_context)| {
 4063                                Rc::new(ResolvedTasks {
 4064                                    templates: tasks.resolve(&task_context).collect(),
 4065                                    position: snapshot.buffer_snapshot.anchor_before(Point::new(
 4066                                        multibuffer_point.row,
 4067                                        tasks.column,
 4068                                    )),
 4069                                })
 4070                            });
 4071                        let spawn_straight_away = resolved_tasks
 4072                            .as_ref()
 4073                            .map_or(false, |tasks| tasks.templates.len() == 1)
 4074                            && code_actions
 4075                                .as_ref()
 4076                                .map_or(true, |actions| actions.is_empty());
 4077                        if let Ok(task) = editor.update(&mut cx, |editor, cx| {
 4078                            *editor.context_menu.borrow_mut() =
 4079                                Some(CodeContextMenu::CodeActions(CodeActionsMenu {
 4080                                    buffer,
 4081                                    actions: CodeActionContents {
 4082                                        tasks: resolved_tasks,
 4083                                        actions: code_actions,
 4084                                    },
 4085                                    selected_item: Default::default(),
 4086                                    scroll_handle: UniformListScrollHandle::default(),
 4087                                    deployed_from_indicator,
 4088                                }));
 4089                            if spawn_straight_away {
 4090                                if let Some(task) = editor.confirm_code_action(
 4091                                    &ConfirmCodeAction { item_ix: Some(0) },
 4092                                    cx,
 4093                                ) {
 4094                                    cx.notify();
 4095                                    return task;
 4096                                }
 4097                            }
 4098                            cx.notify();
 4099                            Task::ready(Ok(()))
 4100                        }) {
 4101                            task.await
 4102                        } else {
 4103                            Ok(())
 4104                        }
 4105                    }))
 4106                } else {
 4107                    Some(Task::ready(Ok(())))
 4108                }
 4109            })?;
 4110            if let Some(task) = spawned_test_task {
 4111                task.await?;
 4112            }
 4113
 4114            Ok::<_, anyhow::Error>(())
 4115        })
 4116        .detach_and_log_err(cx);
 4117    }
 4118
 4119    pub fn confirm_code_action(
 4120        &mut self,
 4121        action: &ConfirmCodeAction,
 4122        cx: &mut ViewContext<Self>,
 4123    ) -> Option<Task<Result<()>>> {
 4124        let actions_menu = if let CodeContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
 4125            menu
 4126        } else {
 4127            return None;
 4128        };
 4129        let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
 4130        let action = actions_menu.actions.get(action_ix)?;
 4131        let title = action.label();
 4132        let buffer = actions_menu.buffer;
 4133        let workspace = self.workspace()?;
 4134
 4135        match action {
 4136            CodeActionsItem::Task(task_source_kind, resolved_task) => {
 4137                workspace.update(cx, |workspace, cx| {
 4138                    workspace::tasks::schedule_resolved_task(
 4139                        workspace,
 4140                        task_source_kind,
 4141                        resolved_task,
 4142                        false,
 4143                        cx,
 4144                    );
 4145
 4146                    Some(Task::ready(Ok(())))
 4147                })
 4148            }
 4149            CodeActionsItem::CodeAction {
 4150                excerpt_id,
 4151                action,
 4152                provider,
 4153            } => {
 4154                let apply_code_action =
 4155                    provider.apply_code_action(buffer, action, excerpt_id, true, cx);
 4156                let workspace = workspace.downgrade();
 4157                Some(cx.spawn(|editor, cx| async move {
 4158                    let project_transaction = apply_code_action.await?;
 4159                    Self::open_project_transaction(
 4160                        &editor,
 4161                        workspace,
 4162                        project_transaction,
 4163                        title,
 4164                        cx,
 4165                    )
 4166                    .await
 4167                }))
 4168            }
 4169        }
 4170    }
 4171
 4172    pub async fn open_project_transaction(
 4173        this: &WeakView<Editor>,
 4174        workspace: WeakView<Workspace>,
 4175        transaction: ProjectTransaction,
 4176        title: String,
 4177        mut cx: AsyncWindowContext,
 4178    ) -> Result<()> {
 4179        let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
 4180        cx.update(|cx| {
 4181            entries.sort_unstable_by_key(|(buffer, _)| {
 4182                buffer.read(cx).file().map(|f| f.path().clone())
 4183            });
 4184        })?;
 4185
 4186        // If the project transaction's edits are all contained within this editor, then
 4187        // avoid opening a new editor to display them.
 4188
 4189        if let Some((buffer, transaction)) = entries.first() {
 4190            if entries.len() == 1 {
 4191                let excerpt = this.update(&mut cx, |editor, cx| {
 4192                    editor
 4193                        .buffer()
 4194                        .read(cx)
 4195                        .excerpt_containing(editor.selections.newest_anchor().head(), cx)
 4196                })?;
 4197                if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
 4198                    if excerpted_buffer == *buffer {
 4199                        let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
 4200                            let excerpt_range = excerpt_range.to_offset(buffer);
 4201                            buffer
 4202                                .edited_ranges_for_transaction::<usize>(transaction)
 4203                                .all(|range| {
 4204                                    excerpt_range.start <= range.start
 4205                                        && excerpt_range.end >= range.end
 4206                                })
 4207                        })?;
 4208
 4209                        if all_edits_within_excerpt {
 4210                            return Ok(());
 4211                        }
 4212                    }
 4213                }
 4214            }
 4215        } else {
 4216            return Ok(());
 4217        }
 4218
 4219        let mut ranges_to_highlight = Vec::new();
 4220        let excerpt_buffer = cx.new_model(|cx| {
 4221            let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
 4222            for (buffer_handle, transaction) in &entries {
 4223                let buffer = buffer_handle.read(cx);
 4224                ranges_to_highlight.extend(
 4225                    multibuffer.push_excerpts_with_context_lines(
 4226                        buffer_handle.clone(),
 4227                        buffer
 4228                            .edited_ranges_for_transaction::<usize>(transaction)
 4229                            .collect(),
 4230                        DEFAULT_MULTIBUFFER_CONTEXT,
 4231                        cx,
 4232                    ),
 4233                );
 4234            }
 4235            multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
 4236            multibuffer
 4237        })?;
 4238
 4239        workspace.update(&mut cx, |workspace, cx| {
 4240            let project = workspace.project().clone();
 4241            let editor =
 4242                cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
 4243            workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
 4244            editor.update(cx, |editor, cx| {
 4245                editor.highlight_background::<Self>(
 4246                    &ranges_to_highlight,
 4247                    |theme| theme.editor_highlighted_line_background,
 4248                    cx,
 4249                );
 4250            });
 4251        })?;
 4252
 4253        Ok(())
 4254    }
 4255
 4256    pub fn clear_code_action_providers(&mut self) {
 4257        self.code_action_providers.clear();
 4258        self.available_code_actions.take();
 4259    }
 4260
 4261    pub fn push_code_action_provider(
 4262        &mut self,
 4263        provider: Rc<dyn CodeActionProvider>,
 4264        cx: &mut ViewContext<Self>,
 4265    ) {
 4266        self.code_action_providers.push(provider);
 4267        self.refresh_code_actions(cx);
 4268    }
 4269
 4270    fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4271        let buffer = self.buffer.read(cx);
 4272        let newest_selection = self.selections.newest_anchor().clone();
 4273        let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
 4274        let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
 4275        if start_buffer != end_buffer {
 4276            return None;
 4277        }
 4278
 4279        self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
 4280            cx.background_executor()
 4281                .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
 4282                .await;
 4283
 4284            let (providers, tasks) = this.update(&mut cx, |this, cx| {
 4285                let providers = this.code_action_providers.clone();
 4286                let tasks = this
 4287                    .code_action_providers
 4288                    .iter()
 4289                    .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
 4290                    .collect::<Vec<_>>();
 4291                (providers, tasks)
 4292            })?;
 4293
 4294            let mut actions = Vec::new();
 4295            for (provider, provider_actions) in
 4296                providers.into_iter().zip(future::join_all(tasks).await)
 4297            {
 4298                if let Some(provider_actions) = provider_actions.log_err() {
 4299                    actions.extend(provider_actions.into_iter().map(|action| {
 4300                        AvailableCodeAction {
 4301                            excerpt_id: newest_selection.start.excerpt_id,
 4302                            action,
 4303                            provider: provider.clone(),
 4304                        }
 4305                    }));
 4306                }
 4307            }
 4308
 4309            this.update(&mut cx, |this, cx| {
 4310                this.available_code_actions = if actions.is_empty() {
 4311                    None
 4312                } else {
 4313                    Some((
 4314                        Location {
 4315                            buffer: start_buffer,
 4316                            range: start..end,
 4317                        },
 4318                        actions.into(),
 4319                    ))
 4320                };
 4321                cx.notify();
 4322            })
 4323        }));
 4324        None
 4325    }
 4326
 4327    fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
 4328        if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
 4329            self.show_git_blame_inline = false;
 4330
 4331            self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
 4332                cx.background_executor().timer(delay).await;
 4333
 4334                this.update(&mut cx, |this, cx| {
 4335                    this.show_git_blame_inline = true;
 4336                    cx.notify();
 4337                })
 4338                .log_err();
 4339            }));
 4340        }
 4341    }
 4342
 4343    fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4344        if self.pending_rename.is_some() {
 4345            return None;
 4346        }
 4347
 4348        let provider = self.semantics_provider.clone()?;
 4349        let buffer = self.buffer.read(cx);
 4350        let newest_selection = self.selections.newest_anchor().clone();
 4351        let cursor_position = newest_selection.head();
 4352        let (cursor_buffer, cursor_buffer_position) =
 4353            buffer.text_anchor_for_position(cursor_position, cx)?;
 4354        let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
 4355        if cursor_buffer != tail_buffer {
 4356            return None;
 4357        }
 4358        let debounce = EditorSettings::get_global(cx).lsp_highlight_debounce;
 4359        self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
 4360            cx.background_executor()
 4361                .timer(Duration::from_millis(debounce))
 4362                .await;
 4363
 4364            let highlights = if let Some(highlights) = cx
 4365                .update(|cx| {
 4366                    provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
 4367                })
 4368                .ok()
 4369                .flatten()
 4370            {
 4371                highlights.await.log_err()
 4372            } else {
 4373                None
 4374            };
 4375
 4376            if let Some(highlights) = highlights {
 4377                this.update(&mut cx, |this, cx| {
 4378                    if this.pending_rename.is_some() {
 4379                        return;
 4380                    }
 4381
 4382                    let buffer_id = cursor_position.buffer_id;
 4383                    let buffer = this.buffer.read(cx);
 4384                    if !buffer
 4385                        .text_anchor_for_position(cursor_position, cx)
 4386                        .map_or(false, |(buffer, _)| buffer == cursor_buffer)
 4387                    {
 4388                        return;
 4389                    }
 4390
 4391                    let cursor_buffer_snapshot = cursor_buffer.read(cx);
 4392                    let mut write_ranges = Vec::new();
 4393                    let mut read_ranges = Vec::new();
 4394                    for highlight in highlights {
 4395                        for (excerpt_id, excerpt_range) in
 4396                            buffer.excerpts_for_buffer(&cursor_buffer, cx)
 4397                        {
 4398                            let start = highlight
 4399                                .range
 4400                                .start
 4401                                .max(&excerpt_range.context.start, cursor_buffer_snapshot);
 4402                            let end = highlight
 4403                                .range
 4404                                .end
 4405                                .min(&excerpt_range.context.end, cursor_buffer_snapshot);
 4406                            if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
 4407                                continue;
 4408                            }
 4409
 4410                            let range = Anchor {
 4411                                buffer_id,
 4412                                excerpt_id,
 4413                                text_anchor: start,
 4414                            }..Anchor {
 4415                                buffer_id,
 4416                                excerpt_id,
 4417                                text_anchor: end,
 4418                            };
 4419                            if highlight.kind == lsp::DocumentHighlightKind::WRITE {
 4420                                write_ranges.push(range);
 4421                            } else {
 4422                                read_ranges.push(range);
 4423                            }
 4424                        }
 4425                    }
 4426
 4427                    this.highlight_background::<DocumentHighlightRead>(
 4428                        &read_ranges,
 4429                        |theme| theme.editor_document_highlight_read_background,
 4430                        cx,
 4431                    );
 4432                    this.highlight_background::<DocumentHighlightWrite>(
 4433                        &write_ranges,
 4434                        |theme| theme.editor_document_highlight_write_background,
 4435                        cx,
 4436                    );
 4437                    cx.notify();
 4438                })
 4439                .log_err();
 4440            }
 4441        }));
 4442        None
 4443    }
 4444
 4445    pub fn refresh_inline_completion(
 4446        &mut self,
 4447        debounce: bool,
 4448        user_requested: bool,
 4449        cx: &mut ViewContext<Self>,
 4450    ) -> Option<()> {
 4451        let provider = self.inline_completion_provider()?;
 4452        let cursor = self.selections.newest_anchor().head();
 4453        let (buffer, cursor_buffer_position) =
 4454            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4455
 4456        if !user_requested
 4457            && (!self.enable_inline_completions
 4458                || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4459                || !self.is_focused(cx))
 4460        {
 4461            self.discard_inline_completion(false, cx);
 4462            return None;
 4463        }
 4464
 4465        self.update_visible_inline_completion(cx);
 4466        provider.refresh(buffer, cursor_buffer_position, debounce, cx);
 4467        Some(())
 4468    }
 4469
 4470    fn cycle_inline_completion(
 4471        &mut self,
 4472        direction: Direction,
 4473        cx: &mut ViewContext<Self>,
 4474    ) -> Option<()> {
 4475        let provider = self.inline_completion_provider()?;
 4476        let cursor = self.selections.newest_anchor().head();
 4477        let (buffer, cursor_buffer_position) =
 4478            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4479        if !self.enable_inline_completions
 4480            || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
 4481        {
 4482            return None;
 4483        }
 4484
 4485        provider.cycle(buffer, cursor_buffer_position, direction, cx);
 4486        self.update_visible_inline_completion(cx);
 4487
 4488        Some(())
 4489    }
 4490
 4491    pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
 4492        if !self.has_active_inline_completion() {
 4493            self.refresh_inline_completion(false, true, cx);
 4494            return;
 4495        }
 4496
 4497        self.update_visible_inline_completion(cx);
 4498    }
 4499
 4500    pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
 4501        self.show_cursor_names(cx);
 4502    }
 4503
 4504    fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
 4505        self.show_cursor_names = true;
 4506        cx.notify();
 4507        cx.spawn(|this, mut cx| async move {
 4508            cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
 4509            this.update(&mut cx, |this, cx| {
 4510                this.show_cursor_names = false;
 4511                cx.notify()
 4512            })
 4513            .ok()
 4514        })
 4515        .detach();
 4516    }
 4517
 4518    pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
 4519        if self.has_active_inline_completion() {
 4520            self.cycle_inline_completion(Direction::Next, cx);
 4521        } else {
 4522            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4523            if is_copilot_disabled {
 4524                cx.propagate();
 4525            }
 4526        }
 4527    }
 4528
 4529    pub fn previous_inline_completion(
 4530        &mut self,
 4531        _: &PreviousInlineCompletion,
 4532        cx: &mut ViewContext<Self>,
 4533    ) {
 4534        if self.has_active_inline_completion() {
 4535            self.cycle_inline_completion(Direction::Prev, cx);
 4536        } else {
 4537            let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
 4538            if is_copilot_disabled {
 4539                cx.propagate();
 4540            }
 4541        }
 4542    }
 4543
 4544    pub fn accept_inline_completion(
 4545        &mut self,
 4546        _: &AcceptInlineCompletion,
 4547        cx: &mut ViewContext<Self>,
 4548    ) {
 4549        self.hide_context_menu(cx);
 4550
 4551        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4552            return;
 4553        };
 4554
 4555        self.report_inline_completion_event(true, cx);
 4556
 4557        match &active_inline_completion.completion {
 4558            InlineCompletion::Move(position) => {
 4559                let position = *position;
 4560                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4561                    selections.select_anchor_ranges([position..position]);
 4562                });
 4563            }
 4564            InlineCompletion::Edit(edits) => {
 4565                if let Some(provider) = self.inline_completion_provider() {
 4566                    provider.accept(cx);
 4567                }
 4568
 4569                let snapshot = self.buffer.read(cx).snapshot(cx);
 4570                let last_edit_end = edits.last().unwrap().0.end.bias_right(&snapshot);
 4571
 4572                self.buffer.update(cx, |buffer, cx| {
 4573                    buffer.edit(edits.iter().cloned(), None, cx)
 4574                });
 4575
 4576                self.change_selections(None, cx, |s| {
 4577                    s.select_anchor_ranges([last_edit_end..last_edit_end])
 4578                });
 4579
 4580                self.update_visible_inline_completion(cx);
 4581                if self.active_inline_completion.is_none() {
 4582                    self.refresh_inline_completion(true, true, cx);
 4583                }
 4584
 4585                cx.notify();
 4586            }
 4587        }
 4588    }
 4589
 4590    pub fn accept_partial_inline_completion(
 4591        &mut self,
 4592        _: &AcceptPartialInlineCompletion,
 4593        cx: &mut ViewContext<Self>,
 4594    ) {
 4595        let Some(active_inline_completion) = self.active_inline_completion.as_ref() else {
 4596            return;
 4597        };
 4598        if self.selections.count() != 1 {
 4599            return;
 4600        }
 4601
 4602        self.report_inline_completion_event(true, cx);
 4603
 4604        match &active_inline_completion.completion {
 4605            InlineCompletion::Move(position) => {
 4606                let position = *position;
 4607                self.change_selections(Some(Autoscroll::newest()), cx, |selections| {
 4608                    selections.select_anchor_ranges([position..position]);
 4609                });
 4610            }
 4611            InlineCompletion::Edit(edits) => {
 4612                if edits.len() == 1 && edits[0].0.start == edits[0].0.end {
 4613                    let text = edits[0].1.as_str();
 4614                    let mut partial_completion = text
 4615                        .chars()
 4616                        .by_ref()
 4617                        .take_while(|c| c.is_alphabetic())
 4618                        .collect::<String>();
 4619                    if partial_completion.is_empty() {
 4620                        partial_completion = text
 4621                            .chars()
 4622                            .by_ref()
 4623                            .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
 4624                            .collect::<String>();
 4625                    }
 4626
 4627                    cx.emit(EditorEvent::InputHandled {
 4628                        utf16_range_to_replace: None,
 4629                        text: partial_completion.clone().into(),
 4630                    });
 4631
 4632                    self.insert_with_autoindent_mode(&partial_completion, None, cx);
 4633
 4634                    self.refresh_inline_completion(true, true, cx);
 4635                    cx.notify();
 4636                }
 4637            }
 4638        }
 4639    }
 4640
 4641    fn discard_inline_completion(
 4642        &mut self,
 4643        should_report_inline_completion_event: bool,
 4644        cx: &mut ViewContext<Self>,
 4645    ) -> bool {
 4646        if should_report_inline_completion_event {
 4647            self.report_inline_completion_event(false, cx);
 4648        }
 4649
 4650        if let Some(provider) = self.inline_completion_provider() {
 4651            provider.discard(cx);
 4652        }
 4653
 4654        self.take_active_inline_completion(cx).is_some()
 4655    }
 4656
 4657    fn report_inline_completion_event(&self, accepted: bool, cx: &AppContext) {
 4658        let Some(provider) = self.inline_completion_provider() else {
 4659            return;
 4660        };
 4661        let Some(project) = self.project.as_ref() else {
 4662            return;
 4663        };
 4664        let Some((_, buffer, _)) = self
 4665            .buffer
 4666            .read(cx)
 4667            .excerpt_containing(self.selections.newest_anchor().head(), cx)
 4668        else {
 4669            return;
 4670        };
 4671
 4672        let project = project.read(cx);
 4673        let extension = buffer
 4674            .read(cx)
 4675            .file()
 4676            .and_then(|file| Some(file.path().extension()?.to_string_lossy().to_string()));
 4677        project.client().telemetry().report_inline_completion_event(
 4678            provider.name().into(),
 4679            accepted,
 4680            extension,
 4681        );
 4682    }
 4683
 4684    pub fn has_active_inline_completion(&self) -> bool {
 4685        self.active_inline_completion.is_some()
 4686    }
 4687
 4688    fn take_active_inline_completion(
 4689        &mut self,
 4690        cx: &mut ViewContext<Self>,
 4691    ) -> Option<InlineCompletion> {
 4692        let active_inline_completion = self.active_inline_completion.take()?;
 4693        self.splice_inlays(active_inline_completion.inlay_ids, Default::default(), cx);
 4694        self.clear_highlights::<InlineCompletionHighlight>(cx);
 4695        Some(active_inline_completion.completion)
 4696    }
 4697
 4698    fn hide_active_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
 4699        if let Some(active_inline_completion) = self.active_inline_completion.as_ref() {
 4700            self.splice_inlays(
 4701                active_inline_completion.inlay_ids.clone(),
 4702                Default::default(),
 4703                cx,
 4704            );
 4705            self.clear_highlights::<InlineCompletionHighlight>(cx);
 4706        }
 4707    }
 4708
 4709    fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
 4710        let selection = self.selections.newest_anchor();
 4711        let cursor = selection.head();
 4712        let multibuffer = self.buffer.read(cx).snapshot(cx);
 4713        let offset_selection = selection.map(|endpoint| endpoint.to_offset(&multibuffer));
 4714        let excerpt_id = cursor.excerpt_id;
 4715
 4716        if !offset_selection.is_empty()
 4717            || self
 4718                .active_inline_completion
 4719                .as_ref()
 4720                .map_or(false, |completion| {
 4721                    let invalidation_range = completion.invalidation_range.to_offset(&multibuffer);
 4722                    let invalidation_range = invalidation_range.start..=invalidation_range.end;
 4723                    !invalidation_range.contains(&offset_selection.head())
 4724                })
 4725        {
 4726            self.discard_inline_completion(false, cx);
 4727            return None;
 4728        }
 4729
 4730        self.take_active_inline_completion(cx);
 4731        let provider = self.inline_completion_provider()?;
 4732
 4733        let (buffer, cursor_buffer_position) =
 4734            self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
 4735
 4736        let completion = provider.suggest(&buffer, cursor_buffer_position, cx)?;
 4737        let edits = completion
 4738            .edits
 4739            .into_iter()
 4740            .flat_map(|(range, new_text)| {
 4741                let start = multibuffer.anchor_in_excerpt(excerpt_id, range.start)?;
 4742                let end = multibuffer.anchor_in_excerpt(excerpt_id, range.end)?;
 4743                Some((start..end, new_text))
 4744            })
 4745            .collect::<Vec<_>>();
 4746        if edits.is_empty() {
 4747            return None;
 4748        }
 4749
 4750        let first_edit_start = edits.first().unwrap().0.start;
 4751        let edit_start_row = first_edit_start
 4752            .to_point(&multibuffer)
 4753            .row
 4754            .saturating_sub(2);
 4755
 4756        let last_edit_end = edits.last().unwrap().0.end;
 4757        let edit_end_row = cmp::min(
 4758            multibuffer.max_point().row,
 4759            last_edit_end.to_point(&multibuffer).row + 2,
 4760        );
 4761
 4762        let cursor_row = cursor.to_point(&multibuffer).row;
 4763
 4764        let mut inlay_ids = Vec::new();
 4765        let invalidation_row_range;
 4766        let completion;
 4767        if cursor_row < edit_start_row {
 4768            invalidation_row_range = cursor_row..edit_end_row;
 4769            completion = InlineCompletion::Move(first_edit_start);
 4770        } else if cursor_row > edit_end_row {
 4771            invalidation_row_range = edit_start_row..cursor_row;
 4772            completion = InlineCompletion::Move(first_edit_start);
 4773        } else {
 4774            if !self.has_active_completions_menu() {
 4775                if edits
 4776                    .iter()
 4777                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4778                {
 4779                    let mut inlays = Vec::new();
 4780                    for (range, new_text) in &edits {
 4781                        let inlay = Inlay::inline_completion(
 4782                            post_inc(&mut self.next_inlay_id),
 4783                            range.start,
 4784                            new_text.as_str(),
 4785                        );
 4786                        inlay_ids.push(inlay.id);
 4787                        inlays.push(inlay);
 4788                    }
 4789
 4790                    self.splice_inlays(vec![], inlays, cx);
 4791                } else {
 4792                    let background_color = cx.theme().status().deleted_background;
 4793                    self.highlight_text::<InlineCompletionHighlight>(
 4794                        edits.iter().map(|(range, _)| range.clone()).collect(),
 4795                        HighlightStyle {
 4796                            background_color: Some(background_color),
 4797                            ..Default::default()
 4798                        },
 4799                        cx,
 4800                    );
 4801                }
 4802            }
 4803
 4804            invalidation_row_range = edit_start_row..edit_end_row;
 4805            completion = InlineCompletion::Edit(edits);
 4806        };
 4807
 4808        let invalidation_range = multibuffer
 4809            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4810            ..multibuffer.anchor_after(Point::new(
 4811                invalidation_row_range.end,
 4812                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4813            ));
 4814
 4815        self.active_inline_completion = Some(InlineCompletionState {
 4816            inlay_ids,
 4817            completion,
 4818            invalidation_range,
 4819        });
 4820
 4821        if self.has_active_completions_menu() {
 4822            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4823                match self.context_menu.borrow_mut().as_mut() {
 4824                    Some(CodeContextMenu::Completions(menu)) => {
 4825                        menu.show_inline_completion_hint(hint);
 4826                    }
 4827                    _ => {}
 4828                }
 4829            }
 4830        }
 4831
 4832        cx.notify();
 4833
 4834        Some(())
 4835    }
 4836
 4837    fn inline_completion_menu_hint(
 4838        &mut self,
 4839        cx: &mut ViewContext<Self>,
 4840    ) -> Option<InlineCompletionMenuHint> {
 4841        if self.has_active_inline_completion() {
 4842            let provider_name = self.inline_completion_provider()?.display_name();
 4843            let editor_snapshot = self.snapshot(cx);
 4844
 4845            let text = match &self.active_inline_completion.as_ref()?.completion {
 4846                InlineCompletion::Edit(edits) => {
 4847                    inline_completion_edit_text(&editor_snapshot, edits, cx)
 4848                }
 4849                InlineCompletion::Move(target) => {
 4850                    let target_point =
 4851                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4852                    let target_line = target_point.row + 1;
 4853                    InlineCompletionText::Move(
 4854                        format!("Jump to edit in line {}", target_line).into(),
 4855                    )
 4856                }
 4857            };
 4858
 4859            Some(InlineCompletionMenuHint {
 4860                provider_name,
 4861                text,
 4862            })
 4863        } else {
 4864            None
 4865        }
 4866    }
 4867
 4868    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4869        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4870    }
 4871
 4872    fn render_code_actions_indicator(
 4873        &self,
 4874        _style: &EditorStyle,
 4875        row: DisplayRow,
 4876        is_active: bool,
 4877        cx: &mut ViewContext<Self>,
 4878    ) -> Option<IconButton> {
 4879        if self.available_code_actions.is_some() {
 4880            Some(
 4881                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4882                    .shape(ui::IconButtonShape::Square)
 4883                    .icon_size(IconSize::XSmall)
 4884                    .icon_color(Color::Muted)
 4885                    .toggle_state(is_active)
 4886                    .tooltip({
 4887                        let focus_handle = self.focus_handle.clone();
 4888                        move |cx| {
 4889                            Tooltip::for_action_in(
 4890                                "Toggle Code Actions",
 4891                                &ToggleCodeActions {
 4892                                    deployed_from_indicator: None,
 4893                                },
 4894                                &focus_handle,
 4895                                cx,
 4896                            )
 4897                        }
 4898                    })
 4899                    .on_click(cx.listener(move |editor, _e, cx| {
 4900                        editor.focus(cx);
 4901                        editor.toggle_code_actions(
 4902                            &ToggleCodeActions {
 4903                                deployed_from_indicator: Some(row),
 4904                            },
 4905                            cx,
 4906                        );
 4907                    })),
 4908            )
 4909        } else {
 4910            None
 4911        }
 4912    }
 4913
 4914    fn clear_tasks(&mut self) {
 4915        self.tasks.clear()
 4916    }
 4917
 4918    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4919        if self.tasks.insert(key, value).is_some() {
 4920            // This case should hopefully be rare, but just in case...
 4921            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4922        }
 4923    }
 4924
 4925    fn build_tasks_context(
 4926        project: &Model<Project>,
 4927        buffer: &Model<Buffer>,
 4928        buffer_row: u32,
 4929        tasks: &Arc<RunnableTasks>,
 4930        cx: &mut ViewContext<Self>,
 4931    ) -> Task<Option<task::TaskContext>> {
 4932        let position = Point::new(buffer_row, tasks.column);
 4933        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4934        let location = Location {
 4935            buffer: buffer.clone(),
 4936            range: range_start..range_start,
 4937        };
 4938        // Fill in the environmental variables from the tree-sitter captures
 4939        let mut captured_task_variables = TaskVariables::default();
 4940        for (capture_name, value) in tasks.extra_variables.clone() {
 4941            captured_task_variables.insert(
 4942                task::VariableName::Custom(capture_name.into()),
 4943                value.clone(),
 4944            );
 4945        }
 4946        project.update(cx, |project, cx| {
 4947            project.task_store().update(cx, |task_store, cx| {
 4948                task_store.task_context_for_location(captured_task_variables, location, cx)
 4949            })
 4950        })
 4951    }
 4952
 4953    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4954        let Some((workspace, _)) = self.workspace.clone() else {
 4955            return;
 4956        };
 4957        let Some(project) = self.project.clone() else {
 4958            return;
 4959        };
 4960
 4961        // Try to find a closest, enclosing node using tree-sitter that has a
 4962        // task
 4963        let Some((buffer, buffer_row, tasks)) = self
 4964            .find_enclosing_node_task(cx)
 4965            // Or find the task that's closest in row-distance.
 4966            .or_else(|| self.find_closest_task(cx))
 4967        else {
 4968            return;
 4969        };
 4970
 4971        let reveal_strategy = action.reveal;
 4972        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4973        cx.spawn(|_, mut cx| async move {
 4974            let context = task_context.await?;
 4975            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4976
 4977            let resolved = resolved_task.resolved.as_mut()?;
 4978            resolved.reveal = reveal_strategy;
 4979
 4980            workspace
 4981                .update(&mut cx, |workspace, cx| {
 4982                    workspace::tasks::schedule_resolved_task(
 4983                        workspace,
 4984                        task_source_kind,
 4985                        resolved_task,
 4986                        false,
 4987                        cx,
 4988                    );
 4989                })
 4990                .ok()
 4991        })
 4992        .detach();
 4993    }
 4994
 4995    fn find_closest_task(
 4996        &mut self,
 4997        cx: &mut ViewContext<Self>,
 4998    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 4999        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5000
 5001        let ((buffer_id, row), tasks) = self
 5002            .tasks
 5003            .iter()
 5004            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5005
 5006        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5007        let tasks = Arc::new(tasks.to_owned());
 5008        Some((buffer, *row, tasks))
 5009    }
 5010
 5011    fn find_enclosing_node_task(
 5012        &mut self,
 5013        cx: &mut ViewContext<Self>,
 5014    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5015        let snapshot = self.buffer.read(cx).snapshot(cx);
 5016        let offset = self.selections.newest::<usize>(cx).head();
 5017        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5018        let buffer_id = excerpt.buffer().remote_id();
 5019
 5020        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5021        let mut cursor = layer.node().walk();
 5022
 5023        while cursor.goto_first_child_for_byte(offset).is_some() {
 5024            if cursor.node().end_byte() == offset {
 5025                cursor.goto_next_sibling();
 5026            }
 5027        }
 5028
 5029        // Ascend to the smallest ancestor that contains the range and has a task.
 5030        loop {
 5031            let node = cursor.node();
 5032            let node_range = node.byte_range();
 5033            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5034
 5035            // Check if this node contains our offset
 5036            if node_range.start <= offset && node_range.end >= offset {
 5037                // If it contains offset, check for task
 5038                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5039                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5040                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5041                }
 5042            }
 5043
 5044            if !cursor.goto_parent() {
 5045                break;
 5046            }
 5047        }
 5048        None
 5049    }
 5050
 5051    fn render_run_indicator(
 5052        &self,
 5053        _style: &EditorStyle,
 5054        is_active: bool,
 5055        row: DisplayRow,
 5056        cx: &mut ViewContext<Self>,
 5057    ) -> IconButton {
 5058        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5059            .shape(ui::IconButtonShape::Square)
 5060            .icon_size(IconSize::XSmall)
 5061            .icon_color(Color::Muted)
 5062            .toggle_state(is_active)
 5063            .on_click(cx.listener(move |editor, _e, cx| {
 5064                editor.focus(cx);
 5065                editor.toggle_code_actions(
 5066                    &ToggleCodeActions {
 5067                        deployed_from_indicator: Some(row),
 5068                    },
 5069                    cx,
 5070                );
 5071            }))
 5072    }
 5073
 5074    #[cfg(feature = "test-support")]
 5075    pub fn context_menu_visible(&self) -> bool {
 5076        self.context_menu
 5077            .borrow()
 5078            .as_ref()
 5079            .map_or(false, |menu| menu.visible())
 5080    }
 5081
 5082    #[cfg(feature = "test-support")]
 5083    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5084        self.context_menu
 5085            .borrow()
 5086            .as_ref()
 5087            .map_or(false, |menu| match menu {
 5088                CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
 5089                    matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5090                }),
 5091                CodeContextMenu::CodeActions(_) => false,
 5092            })
 5093    }
 5094
 5095    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5096        self.context_menu
 5097            .borrow()
 5098            .as_ref()
 5099            .map(|menu| menu.origin(cursor_position))
 5100    }
 5101
 5102    fn render_context_menu(
 5103        &self,
 5104        style: &EditorStyle,
 5105        max_height_in_lines: u32,
 5106        cx: &mut ViewContext<Editor>,
 5107    ) -> Option<AnyElement> {
 5108        self.context_menu.borrow().as_ref().and_then(|menu| {
 5109            if menu.visible() {
 5110                Some(menu.render(style, max_height_in_lines, cx))
 5111            } else {
 5112                None
 5113            }
 5114        })
 5115    }
 5116
 5117    fn render_context_menu_aside(
 5118        &self,
 5119        style: &EditorStyle,
 5120        max_height: Pixels,
 5121        cx: &mut ViewContext<Editor>,
 5122    ) -> Option<AnyElement> {
 5123        self.context_menu.borrow().as_ref().and_then(|menu| {
 5124            if menu.visible() {
 5125                menu.render_aside(
 5126                    style,
 5127                    max_height,
 5128                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5129                    cx,
 5130                )
 5131            } else {
 5132                None
 5133            }
 5134        })
 5135    }
 5136
 5137    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5138        cx.notify();
 5139        self.completion_tasks.clear();
 5140        self.context_menu.borrow_mut().take()
 5141    }
 5142
 5143    fn show_snippet_choices(
 5144        &mut self,
 5145        choices: &Vec<String>,
 5146        selection: Range<Anchor>,
 5147        cx: &mut ViewContext<Self>,
 5148    ) {
 5149        if selection.start.buffer_id.is_none() {
 5150            return;
 5151        }
 5152        let buffer_id = selection.start.buffer_id.unwrap();
 5153        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5154        let id = post_inc(&mut self.next_completion_id);
 5155
 5156        if let Some(buffer) = buffer {
 5157            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5158                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5159            ));
 5160        }
 5161    }
 5162
 5163    pub fn insert_snippet(
 5164        &mut self,
 5165        insertion_ranges: &[Range<usize>],
 5166        snippet: Snippet,
 5167        cx: &mut ViewContext<Self>,
 5168    ) -> Result<()> {
 5169        struct Tabstop<T> {
 5170            is_end_tabstop: bool,
 5171            ranges: Vec<Range<T>>,
 5172            choices: Option<Vec<String>>,
 5173        }
 5174
 5175        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5176            let snippet_text: Arc<str> = snippet.text.clone().into();
 5177            buffer.edit(
 5178                insertion_ranges
 5179                    .iter()
 5180                    .cloned()
 5181                    .map(|range| (range, snippet_text.clone())),
 5182                Some(AutoindentMode::EachLine),
 5183                cx,
 5184            );
 5185
 5186            let snapshot = &*buffer.read(cx);
 5187            let snippet = &snippet;
 5188            snippet
 5189                .tabstops
 5190                .iter()
 5191                .map(|tabstop| {
 5192                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5193                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5194                    });
 5195                    let mut tabstop_ranges = tabstop
 5196                        .ranges
 5197                        .iter()
 5198                        .flat_map(|tabstop_range| {
 5199                            let mut delta = 0_isize;
 5200                            insertion_ranges.iter().map(move |insertion_range| {
 5201                                let insertion_start = insertion_range.start as isize + delta;
 5202                                delta +=
 5203                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5204
 5205                                let start = ((insertion_start + tabstop_range.start) as usize)
 5206                                    .min(snapshot.len());
 5207                                let end = ((insertion_start + tabstop_range.end) as usize)
 5208                                    .min(snapshot.len());
 5209                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5210                            })
 5211                        })
 5212                        .collect::<Vec<_>>();
 5213                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5214
 5215                    Tabstop {
 5216                        is_end_tabstop,
 5217                        ranges: tabstop_ranges,
 5218                        choices: tabstop.choices.clone(),
 5219                    }
 5220                })
 5221                .collect::<Vec<_>>()
 5222        });
 5223        if let Some(tabstop) = tabstops.first() {
 5224            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5225                s.select_ranges(tabstop.ranges.iter().cloned());
 5226            });
 5227
 5228            if let Some(choices) = &tabstop.choices {
 5229                if let Some(selection) = tabstop.ranges.first() {
 5230                    self.show_snippet_choices(choices, selection.clone(), cx)
 5231                }
 5232            }
 5233
 5234            // If we're already at the last tabstop and it's at the end of the snippet,
 5235            // we're done, we don't need to keep the state around.
 5236            if !tabstop.is_end_tabstop {
 5237                let choices = tabstops
 5238                    .iter()
 5239                    .map(|tabstop| tabstop.choices.clone())
 5240                    .collect();
 5241
 5242                let ranges = tabstops
 5243                    .into_iter()
 5244                    .map(|tabstop| tabstop.ranges)
 5245                    .collect::<Vec<_>>();
 5246
 5247                self.snippet_stack.push(SnippetState {
 5248                    active_index: 0,
 5249                    ranges,
 5250                    choices,
 5251                });
 5252            }
 5253
 5254            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5255            if self.autoclose_regions.is_empty() {
 5256                let snapshot = self.buffer.read(cx).snapshot(cx);
 5257                for selection in &mut self.selections.all::<Point>(cx) {
 5258                    let selection_head = selection.head();
 5259                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5260                        continue;
 5261                    };
 5262
 5263                    let mut bracket_pair = None;
 5264                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5265                    let prev_chars = snapshot
 5266                        .reversed_chars_at(selection_head)
 5267                        .collect::<String>();
 5268                    for (pair, enabled) in scope.brackets() {
 5269                        if enabled
 5270                            && pair.close
 5271                            && prev_chars.starts_with(pair.start.as_str())
 5272                            && next_chars.starts_with(pair.end.as_str())
 5273                        {
 5274                            bracket_pair = Some(pair.clone());
 5275                            break;
 5276                        }
 5277                    }
 5278                    if let Some(pair) = bracket_pair {
 5279                        let start = snapshot.anchor_after(selection_head);
 5280                        let end = snapshot.anchor_after(selection_head);
 5281                        self.autoclose_regions.push(AutocloseRegion {
 5282                            selection_id: selection.id,
 5283                            range: start..end,
 5284                            pair,
 5285                        });
 5286                    }
 5287                }
 5288            }
 5289        }
 5290        Ok(())
 5291    }
 5292
 5293    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5294        self.move_to_snippet_tabstop(Bias::Right, cx)
 5295    }
 5296
 5297    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5298        self.move_to_snippet_tabstop(Bias::Left, cx)
 5299    }
 5300
 5301    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5302        if let Some(mut snippet) = self.snippet_stack.pop() {
 5303            match bias {
 5304                Bias::Left => {
 5305                    if snippet.active_index > 0 {
 5306                        snippet.active_index -= 1;
 5307                    } else {
 5308                        self.snippet_stack.push(snippet);
 5309                        return false;
 5310                    }
 5311                }
 5312                Bias::Right => {
 5313                    if snippet.active_index + 1 < snippet.ranges.len() {
 5314                        snippet.active_index += 1;
 5315                    } else {
 5316                        self.snippet_stack.push(snippet);
 5317                        return false;
 5318                    }
 5319                }
 5320            }
 5321            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5322                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5323                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5324                });
 5325
 5326                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5327                    if let Some(selection) = current_ranges.first() {
 5328                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5329                    }
 5330                }
 5331
 5332                // If snippet state is not at the last tabstop, push it back on the stack
 5333                if snippet.active_index + 1 < snippet.ranges.len() {
 5334                    self.snippet_stack.push(snippet);
 5335                }
 5336                return true;
 5337            }
 5338        }
 5339
 5340        false
 5341    }
 5342
 5343    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5344        self.transact(cx, |this, cx| {
 5345            this.select_all(&SelectAll, cx);
 5346            this.insert("", cx);
 5347        });
 5348    }
 5349
 5350    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5351        self.transact(cx, |this, cx| {
 5352            this.select_autoclose_pair(cx);
 5353            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5354            if !this.linked_edit_ranges.is_empty() {
 5355                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5356                let snapshot = this.buffer.read(cx).snapshot(cx);
 5357
 5358                for selection in selections.iter() {
 5359                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5360                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5361                    if selection_start.buffer_id != selection_end.buffer_id {
 5362                        continue;
 5363                    }
 5364                    if let Some(ranges) =
 5365                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5366                    {
 5367                        for (buffer, entries) in ranges {
 5368                            linked_ranges.entry(buffer).or_default().extend(entries);
 5369                        }
 5370                    }
 5371                }
 5372            }
 5373
 5374            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5375            if !this.selections.line_mode {
 5376                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5377                for selection in &mut selections {
 5378                    if selection.is_empty() {
 5379                        let old_head = selection.head();
 5380                        let mut new_head =
 5381                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5382                                .to_point(&display_map);
 5383                        if let Some((buffer, line_buffer_range)) = display_map
 5384                            .buffer_snapshot
 5385                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5386                        {
 5387                            let indent_size =
 5388                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5389                            let indent_len = match indent_size.kind {
 5390                                IndentKind::Space => {
 5391                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5392                                }
 5393                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5394                            };
 5395                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5396                                let indent_len = indent_len.get();
 5397                                new_head = cmp::min(
 5398                                    new_head,
 5399                                    MultiBufferPoint::new(
 5400                                        old_head.row,
 5401                                        ((old_head.column - 1) / indent_len) * indent_len,
 5402                                    ),
 5403                                );
 5404                            }
 5405                        }
 5406
 5407                        selection.set_head(new_head, SelectionGoal::None);
 5408                    }
 5409                }
 5410            }
 5411
 5412            this.signature_help_state.set_backspace_pressed(true);
 5413            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5414            this.insert("", cx);
 5415            let empty_str: Arc<str> = Arc::from("");
 5416            for (buffer, edits) in linked_ranges {
 5417                let snapshot = buffer.read(cx).snapshot();
 5418                use text::ToPoint as TP;
 5419
 5420                let edits = edits
 5421                    .into_iter()
 5422                    .map(|range| {
 5423                        let end_point = TP::to_point(&range.end, &snapshot);
 5424                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5425
 5426                        if end_point == start_point {
 5427                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5428                                .saturating_sub(1);
 5429                            start_point =
 5430                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5431                        };
 5432
 5433                        (start_point..end_point, empty_str.clone())
 5434                    })
 5435                    .sorted_by_key(|(range, _)| range.start)
 5436                    .collect::<Vec<_>>();
 5437                buffer.update(cx, |this, cx| {
 5438                    this.edit(edits, None, cx);
 5439                })
 5440            }
 5441            this.refresh_inline_completion(true, false, cx);
 5442            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5443        });
 5444    }
 5445
 5446    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5447        self.transact(cx, |this, cx| {
 5448            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5449                let line_mode = s.line_mode;
 5450                s.move_with(|map, selection| {
 5451                    if selection.is_empty() && !line_mode {
 5452                        let cursor = movement::right(map, selection.head());
 5453                        selection.end = cursor;
 5454                        selection.reversed = true;
 5455                        selection.goal = SelectionGoal::None;
 5456                    }
 5457                })
 5458            });
 5459            this.insert("", cx);
 5460            this.refresh_inline_completion(true, false, cx);
 5461        });
 5462    }
 5463
 5464    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5465        if self.move_to_prev_snippet_tabstop(cx) {
 5466            return;
 5467        }
 5468
 5469        self.outdent(&Outdent, cx);
 5470    }
 5471
 5472    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5473        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5474            return;
 5475        }
 5476
 5477        let mut selections = self.selections.all_adjusted(cx);
 5478        let buffer = self.buffer.read(cx);
 5479        let snapshot = buffer.snapshot(cx);
 5480        let rows_iter = selections.iter().map(|s| s.head().row);
 5481        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5482
 5483        let mut edits = Vec::new();
 5484        let mut prev_edited_row = 0;
 5485        let mut row_delta = 0;
 5486        for selection in &mut selections {
 5487            if selection.start.row != prev_edited_row {
 5488                row_delta = 0;
 5489            }
 5490            prev_edited_row = selection.end.row;
 5491
 5492            // If the selection is non-empty, then increase the indentation of the selected lines.
 5493            if !selection.is_empty() {
 5494                row_delta =
 5495                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5496                continue;
 5497            }
 5498
 5499            // If the selection is empty and the cursor is in the leading whitespace before the
 5500            // suggested indentation, then auto-indent the line.
 5501            let cursor = selection.head();
 5502            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5503            if let Some(suggested_indent) =
 5504                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5505            {
 5506                if cursor.column < suggested_indent.len
 5507                    && cursor.column <= current_indent.len
 5508                    && current_indent.len <= suggested_indent.len
 5509                {
 5510                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5511                    selection.end = selection.start;
 5512                    if row_delta == 0 {
 5513                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5514                            cursor.row,
 5515                            current_indent,
 5516                            suggested_indent,
 5517                        ));
 5518                        row_delta = suggested_indent.len - current_indent.len;
 5519                    }
 5520                    continue;
 5521                }
 5522            }
 5523
 5524            // Otherwise, insert a hard or soft tab.
 5525            let settings = buffer.settings_at(cursor, cx);
 5526            let tab_size = if settings.hard_tabs {
 5527                IndentSize::tab()
 5528            } else {
 5529                let tab_size = settings.tab_size.get();
 5530                let char_column = snapshot
 5531                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5532                    .flat_map(str::chars)
 5533                    .count()
 5534                    + row_delta as usize;
 5535                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5536                IndentSize::spaces(chars_to_next_tab_stop)
 5537            };
 5538            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5539            selection.end = selection.start;
 5540            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5541            row_delta += tab_size.len;
 5542        }
 5543
 5544        self.transact(cx, |this, cx| {
 5545            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5546            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5547            this.refresh_inline_completion(true, false, cx);
 5548        });
 5549    }
 5550
 5551    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5552        if self.read_only(cx) {
 5553            return;
 5554        }
 5555        let mut selections = self.selections.all::<Point>(cx);
 5556        let mut prev_edited_row = 0;
 5557        let mut row_delta = 0;
 5558        let mut edits = Vec::new();
 5559        let buffer = self.buffer.read(cx);
 5560        let snapshot = buffer.snapshot(cx);
 5561        for selection in &mut selections {
 5562            if selection.start.row != prev_edited_row {
 5563                row_delta = 0;
 5564            }
 5565            prev_edited_row = selection.end.row;
 5566
 5567            row_delta =
 5568                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5569        }
 5570
 5571        self.transact(cx, |this, cx| {
 5572            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5573            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5574        });
 5575    }
 5576
 5577    fn indent_selection(
 5578        buffer: &MultiBuffer,
 5579        snapshot: &MultiBufferSnapshot,
 5580        selection: &mut Selection<Point>,
 5581        edits: &mut Vec<(Range<Point>, String)>,
 5582        delta_for_start_row: u32,
 5583        cx: &AppContext,
 5584    ) -> u32 {
 5585        let settings = buffer.settings_at(selection.start, cx);
 5586        let tab_size = settings.tab_size.get();
 5587        let indent_kind = if settings.hard_tabs {
 5588            IndentKind::Tab
 5589        } else {
 5590            IndentKind::Space
 5591        };
 5592        let mut start_row = selection.start.row;
 5593        let mut end_row = selection.end.row + 1;
 5594
 5595        // If a selection ends at the beginning of a line, don't indent
 5596        // that last line.
 5597        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5598            end_row -= 1;
 5599        }
 5600
 5601        // Avoid re-indenting a row that has already been indented by a
 5602        // previous selection, but still update this selection's column
 5603        // to reflect that indentation.
 5604        if delta_for_start_row > 0 {
 5605            start_row += 1;
 5606            selection.start.column += delta_for_start_row;
 5607            if selection.end.row == selection.start.row {
 5608                selection.end.column += delta_for_start_row;
 5609            }
 5610        }
 5611
 5612        let mut delta_for_end_row = 0;
 5613        let has_multiple_rows = start_row + 1 != end_row;
 5614        for row in start_row..end_row {
 5615            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5616            let indent_delta = match (current_indent.kind, indent_kind) {
 5617                (IndentKind::Space, IndentKind::Space) => {
 5618                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5619                    IndentSize::spaces(columns_to_next_tab_stop)
 5620                }
 5621                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5622                (_, IndentKind::Tab) => IndentSize::tab(),
 5623            };
 5624
 5625            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5626                0
 5627            } else {
 5628                selection.start.column
 5629            };
 5630            let row_start = Point::new(row, start);
 5631            edits.push((
 5632                row_start..row_start,
 5633                indent_delta.chars().collect::<String>(),
 5634            ));
 5635
 5636            // Update this selection's endpoints to reflect the indentation.
 5637            if row == selection.start.row {
 5638                selection.start.column += indent_delta.len;
 5639            }
 5640            if row == selection.end.row {
 5641                selection.end.column += indent_delta.len;
 5642                delta_for_end_row = indent_delta.len;
 5643            }
 5644        }
 5645
 5646        if selection.start.row == selection.end.row {
 5647            delta_for_start_row + delta_for_end_row
 5648        } else {
 5649            delta_for_end_row
 5650        }
 5651    }
 5652
 5653    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5654        if self.read_only(cx) {
 5655            return;
 5656        }
 5657        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5658        let selections = self.selections.all::<Point>(cx);
 5659        let mut deletion_ranges = Vec::new();
 5660        let mut last_outdent = None;
 5661        {
 5662            let buffer = self.buffer.read(cx);
 5663            let snapshot = buffer.snapshot(cx);
 5664            for selection in &selections {
 5665                let settings = buffer.settings_at(selection.start, cx);
 5666                let tab_size = settings.tab_size.get();
 5667                let mut rows = selection.spanned_rows(false, &display_map);
 5668
 5669                // Avoid re-outdenting a row that has already been outdented by a
 5670                // previous selection.
 5671                if let Some(last_row) = last_outdent {
 5672                    if last_row == rows.start {
 5673                        rows.start = rows.start.next_row();
 5674                    }
 5675                }
 5676                let has_multiple_rows = rows.len() > 1;
 5677                for row in rows.iter_rows() {
 5678                    let indent_size = snapshot.indent_size_for_line(row);
 5679                    if indent_size.len > 0 {
 5680                        let deletion_len = match indent_size.kind {
 5681                            IndentKind::Space => {
 5682                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5683                                if columns_to_prev_tab_stop == 0 {
 5684                                    tab_size
 5685                                } else {
 5686                                    columns_to_prev_tab_stop
 5687                                }
 5688                            }
 5689                            IndentKind::Tab => 1,
 5690                        };
 5691                        let start = if has_multiple_rows
 5692                            || deletion_len > selection.start.column
 5693                            || indent_size.len < selection.start.column
 5694                        {
 5695                            0
 5696                        } else {
 5697                            selection.start.column - deletion_len
 5698                        };
 5699                        deletion_ranges.push(
 5700                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5701                        );
 5702                        last_outdent = Some(row);
 5703                    }
 5704                }
 5705            }
 5706        }
 5707
 5708        self.transact(cx, |this, cx| {
 5709            this.buffer.update(cx, |buffer, cx| {
 5710                let empty_str: Arc<str> = Arc::default();
 5711                buffer.edit(
 5712                    deletion_ranges
 5713                        .into_iter()
 5714                        .map(|range| (range, empty_str.clone())),
 5715                    None,
 5716                    cx,
 5717                );
 5718            });
 5719            let selections = this.selections.all::<usize>(cx);
 5720            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5721        });
 5722    }
 5723
 5724    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5725        if self.read_only(cx) {
 5726            return;
 5727        }
 5728        let selections = self
 5729            .selections
 5730            .all::<usize>(cx)
 5731            .into_iter()
 5732            .map(|s| s.range());
 5733
 5734        self.transact(cx, |this, cx| {
 5735            this.buffer.update(cx, |buffer, cx| {
 5736                buffer.autoindent_ranges(selections, cx);
 5737            });
 5738            let selections = this.selections.all::<usize>(cx);
 5739            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5740        });
 5741    }
 5742
 5743    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5744        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5745        let selections = self.selections.all::<Point>(cx);
 5746
 5747        let mut new_cursors = Vec::new();
 5748        let mut edit_ranges = Vec::new();
 5749        let mut selections = selections.iter().peekable();
 5750        while let Some(selection) = selections.next() {
 5751            let mut rows = selection.spanned_rows(false, &display_map);
 5752            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5753
 5754            // Accumulate contiguous regions of rows that we want to delete.
 5755            while let Some(next_selection) = selections.peek() {
 5756                let next_rows = next_selection.spanned_rows(false, &display_map);
 5757                if next_rows.start <= rows.end {
 5758                    rows.end = next_rows.end;
 5759                    selections.next().unwrap();
 5760                } else {
 5761                    break;
 5762                }
 5763            }
 5764
 5765            let buffer = &display_map.buffer_snapshot;
 5766            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5767            let edit_end;
 5768            let cursor_buffer_row;
 5769            if buffer.max_point().row >= rows.end.0 {
 5770                // If there's a line after the range, delete the \n from the end of the row range
 5771                // and position the cursor on the next line.
 5772                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5773                cursor_buffer_row = rows.end;
 5774            } else {
 5775                // If there isn't a line after the range, delete the \n from the line before the
 5776                // start of the row range and position the cursor there.
 5777                edit_start = edit_start.saturating_sub(1);
 5778                edit_end = buffer.len();
 5779                cursor_buffer_row = rows.start.previous_row();
 5780            }
 5781
 5782            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5783            *cursor.column_mut() =
 5784                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5785
 5786            new_cursors.push((
 5787                selection.id,
 5788                buffer.anchor_after(cursor.to_point(&display_map)),
 5789            ));
 5790            edit_ranges.push(edit_start..edit_end);
 5791        }
 5792
 5793        self.transact(cx, |this, cx| {
 5794            let buffer = this.buffer.update(cx, |buffer, cx| {
 5795                let empty_str: Arc<str> = Arc::default();
 5796                buffer.edit(
 5797                    edit_ranges
 5798                        .into_iter()
 5799                        .map(|range| (range, empty_str.clone())),
 5800                    None,
 5801                    cx,
 5802                );
 5803                buffer.snapshot(cx)
 5804            });
 5805            let new_selections = new_cursors
 5806                .into_iter()
 5807                .map(|(id, cursor)| {
 5808                    let cursor = cursor.to_point(&buffer);
 5809                    Selection {
 5810                        id,
 5811                        start: cursor,
 5812                        end: cursor,
 5813                        reversed: false,
 5814                        goal: SelectionGoal::None,
 5815                    }
 5816                })
 5817                .collect();
 5818
 5819            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5820                s.select(new_selections);
 5821            });
 5822        });
 5823    }
 5824
 5825    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5826        if self.read_only(cx) {
 5827            return;
 5828        }
 5829        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5830        for selection in self.selections.all::<Point>(cx) {
 5831            let start = MultiBufferRow(selection.start.row);
 5832            // Treat single line selections as if they include the next line. Otherwise this action
 5833            // would do nothing for single line selections individual cursors.
 5834            let end = if selection.start.row == selection.end.row {
 5835                MultiBufferRow(selection.start.row + 1)
 5836            } else {
 5837                MultiBufferRow(selection.end.row)
 5838            };
 5839
 5840            if let Some(last_row_range) = row_ranges.last_mut() {
 5841                if start <= last_row_range.end {
 5842                    last_row_range.end = end;
 5843                    continue;
 5844                }
 5845            }
 5846            row_ranges.push(start..end);
 5847        }
 5848
 5849        let snapshot = self.buffer.read(cx).snapshot(cx);
 5850        let mut cursor_positions = Vec::new();
 5851        for row_range in &row_ranges {
 5852            let anchor = snapshot.anchor_before(Point::new(
 5853                row_range.end.previous_row().0,
 5854                snapshot.line_len(row_range.end.previous_row()),
 5855            ));
 5856            cursor_positions.push(anchor..anchor);
 5857        }
 5858
 5859        self.transact(cx, |this, cx| {
 5860            for row_range in row_ranges.into_iter().rev() {
 5861                for row in row_range.iter_rows().rev() {
 5862                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5863                    let next_line_row = row.next_row();
 5864                    let indent = snapshot.indent_size_for_line(next_line_row);
 5865                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5866
 5867                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5868                        " "
 5869                    } else {
 5870                        ""
 5871                    };
 5872
 5873                    this.buffer.update(cx, |buffer, cx| {
 5874                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5875                    });
 5876                }
 5877            }
 5878
 5879            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5880                s.select_anchor_ranges(cursor_positions)
 5881            });
 5882        });
 5883    }
 5884
 5885    pub fn sort_lines_case_sensitive(
 5886        &mut self,
 5887        _: &SortLinesCaseSensitive,
 5888        cx: &mut ViewContext<Self>,
 5889    ) {
 5890        self.manipulate_lines(cx, |lines| lines.sort())
 5891    }
 5892
 5893    pub fn sort_lines_case_insensitive(
 5894        &mut self,
 5895        _: &SortLinesCaseInsensitive,
 5896        cx: &mut ViewContext<Self>,
 5897    ) {
 5898        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5899    }
 5900
 5901    pub fn unique_lines_case_insensitive(
 5902        &mut self,
 5903        _: &UniqueLinesCaseInsensitive,
 5904        cx: &mut ViewContext<Self>,
 5905    ) {
 5906        self.manipulate_lines(cx, |lines| {
 5907            let mut seen = HashSet::default();
 5908            lines.retain(|line| seen.insert(line.to_lowercase()));
 5909        })
 5910    }
 5911
 5912    pub fn unique_lines_case_sensitive(
 5913        &mut self,
 5914        _: &UniqueLinesCaseSensitive,
 5915        cx: &mut ViewContext<Self>,
 5916    ) {
 5917        self.manipulate_lines(cx, |lines| {
 5918            let mut seen = HashSet::default();
 5919            lines.retain(|line| seen.insert(*line));
 5920        })
 5921    }
 5922
 5923    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5924        let mut revert_changes = HashMap::default();
 5925        let snapshot = self.snapshot(cx);
 5926        for hunk in hunks_for_ranges(
 5927            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5928            &snapshot,
 5929        ) {
 5930            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5931        }
 5932        if !revert_changes.is_empty() {
 5933            self.transact(cx, |editor, cx| {
 5934                editor.revert(revert_changes, cx);
 5935            });
 5936        }
 5937    }
 5938
 5939    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5940        let Some(project) = self.project.clone() else {
 5941            return;
 5942        };
 5943        self.reload(project, cx).detach_and_notify_err(cx);
 5944    }
 5945
 5946    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5947        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5948        if !revert_changes.is_empty() {
 5949            self.transact(cx, |editor, cx| {
 5950                editor.revert(revert_changes, cx);
 5951            });
 5952        }
 5953    }
 5954
 5955    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5956        let snapshot = self.buffer.read(cx).read(cx);
 5957        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5958            drop(snapshot);
 5959            let mut revert_changes = HashMap::default();
 5960            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5961            if !revert_changes.is_empty() {
 5962                self.revert(revert_changes, cx)
 5963            }
 5964        }
 5965    }
 5966
 5967    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5968        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5969            let project_path = buffer.read(cx).project_path(cx)?;
 5970            let project = self.project.as_ref()?.read(cx);
 5971            let entry = project.entry_for_path(&project_path, cx)?;
 5972            let parent = match &entry.canonical_path {
 5973                Some(canonical_path) => canonical_path.to_path_buf(),
 5974                None => project.absolute_path(&project_path, cx)?,
 5975            }
 5976            .parent()?
 5977            .to_path_buf();
 5978            Some(parent)
 5979        }) {
 5980            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5981        }
 5982    }
 5983
 5984    fn gather_revert_changes(
 5985        &mut self,
 5986        selections: &[Selection<Point>],
 5987        cx: &mut ViewContext<'_, Editor>,
 5988    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5989        let mut revert_changes = HashMap::default();
 5990        let snapshot = self.snapshot(cx);
 5991        for hunk in hunks_for_selections(&snapshot, selections) {
 5992            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5993        }
 5994        revert_changes
 5995    }
 5996
 5997    pub fn prepare_revert_change(
 5998        &mut self,
 5999        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6000        hunk: &MultiBufferDiffHunk,
 6001        cx: &AppContext,
 6002    ) -> Option<()> {
 6003        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6004        let buffer = buffer.read(cx);
 6005        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6006        let original_text = change_set
 6007            .read(cx)
 6008            .base_text
 6009            .as_ref()?
 6010            .read(cx)
 6011            .as_rope()
 6012            .slice(hunk.diff_base_byte_range.clone());
 6013        let buffer_snapshot = buffer.snapshot();
 6014        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6015        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6016            probe
 6017                .0
 6018                .start
 6019                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6020                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6021        }) {
 6022            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6023            Some(())
 6024        } else {
 6025            None
 6026        }
 6027    }
 6028
 6029    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6030        self.manipulate_lines(cx, |lines| lines.reverse())
 6031    }
 6032
 6033    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6034        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6035    }
 6036
 6037    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6038    where
 6039        Fn: FnMut(&mut Vec<&str>),
 6040    {
 6041        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6042        let buffer = self.buffer.read(cx).snapshot(cx);
 6043
 6044        let mut edits = Vec::new();
 6045
 6046        let selections = self.selections.all::<Point>(cx);
 6047        let mut selections = selections.iter().peekable();
 6048        let mut contiguous_row_selections = Vec::new();
 6049        let mut new_selections = Vec::new();
 6050        let mut added_lines = 0;
 6051        let mut removed_lines = 0;
 6052
 6053        while let Some(selection) = selections.next() {
 6054            let (start_row, end_row) = consume_contiguous_rows(
 6055                &mut contiguous_row_selections,
 6056                selection,
 6057                &display_map,
 6058                &mut selections,
 6059            );
 6060
 6061            let start_point = Point::new(start_row.0, 0);
 6062            let end_point = Point::new(
 6063                end_row.previous_row().0,
 6064                buffer.line_len(end_row.previous_row()),
 6065            );
 6066            let text = buffer
 6067                .text_for_range(start_point..end_point)
 6068                .collect::<String>();
 6069
 6070            let mut lines = text.split('\n').collect_vec();
 6071
 6072            let lines_before = lines.len();
 6073            callback(&mut lines);
 6074            let lines_after = lines.len();
 6075
 6076            edits.push((start_point..end_point, lines.join("\n")));
 6077
 6078            // Selections must change based on added and removed line count
 6079            let start_row =
 6080                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6081            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6082            new_selections.push(Selection {
 6083                id: selection.id,
 6084                start: start_row,
 6085                end: end_row,
 6086                goal: SelectionGoal::None,
 6087                reversed: selection.reversed,
 6088            });
 6089
 6090            if lines_after > lines_before {
 6091                added_lines += lines_after - lines_before;
 6092            } else if lines_before > lines_after {
 6093                removed_lines += lines_before - lines_after;
 6094            }
 6095        }
 6096
 6097        self.transact(cx, |this, cx| {
 6098            let buffer = this.buffer.update(cx, |buffer, cx| {
 6099                buffer.edit(edits, None, cx);
 6100                buffer.snapshot(cx)
 6101            });
 6102
 6103            // Recalculate offsets on newly edited buffer
 6104            let new_selections = new_selections
 6105                .iter()
 6106                .map(|s| {
 6107                    let start_point = Point::new(s.start.0, 0);
 6108                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6109                    Selection {
 6110                        id: s.id,
 6111                        start: buffer.point_to_offset(start_point),
 6112                        end: buffer.point_to_offset(end_point),
 6113                        goal: s.goal,
 6114                        reversed: s.reversed,
 6115                    }
 6116                })
 6117                .collect();
 6118
 6119            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6120                s.select(new_selections);
 6121            });
 6122
 6123            this.request_autoscroll(Autoscroll::fit(), cx);
 6124        });
 6125    }
 6126
 6127    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6128        self.manipulate_text(cx, |text| text.to_uppercase())
 6129    }
 6130
 6131    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6132        self.manipulate_text(cx, |text| text.to_lowercase())
 6133    }
 6134
 6135    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6136        self.manipulate_text(cx, |text| {
 6137            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6138            // https://github.com/rutrum/convert-case/issues/16
 6139            text.split('\n')
 6140                .map(|line| line.to_case(Case::Title))
 6141                .join("\n")
 6142        })
 6143    }
 6144
 6145    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6146        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6147    }
 6148
 6149    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6150        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6151    }
 6152
 6153    pub fn convert_to_upper_camel_case(
 6154        &mut self,
 6155        _: &ConvertToUpperCamelCase,
 6156        cx: &mut ViewContext<Self>,
 6157    ) {
 6158        self.manipulate_text(cx, |text| {
 6159            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6160            // https://github.com/rutrum/convert-case/issues/16
 6161            text.split('\n')
 6162                .map(|line| line.to_case(Case::UpperCamel))
 6163                .join("\n")
 6164        })
 6165    }
 6166
 6167    pub fn convert_to_lower_camel_case(
 6168        &mut self,
 6169        _: &ConvertToLowerCamelCase,
 6170        cx: &mut ViewContext<Self>,
 6171    ) {
 6172        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6173    }
 6174
 6175    pub fn convert_to_opposite_case(
 6176        &mut self,
 6177        _: &ConvertToOppositeCase,
 6178        cx: &mut ViewContext<Self>,
 6179    ) {
 6180        self.manipulate_text(cx, |text| {
 6181            text.chars()
 6182                .fold(String::with_capacity(text.len()), |mut t, c| {
 6183                    if c.is_uppercase() {
 6184                        t.extend(c.to_lowercase());
 6185                    } else {
 6186                        t.extend(c.to_uppercase());
 6187                    }
 6188                    t
 6189                })
 6190        })
 6191    }
 6192
 6193    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6194    where
 6195        Fn: FnMut(&str) -> String,
 6196    {
 6197        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6198        let buffer = self.buffer.read(cx).snapshot(cx);
 6199
 6200        let mut new_selections = Vec::new();
 6201        let mut edits = Vec::new();
 6202        let mut selection_adjustment = 0i32;
 6203
 6204        for selection in self.selections.all::<usize>(cx) {
 6205            let selection_is_empty = selection.is_empty();
 6206
 6207            let (start, end) = if selection_is_empty {
 6208                let word_range = movement::surrounding_word(
 6209                    &display_map,
 6210                    selection.start.to_display_point(&display_map),
 6211                );
 6212                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6213                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6214                (start, end)
 6215            } else {
 6216                (selection.start, selection.end)
 6217            };
 6218
 6219            let text = buffer.text_for_range(start..end).collect::<String>();
 6220            let old_length = text.len() as i32;
 6221            let text = callback(&text);
 6222
 6223            new_selections.push(Selection {
 6224                start: (start as i32 - selection_adjustment) as usize,
 6225                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6226                goal: SelectionGoal::None,
 6227                ..selection
 6228            });
 6229
 6230            selection_adjustment += old_length - text.len() as i32;
 6231
 6232            edits.push((start..end, text));
 6233        }
 6234
 6235        self.transact(cx, |this, cx| {
 6236            this.buffer.update(cx, |buffer, cx| {
 6237                buffer.edit(edits, None, cx);
 6238            });
 6239
 6240            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6241                s.select(new_selections);
 6242            });
 6243
 6244            this.request_autoscroll(Autoscroll::fit(), cx);
 6245        });
 6246    }
 6247
 6248    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6249        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6250        let buffer = &display_map.buffer_snapshot;
 6251        let selections = self.selections.all::<Point>(cx);
 6252
 6253        let mut edits = Vec::new();
 6254        let mut selections_iter = selections.iter().peekable();
 6255        while let Some(selection) = selections_iter.next() {
 6256            let mut rows = selection.spanned_rows(false, &display_map);
 6257            // duplicate line-wise
 6258            if whole_lines || selection.start == selection.end {
 6259                // Avoid duplicating the same lines twice.
 6260                while let Some(next_selection) = selections_iter.peek() {
 6261                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6262                    if next_rows.start < rows.end {
 6263                        rows.end = next_rows.end;
 6264                        selections_iter.next().unwrap();
 6265                    } else {
 6266                        break;
 6267                    }
 6268                }
 6269
 6270                // Copy the text from the selected row region and splice it either at the start
 6271                // or end of the region.
 6272                let start = Point::new(rows.start.0, 0);
 6273                let end = Point::new(
 6274                    rows.end.previous_row().0,
 6275                    buffer.line_len(rows.end.previous_row()),
 6276                );
 6277                let text = buffer
 6278                    .text_for_range(start..end)
 6279                    .chain(Some("\n"))
 6280                    .collect::<String>();
 6281                let insert_location = if upwards {
 6282                    Point::new(rows.end.0, 0)
 6283                } else {
 6284                    start
 6285                };
 6286                edits.push((insert_location..insert_location, text));
 6287            } else {
 6288                // duplicate character-wise
 6289                let start = selection.start;
 6290                let end = selection.end;
 6291                let text = buffer.text_for_range(start..end).collect::<String>();
 6292                edits.push((selection.end..selection.end, text));
 6293            }
 6294        }
 6295
 6296        self.transact(cx, |this, cx| {
 6297            this.buffer.update(cx, |buffer, cx| {
 6298                buffer.edit(edits, None, cx);
 6299            });
 6300
 6301            this.request_autoscroll(Autoscroll::fit(), cx);
 6302        });
 6303    }
 6304
 6305    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6306        self.duplicate(true, true, cx);
 6307    }
 6308
 6309    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6310        self.duplicate(false, true, cx);
 6311    }
 6312
 6313    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6314        self.duplicate(false, false, cx);
 6315    }
 6316
 6317    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6318        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6319        let buffer = self.buffer.read(cx).snapshot(cx);
 6320
 6321        let mut edits = Vec::new();
 6322        let mut unfold_ranges = Vec::new();
 6323        let mut refold_creases = Vec::new();
 6324
 6325        let selections = self.selections.all::<Point>(cx);
 6326        let mut selections = selections.iter().peekable();
 6327        let mut contiguous_row_selections = Vec::new();
 6328        let mut new_selections = Vec::new();
 6329
 6330        while let Some(selection) = selections.next() {
 6331            // Find all the selections that span a contiguous row range
 6332            let (start_row, end_row) = consume_contiguous_rows(
 6333                &mut contiguous_row_selections,
 6334                selection,
 6335                &display_map,
 6336                &mut selections,
 6337            );
 6338
 6339            // Move the text spanned by the row range to be before the line preceding the row range
 6340            if start_row.0 > 0 {
 6341                let range_to_move = Point::new(
 6342                    start_row.previous_row().0,
 6343                    buffer.line_len(start_row.previous_row()),
 6344                )
 6345                    ..Point::new(
 6346                        end_row.previous_row().0,
 6347                        buffer.line_len(end_row.previous_row()),
 6348                    );
 6349                let insertion_point = display_map
 6350                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6351                    .0;
 6352
 6353                // Don't move lines across excerpts
 6354                if buffer
 6355                    .excerpt_boundaries_in_range((
 6356                        Bound::Excluded(insertion_point),
 6357                        Bound::Included(range_to_move.end),
 6358                    ))
 6359                    .next()
 6360                    .is_none()
 6361                {
 6362                    let text = buffer
 6363                        .text_for_range(range_to_move.clone())
 6364                        .flat_map(|s| s.chars())
 6365                        .skip(1)
 6366                        .chain(['\n'])
 6367                        .collect::<String>();
 6368
 6369                    edits.push((
 6370                        buffer.anchor_after(range_to_move.start)
 6371                            ..buffer.anchor_before(range_to_move.end),
 6372                        String::new(),
 6373                    ));
 6374                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6375                    edits.push((insertion_anchor..insertion_anchor, text));
 6376
 6377                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6378
 6379                    // Move selections up
 6380                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6381                        |mut selection| {
 6382                            selection.start.row -= row_delta;
 6383                            selection.end.row -= row_delta;
 6384                            selection
 6385                        },
 6386                    ));
 6387
 6388                    // Move folds up
 6389                    unfold_ranges.push(range_to_move.clone());
 6390                    for fold in display_map.folds_in_range(
 6391                        buffer.anchor_before(range_to_move.start)
 6392                            ..buffer.anchor_after(range_to_move.end),
 6393                    ) {
 6394                        let mut start = fold.range.start.to_point(&buffer);
 6395                        let mut end = fold.range.end.to_point(&buffer);
 6396                        start.row -= row_delta;
 6397                        end.row -= row_delta;
 6398                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6399                    }
 6400                }
 6401            }
 6402
 6403            // If we didn't move line(s), preserve the existing selections
 6404            new_selections.append(&mut contiguous_row_selections);
 6405        }
 6406
 6407        self.transact(cx, |this, cx| {
 6408            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6409            this.buffer.update(cx, |buffer, cx| {
 6410                for (range, text) in edits {
 6411                    buffer.edit([(range, text)], None, cx);
 6412                }
 6413            });
 6414            this.fold_creases(refold_creases, true, cx);
 6415            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6416                s.select(new_selections);
 6417            })
 6418        });
 6419    }
 6420
 6421    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6422        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6423        let buffer = self.buffer.read(cx).snapshot(cx);
 6424
 6425        let mut edits = Vec::new();
 6426        let mut unfold_ranges = Vec::new();
 6427        let mut refold_creases = Vec::new();
 6428
 6429        let selections = self.selections.all::<Point>(cx);
 6430        let mut selections = selections.iter().peekable();
 6431        let mut contiguous_row_selections = Vec::new();
 6432        let mut new_selections = Vec::new();
 6433
 6434        while let Some(selection) = selections.next() {
 6435            // Find all the selections that span a contiguous row range
 6436            let (start_row, end_row) = consume_contiguous_rows(
 6437                &mut contiguous_row_selections,
 6438                selection,
 6439                &display_map,
 6440                &mut selections,
 6441            );
 6442
 6443            // Move the text spanned by the row range to be after the last line of the row range
 6444            if end_row.0 <= buffer.max_point().row {
 6445                let range_to_move =
 6446                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6447                let insertion_point = display_map
 6448                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6449                    .0;
 6450
 6451                // Don't move lines across excerpt boundaries
 6452                if buffer
 6453                    .excerpt_boundaries_in_range((
 6454                        Bound::Excluded(range_to_move.start),
 6455                        Bound::Included(insertion_point),
 6456                    ))
 6457                    .next()
 6458                    .is_none()
 6459                {
 6460                    let mut text = String::from("\n");
 6461                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6462                    text.pop(); // Drop trailing newline
 6463                    edits.push((
 6464                        buffer.anchor_after(range_to_move.start)
 6465                            ..buffer.anchor_before(range_to_move.end),
 6466                        String::new(),
 6467                    ));
 6468                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6469                    edits.push((insertion_anchor..insertion_anchor, text));
 6470
 6471                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6472
 6473                    // Move selections down
 6474                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6475                        |mut selection| {
 6476                            selection.start.row += row_delta;
 6477                            selection.end.row += row_delta;
 6478                            selection
 6479                        },
 6480                    ));
 6481
 6482                    // Move folds down
 6483                    unfold_ranges.push(range_to_move.clone());
 6484                    for fold in display_map.folds_in_range(
 6485                        buffer.anchor_before(range_to_move.start)
 6486                            ..buffer.anchor_after(range_to_move.end),
 6487                    ) {
 6488                        let mut start = fold.range.start.to_point(&buffer);
 6489                        let mut end = fold.range.end.to_point(&buffer);
 6490                        start.row += row_delta;
 6491                        end.row += row_delta;
 6492                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6493                    }
 6494                }
 6495            }
 6496
 6497            // If we didn't move line(s), preserve the existing selections
 6498            new_selections.append(&mut contiguous_row_selections);
 6499        }
 6500
 6501        self.transact(cx, |this, cx| {
 6502            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6503            this.buffer.update(cx, |buffer, cx| {
 6504                for (range, text) in edits {
 6505                    buffer.edit([(range, text)], None, cx);
 6506                }
 6507            });
 6508            this.fold_creases(refold_creases, true, cx);
 6509            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6510        });
 6511    }
 6512
 6513    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6514        let text_layout_details = &self.text_layout_details(cx);
 6515        self.transact(cx, |this, cx| {
 6516            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6517                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6518                let line_mode = s.line_mode;
 6519                s.move_with(|display_map, selection| {
 6520                    if !selection.is_empty() || line_mode {
 6521                        return;
 6522                    }
 6523
 6524                    let mut head = selection.head();
 6525                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6526                    if head.column() == display_map.line_len(head.row()) {
 6527                        transpose_offset = display_map
 6528                            .buffer_snapshot
 6529                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6530                    }
 6531
 6532                    if transpose_offset == 0 {
 6533                        return;
 6534                    }
 6535
 6536                    *head.column_mut() += 1;
 6537                    head = display_map.clip_point(head, Bias::Right);
 6538                    let goal = SelectionGoal::HorizontalPosition(
 6539                        display_map
 6540                            .x_for_display_point(head, text_layout_details)
 6541                            .into(),
 6542                    );
 6543                    selection.collapse_to(head, goal);
 6544
 6545                    let transpose_start = display_map
 6546                        .buffer_snapshot
 6547                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6548                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6549                        let transpose_end = display_map
 6550                            .buffer_snapshot
 6551                            .clip_offset(transpose_offset + 1, Bias::Right);
 6552                        if let Some(ch) =
 6553                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6554                        {
 6555                            edits.push((transpose_start..transpose_offset, String::new()));
 6556                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6557                        }
 6558                    }
 6559                });
 6560                edits
 6561            });
 6562            this.buffer
 6563                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6564            let selections = this.selections.all::<usize>(cx);
 6565            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6566                s.select(selections);
 6567            });
 6568        });
 6569    }
 6570
 6571    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6572        self.rewrap_impl(IsVimMode::No, cx)
 6573    }
 6574
 6575    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6576        let buffer = self.buffer.read(cx).snapshot(cx);
 6577        let selections = self.selections.all::<Point>(cx);
 6578        let mut selections = selections.iter().peekable();
 6579
 6580        let mut edits = Vec::new();
 6581        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6582
 6583        while let Some(selection) = selections.next() {
 6584            let mut start_row = selection.start.row;
 6585            let mut end_row = selection.end.row;
 6586
 6587            // Skip selections that overlap with a range that has already been rewrapped.
 6588            let selection_range = start_row..end_row;
 6589            if rewrapped_row_ranges
 6590                .iter()
 6591                .any(|range| range.overlaps(&selection_range))
 6592            {
 6593                continue;
 6594            }
 6595
 6596            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6597
 6598            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6599                match language_scope.language_name().0.as_ref() {
 6600                    "Markdown" | "Plain Text" => {
 6601                        should_rewrap = true;
 6602                    }
 6603                    _ => {}
 6604                }
 6605            }
 6606
 6607            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6608
 6609            // Since not all lines in the selection may be at the same indent
 6610            // level, choose the indent size that is the most common between all
 6611            // of the lines.
 6612            //
 6613            // If there is a tie, we use the deepest indent.
 6614            let (indent_size, indent_end) = {
 6615                let mut indent_size_occurrences = HashMap::default();
 6616                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6617
 6618                for row in start_row..=end_row {
 6619                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6620                    rows_by_indent_size.entry(indent).or_default().push(row);
 6621                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6622                }
 6623
 6624                let indent_size = indent_size_occurrences
 6625                    .into_iter()
 6626                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6627                    .map(|(indent, _)| indent)
 6628                    .unwrap_or_default();
 6629                let row = rows_by_indent_size[&indent_size][0];
 6630                let indent_end = Point::new(row, indent_size.len);
 6631
 6632                (indent_size, indent_end)
 6633            };
 6634
 6635            let mut line_prefix = indent_size.chars().collect::<String>();
 6636
 6637            if let Some(comment_prefix) =
 6638                buffer
 6639                    .language_scope_at(selection.head())
 6640                    .and_then(|language| {
 6641                        language
 6642                            .line_comment_prefixes()
 6643                            .iter()
 6644                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6645                            .cloned()
 6646                    })
 6647            {
 6648                line_prefix.push_str(&comment_prefix);
 6649                should_rewrap = true;
 6650            }
 6651
 6652            if !should_rewrap {
 6653                continue;
 6654            }
 6655
 6656            if selection.is_empty() {
 6657                'expand_upwards: while start_row > 0 {
 6658                    let prev_row = start_row - 1;
 6659                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6660                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6661                    {
 6662                        start_row = prev_row;
 6663                    } else {
 6664                        break 'expand_upwards;
 6665                    }
 6666                }
 6667
 6668                'expand_downwards: while end_row < buffer.max_point().row {
 6669                    let next_row = end_row + 1;
 6670                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6671                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6672                    {
 6673                        end_row = next_row;
 6674                    } else {
 6675                        break 'expand_downwards;
 6676                    }
 6677                }
 6678            }
 6679
 6680            let start = Point::new(start_row, 0);
 6681            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6682            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6683            let Some(lines_without_prefixes) = selection_text
 6684                .lines()
 6685                .map(|line| {
 6686                    line.strip_prefix(&line_prefix)
 6687                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6688                        .ok_or_else(|| {
 6689                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6690                        })
 6691                })
 6692                .collect::<Result<Vec<_>, _>>()
 6693                .log_err()
 6694            else {
 6695                continue;
 6696            };
 6697
 6698            let wrap_column = buffer
 6699                .settings_at(Point::new(start_row, 0), cx)
 6700                .preferred_line_length as usize;
 6701            let wrapped_text = wrap_with_prefix(
 6702                line_prefix,
 6703                lines_without_prefixes.join(" "),
 6704                wrap_column,
 6705                tab_size,
 6706            );
 6707
 6708            // TODO: should always use char-based diff while still supporting cursor behavior that
 6709            // matches vim.
 6710            let diff = match is_vim_mode {
 6711                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6712                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6713            };
 6714            let mut offset = start.to_offset(&buffer);
 6715            let mut moved_since_edit = true;
 6716
 6717            for change in diff.iter_all_changes() {
 6718                let value = change.value();
 6719                match change.tag() {
 6720                    ChangeTag::Equal => {
 6721                        offset += value.len();
 6722                        moved_since_edit = true;
 6723                    }
 6724                    ChangeTag::Delete => {
 6725                        let start = buffer.anchor_after(offset);
 6726                        let end = buffer.anchor_before(offset + value.len());
 6727
 6728                        if moved_since_edit {
 6729                            edits.push((start..end, String::new()));
 6730                        } else {
 6731                            edits.last_mut().unwrap().0.end = end;
 6732                        }
 6733
 6734                        offset += value.len();
 6735                        moved_since_edit = false;
 6736                    }
 6737                    ChangeTag::Insert => {
 6738                        if moved_since_edit {
 6739                            let anchor = buffer.anchor_after(offset);
 6740                            edits.push((anchor..anchor, value.to_string()));
 6741                        } else {
 6742                            edits.last_mut().unwrap().1.push_str(value);
 6743                        }
 6744
 6745                        moved_since_edit = false;
 6746                    }
 6747                }
 6748            }
 6749
 6750            rewrapped_row_ranges.push(start_row..=end_row);
 6751        }
 6752
 6753        self.buffer
 6754            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6755    }
 6756
 6757    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6758        let mut text = String::new();
 6759        let buffer = self.buffer.read(cx).snapshot(cx);
 6760        let mut selections = self.selections.all::<Point>(cx);
 6761        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6762        {
 6763            let max_point = buffer.max_point();
 6764            let mut is_first = true;
 6765            for selection in &mut selections {
 6766                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6767                if is_entire_line {
 6768                    selection.start = Point::new(selection.start.row, 0);
 6769                    if !selection.is_empty() && selection.end.column == 0 {
 6770                        selection.end = cmp::min(max_point, selection.end);
 6771                    } else {
 6772                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6773                    }
 6774                    selection.goal = SelectionGoal::None;
 6775                }
 6776                if is_first {
 6777                    is_first = false;
 6778                } else {
 6779                    text += "\n";
 6780                }
 6781                let mut len = 0;
 6782                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6783                    text.push_str(chunk);
 6784                    len += chunk.len();
 6785                }
 6786                clipboard_selections.push(ClipboardSelection {
 6787                    len,
 6788                    is_entire_line,
 6789                    first_line_indent: buffer
 6790                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6791                        .len,
 6792                });
 6793            }
 6794        }
 6795
 6796        self.transact(cx, |this, cx| {
 6797            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6798                s.select(selections);
 6799            });
 6800            this.insert("", cx);
 6801        });
 6802        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6803    }
 6804
 6805    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6806        let item = self.cut_common(cx);
 6807        cx.write_to_clipboard(item);
 6808    }
 6809
 6810    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6811        self.change_selections(None, cx, |s| {
 6812            s.move_with(|snapshot, sel| {
 6813                if sel.is_empty() {
 6814                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6815                }
 6816            });
 6817        });
 6818        let item = self.cut_common(cx);
 6819        cx.set_global(KillRing(item))
 6820    }
 6821
 6822    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6823        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6824            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6825                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6826            } else {
 6827                return;
 6828            }
 6829        } else {
 6830            return;
 6831        };
 6832        self.do_paste(&text, metadata, false, cx);
 6833    }
 6834
 6835    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6836        let selections = self.selections.all::<Point>(cx);
 6837        let buffer = self.buffer.read(cx).read(cx);
 6838        let mut text = String::new();
 6839
 6840        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6841        {
 6842            let max_point = buffer.max_point();
 6843            let mut is_first = true;
 6844            for selection in selections.iter() {
 6845                let mut start = selection.start;
 6846                let mut end = selection.end;
 6847                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6848                if is_entire_line {
 6849                    start = Point::new(start.row, 0);
 6850                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6851                }
 6852                if is_first {
 6853                    is_first = false;
 6854                } else {
 6855                    text += "\n";
 6856                }
 6857                let mut len = 0;
 6858                for chunk in buffer.text_for_range(start..end) {
 6859                    text.push_str(chunk);
 6860                    len += chunk.len();
 6861                }
 6862                clipboard_selections.push(ClipboardSelection {
 6863                    len,
 6864                    is_entire_line,
 6865                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6866                });
 6867            }
 6868        }
 6869
 6870        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6871            text,
 6872            clipboard_selections,
 6873        ));
 6874    }
 6875
 6876    pub fn do_paste(
 6877        &mut self,
 6878        text: &String,
 6879        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6880        handle_entire_lines: bool,
 6881        cx: &mut ViewContext<Self>,
 6882    ) {
 6883        if self.read_only(cx) {
 6884            return;
 6885        }
 6886
 6887        let clipboard_text = Cow::Borrowed(text);
 6888
 6889        self.transact(cx, |this, cx| {
 6890            if let Some(mut clipboard_selections) = clipboard_selections {
 6891                let old_selections = this.selections.all::<usize>(cx);
 6892                let all_selections_were_entire_line =
 6893                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6894                let first_selection_indent_column =
 6895                    clipboard_selections.first().map(|s| s.first_line_indent);
 6896                if clipboard_selections.len() != old_selections.len() {
 6897                    clipboard_selections.drain(..);
 6898                }
 6899                let cursor_offset = this.selections.last::<usize>(cx).head();
 6900                let mut auto_indent_on_paste = true;
 6901
 6902                this.buffer.update(cx, |buffer, cx| {
 6903                    let snapshot = buffer.read(cx);
 6904                    auto_indent_on_paste =
 6905                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6906
 6907                    let mut start_offset = 0;
 6908                    let mut edits = Vec::new();
 6909                    let mut original_indent_columns = Vec::new();
 6910                    for (ix, selection) in old_selections.iter().enumerate() {
 6911                        let to_insert;
 6912                        let entire_line;
 6913                        let original_indent_column;
 6914                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6915                            let end_offset = start_offset + clipboard_selection.len;
 6916                            to_insert = &clipboard_text[start_offset..end_offset];
 6917                            entire_line = clipboard_selection.is_entire_line;
 6918                            start_offset = end_offset + 1;
 6919                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6920                        } else {
 6921                            to_insert = clipboard_text.as_str();
 6922                            entire_line = all_selections_were_entire_line;
 6923                            original_indent_column = first_selection_indent_column
 6924                        }
 6925
 6926                        // If the corresponding selection was empty when this slice of the
 6927                        // clipboard text was written, then the entire line containing the
 6928                        // selection was copied. If this selection is also currently empty,
 6929                        // then paste the line before the current line of the buffer.
 6930                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6931                            let column = selection.start.to_point(&snapshot).column as usize;
 6932                            let line_start = selection.start - column;
 6933                            line_start..line_start
 6934                        } else {
 6935                            selection.range()
 6936                        };
 6937
 6938                        edits.push((range, to_insert));
 6939                        original_indent_columns.extend(original_indent_column);
 6940                    }
 6941                    drop(snapshot);
 6942
 6943                    buffer.edit(
 6944                        edits,
 6945                        if auto_indent_on_paste {
 6946                            Some(AutoindentMode::Block {
 6947                                original_indent_columns,
 6948                            })
 6949                        } else {
 6950                            None
 6951                        },
 6952                        cx,
 6953                    );
 6954                });
 6955
 6956                let selections = this.selections.all::<usize>(cx);
 6957                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6958            } else {
 6959                this.insert(&clipboard_text, cx);
 6960            }
 6961        });
 6962    }
 6963
 6964    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6965        if let Some(item) = cx.read_from_clipboard() {
 6966            let entries = item.entries();
 6967
 6968            match entries.first() {
 6969                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6970                // of all the pasted entries.
 6971                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6972                    .do_paste(
 6973                        clipboard_string.text(),
 6974                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6975                        true,
 6976                        cx,
 6977                    ),
 6978                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6979            }
 6980        }
 6981    }
 6982
 6983    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6984        if self.read_only(cx) {
 6985            return;
 6986        }
 6987
 6988        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6989            if let Some((selections, _)) =
 6990                self.selection_history.transaction(transaction_id).cloned()
 6991            {
 6992                self.change_selections(None, cx, |s| {
 6993                    s.select_anchors(selections.to_vec());
 6994                });
 6995            }
 6996            self.request_autoscroll(Autoscroll::fit(), cx);
 6997            self.unmark_text(cx);
 6998            self.refresh_inline_completion(true, false, cx);
 6999            cx.emit(EditorEvent::Edited { transaction_id });
 7000            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7001        }
 7002    }
 7003
 7004    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7005        if self.read_only(cx) {
 7006            return;
 7007        }
 7008
 7009        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7010            if let Some((_, Some(selections))) =
 7011                self.selection_history.transaction(transaction_id).cloned()
 7012            {
 7013                self.change_selections(None, cx, |s| {
 7014                    s.select_anchors(selections.to_vec());
 7015                });
 7016            }
 7017            self.request_autoscroll(Autoscroll::fit(), cx);
 7018            self.unmark_text(cx);
 7019            self.refresh_inline_completion(true, false, cx);
 7020            cx.emit(EditorEvent::Edited { transaction_id });
 7021        }
 7022    }
 7023
 7024    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7025        self.buffer
 7026            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7027    }
 7028
 7029    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7030        self.buffer
 7031            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7032    }
 7033
 7034    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7035        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7036            let line_mode = s.line_mode;
 7037            s.move_with(|map, selection| {
 7038                let cursor = if selection.is_empty() && !line_mode {
 7039                    movement::left(map, selection.start)
 7040                } else {
 7041                    selection.start
 7042                };
 7043                selection.collapse_to(cursor, SelectionGoal::None);
 7044            });
 7045        })
 7046    }
 7047
 7048    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7049        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7050            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7051        })
 7052    }
 7053
 7054    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7055        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7056            let line_mode = s.line_mode;
 7057            s.move_with(|map, selection| {
 7058                let cursor = if selection.is_empty() && !line_mode {
 7059                    movement::right(map, selection.end)
 7060                } else {
 7061                    selection.end
 7062                };
 7063                selection.collapse_to(cursor, SelectionGoal::None)
 7064            });
 7065        })
 7066    }
 7067
 7068    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7069        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7070            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7071        })
 7072    }
 7073
 7074    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7075        if self.take_rename(true, cx).is_some() {
 7076            return;
 7077        }
 7078
 7079        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7080            cx.propagate();
 7081            return;
 7082        }
 7083
 7084        let text_layout_details = &self.text_layout_details(cx);
 7085        let selection_count = self.selections.count();
 7086        let first_selection = self.selections.first_anchor();
 7087
 7088        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7089            let line_mode = s.line_mode;
 7090            s.move_with(|map, selection| {
 7091                if !selection.is_empty() && !line_mode {
 7092                    selection.goal = SelectionGoal::None;
 7093                }
 7094                let (cursor, goal) = movement::up(
 7095                    map,
 7096                    selection.start,
 7097                    selection.goal,
 7098                    false,
 7099                    text_layout_details,
 7100                );
 7101                selection.collapse_to(cursor, goal);
 7102            });
 7103        });
 7104
 7105        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7106        {
 7107            cx.propagate();
 7108        }
 7109    }
 7110
 7111    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7112        if self.take_rename(true, cx).is_some() {
 7113            return;
 7114        }
 7115
 7116        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7117            cx.propagate();
 7118            return;
 7119        }
 7120
 7121        let text_layout_details = &self.text_layout_details(cx);
 7122
 7123        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7124            let line_mode = s.line_mode;
 7125            s.move_with(|map, selection| {
 7126                if !selection.is_empty() && !line_mode {
 7127                    selection.goal = SelectionGoal::None;
 7128                }
 7129                let (cursor, goal) = movement::up_by_rows(
 7130                    map,
 7131                    selection.start,
 7132                    action.lines,
 7133                    selection.goal,
 7134                    false,
 7135                    text_layout_details,
 7136                );
 7137                selection.collapse_to(cursor, goal);
 7138            });
 7139        })
 7140    }
 7141
 7142    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7143        if self.take_rename(true, cx).is_some() {
 7144            return;
 7145        }
 7146
 7147        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7148            cx.propagate();
 7149            return;
 7150        }
 7151
 7152        let text_layout_details = &self.text_layout_details(cx);
 7153
 7154        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7155            let line_mode = s.line_mode;
 7156            s.move_with(|map, selection| {
 7157                if !selection.is_empty() && !line_mode {
 7158                    selection.goal = SelectionGoal::None;
 7159                }
 7160                let (cursor, goal) = movement::down_by_rows(
 7161                    map,
 7162                    selection.start,
 7163                    action.lines,
 7164                    selection.goal,
 7165                    false,
 7166                    text_layout_details,
 7167                );
 7168                selection.collapse_to(cursor, goal);
 7169            });
 7170        })
 7171    }
 7172
 7173    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7174        let text_layout_details = &self.text_layout_details(cx);
 7175        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7176            s.move_heads_with(|map, head, goal| {
 7177                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7178            })
 7179        })
 7180    }
 7181
 7182    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7183        let text_layout_details = &self.text_layout_details(cx);
 7184        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7185            s.move_heads_with(|map, head, goal| {
 7186                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7187            })
 7188        })
 7189    }
 7190
 7191    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7192        let Some(row_count) = self.visible_row_count() else {
 7193            return;
 7194        };
 7195
 7196        let text_layout_details = &self.text_layout_details(cx);
 7197
 7198        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7199            s.move_heads_with(|map, head, goal| {
 7200                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7201            })
 7202        })
 7203    }
 7204
 7205    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7206        if self.take_rename(true, cx).is_some() {
 7207            return;
 7208        }
 7209
 7210        if self
 7211            .context_menu
 7212            .borrow_mut()
 7213            .as_mut()
 7214            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7215            .unwrap_or(false)
 7216        {
 7217            return;
 7218        }
 7219
 7220        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7221            cx.propagate();
 7222            return;
 7223        }
 7224
 7225        let Some(row_count) = self.visible_row_count() else {
 7226            return;
 7227        };
 7228
 7229        let autoscroll = if action.center_cursor {
 7230            Autoscroll::center()
 7231        } else {
 7232            Autoscroll::fit()
 7233        };
 7234
 7235        let text_layout_details = &self.text_layout_details(cx);
 7236
 7237        self.change_selections(Some(autoscroll), cx, |s| {
 7238            let line_mode = s.line_mode;
 7239            s.move_with(|map, selection| {
 7240                if !selection.is_empty() && !line_mode {
 7241                    selection.goal = SelectionGoal::None;
 7242                }
 7243                let (cursor, goal) = movement::up_by_rows(
 7244                    map,
 7245                    selection.end,
 7246                    row_count,
 7247                    selection.goal,
 7248                    false,
 7249                    text_layout_details,
 7250                );
 7251                selection.collapse_to(cursor, goal);
 7252            });
 7253        });
 7254    }
 7255
 7256    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7257        let text_layout_details = &self.text_layout_details(cx);
 7258        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7259            s.move_heads_with(|map, head, goal| {
 7260                movement::up(map, head, goal, false, text_layout_details)
 7261            })
 7262        })
 7263    }
 7264
 7265    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7266        self.take_rename(true, cx);
 7267
 7268        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7269            cx.propagate();
 7270            return;
 7271        }
 7272
 7273        let text_layout_details = &self.text_layout_details(cx);
 7274        let selection_count = self.selections.count();
 7275        let first_selection = self.selections.first_anchor();
 7276
 7277        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7278            let line_mode = s.line_mode;
 7279            s.move_with(|map, selection| {
 7280                if !selection.is_empty() && !line_mode {
 7281                    selection.goal = SelectionGoal::None;
 7282                }
 7283                let (cursor, goal) = movement::down(
 7284                    map,
 7285                    selection.end,
 7286                    selection.goal,
 7287                    false,
 7288                    text_layout_details,
 7289                );
 7290                selection.collapse_to(cursor, goal);
 7291            });
 7292        });
 7293
 7294        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7295        {
 7296            cx.propagate();
 7297        }
 7298    }
 7299
 7300    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7301        let Some(row_count) = self.visible_row_count() else {
 7302            return;
 7303        };
 7304
 7305        let text_layout_details = &self.text_layout_details(cx);
 7306
 7307        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7308            s.move_heads_with(|map, head, goal| {
 7309                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7310            })
 7311        })
 7312    }
 7313
 7314    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7315        if self.take_rename(true, cx).is_some() {
 7316            return;
 7317        }
 7318
 7319        if self
 7320            .context_menu
 7321            .borrow_mut()
 7322            .as_mut()
 7323            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7324            .unwrap_or(false)
 7325        {
 7326            return;
 7327        }
 7328
 7329        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7330            cx.propagate();
 7331            return;
 7332        }
 7333
 7334        let Some(row_count) = self.visible_row_count() else {
 7335            return;
 7336        };
 7337
 7338        let autoscroll = if action.center_cursor {
 7339            Autoscroll::center()
 7340        } else {
 7341            Autoscroll::fit()
 7342        };
 7343
 7344        let text_layout_details = &self.text_layout_details(cx);
 7345        self.change_selections(Some(autoscroll), cx, |s| {
 7346            let line_mode = s.line_mode;
 7347            s.move_with(|map, selection| {
 7348                if !selection.is_empty() && !line_mode {
 7349                    selection.goal = SelectionGoal::None;
 7350                }
 7351                let (cursor, goal) = movement::down_by_rows(
 7352                    map,
 7353                    selection.end,
 7354                    row_count,
 7355                    selection.goal,
 7356                    false,
 7357                    text_layout_details,
 7358                );
 7359                selection.collapse_to(cursor, goal);
 7360            });
 7361        });
 7362    }
 7363
 7364    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7365        let text_layout_details = &self.text_layout_details(cx);
 7366        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7367            s.move_heads_with(|map, head, goal| {
 7368                movement::down(map, head, goal, false, text_layout_details)
 7369            })
 7370        });
 7371    }
 7372
 7373    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7374        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7375            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7376        }
 7377    }
 7378
 7379    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7380        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7381            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7382        }
 7383    }
 7384
 7385    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7386        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7387            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7388        }
 7389    }
 7390
 7391    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7392        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7393            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7394        }
 7395    }
 7396
 7397    pub fn move_to_previous_word_start(
 7398        &mut self,
 7399        _: &MoveToPreviousWordStart,
 7400        cx: &mut ViewContext<Self>,
 7401    ) {
 7402        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7403            s.move_cursors_with(|map, head, _| {
 7404                (
 7405                    movement::previous_word_start(map, head),
 7406                    SelectionGoal::None,
 7407                )
 7408            });
 7409        })
 7410    }
 7411
 7412    pub fn move_to_previous_subword_start(
 7413        &mut self,
 7414        _: &MoveToPreviousSubwordStart,
 7415        cx: &mut ViewContext<Self>,
 7416    ) {
 7417        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7418            s.move_cursors_with(|map, head, _| {
 7419                (
 7420                    movement::previous_subword_start(map, head),
 7421                    SelectionGoal::None,
 7422                )
 7423            });
 7424        })
 7425    }
 7426
 7427    pub fn select_to_previous_word_start(
 7428        &mut self,
 7429        _: &SelectToPreviousWordStart,
 7430        cx: &mut ViewContext<Self>,
 7431    ) {
 7432        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7433            s.move_heads_with(|map, head, _| {
 7434                (
 7435                    movement::previous_word_start(map, head),
 7436                    SelectionGoal::None,
 7437                )
 7438            });
 7439        })
 7440    }
 7441
 7442    pub fn select_to_previous_subword_start(
 7443        &mut self,
 7444        _: &SelectToPreviousSubwordStart,
 7445        cx: &mut ViewContext<Self>,
 7446    ) {
 7447        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7448            s.move_heads_with(|map, head, _| {
 7449                (
 7450                    movement::previous_subword_start(map, head),
 7451                    SelectionGoal::None,
 7452                )
 7453            });
 7454        })
 7455    }
 7456
 7457    pub fn delete_to_previous_word_start(
 7458        &mut self,
 7459        action: &DeleteToPreviousWordStart,
 7460        cx: &mut ViewContext<Self>,
 7461    ) {
 7462        self.transact(cx, |this, cx| {
 7463            this.select_autoclose_pair(cx);
 7464            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7465                let line_mode = s.line_mode;
 7466                s.move_with(|map, selection| {
 7467                    if selection.is_empty() && !line_mode {
 7468                        let cursor = if action.ignore_newlines {
 7469                            movement::previous_word_start(map, selection.head())
 7470                        } else {
 7471                            movement::previous_word_start_or_newline(map, selection.head())
 7472                        };
 7473                        selection.set_head(cursor, SelectionGoal::None);
 7474                    }
 7475                });
 7476            });
 7477            this.insert("", cx);
 7478        });
 7479    }
 7480
 7481    pub fn delete_to_previous_subword_start(
 7482        &mut self,
 7483        _: &DeleteToPreviousSubwordStart,
 7484        cx: &mut ViewContext<Self>,
 7485    ) {
 7486        self.transact(cx, |this, cx| {
 7487            this.select_autoclose_pair(cx);
 7488            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7489                let line_mode = s.line_mode;
 7490                s.move_with(|map, selection| {
 7491                    if selection.is_empty() && !line_mode {
 7492                        let cursor = movement::previous_subword_start(map, selection.head());
 7493                        selection.set_head(cursor, SelectionGoal::None);
 7494                    }
 7495                });
 7496            });
 7497            this.insert("", cx);
 7498        });
 7499    }
 7500
 7501    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7502        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7503            s.move_cursors_with(|map, head, _| {
 7504                (movement::next_word_end(map, head), SelectionGoal::None)
 7505            });
 7506        })
 7507    }
 7508
 7509    pub fn move_to_next_subword_end(
 7510        &mut self,
 7511        _: &MoveToNextSubwordEnd,
 7512        cx: &mut ViewContext<Self>,
 7513    ) {
 7514        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7515            s.move_cursors_with(|map, head, _| {
 7516                (movement::next_subword_end(map, head), SelectionGoal::None)
 7517            });
 7518        })
 7519    }
 7520
 7521    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7522        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7523            s.move_heads_with(|map, head, _| {
 7524                (movement::next_word_end(map, head), SelectionGoal::None)
 7525            });
 7526        })
 7527    }
 7528
 7529    pub fn select_to_next_subword_end(
 7530        &mut self,
 7531        _: &SelectToNextSubwordEnd,
 7532        cx: &mut ViewContext<Self>,
 7533    ) {
 7534        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7535            s.move_heads_with(|map, head, _| {
 7536                (movement::next_subword_end(map, head), SelectionGoal::None)
 7537            });
 7538        })
 7539    }
 7540
 7541    pub fn delete_to_next_word_end(
 7542        &mut self,
 7543        action: &DeleteToNextWordEnd,
 7544        cx: &mut ViewContext<Self>,
 7545    ) {
 7546        self.transact(cx, |this, cx| {
 7547            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7548                let line_mode = s.line_mode;
 7549                s.move_with(|map, selection| {
 7550                    if selection.is_empty() && !line_mode {
 7551                        let cursor = if action.ignore_newlines {
 7552                            movement::next_word_end(map, selection.head())
 7553                        } else {
 7554                            movement::next_word_end_or_newline(map, selection.head())
 7555                        };
 7556                        selection.set_head(cursor, SelectionGoal::None);
 7557                    }
 7558                });
 7559            });
 7560            this.insert("", cx);
 7561        });
 7562    }
 7563
 7564    pub fn delete_to_next_subword_end(
 7565        &mut self,
 7566        _: &DeleteToNextSubwordEnd,
 7567        cx: &mut ViewContext<Self>,
 7568    ) {
 7569        self.transact(cx, |this, cx| {
 7570            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7571                s.move_with(|map, selection| {
 7572                    if selection.is_empty() {
 7573                        let cursor = movement::next_subword_end(map, selection.head());
 7574                        selection.set_head(cursor, SelectionGoal::None);
 7575                    }
 7576                });
 7577            });
 7578            this.insert("", cx);
 7579        });
 7580    }
 7581
 7582    pub fn move_to_beginning_of_line(
 7583        &mut self,
 7584        action: &MoveToBeginningOfLine,
 7585        cx: &mut ViewContext<Self>,
 7586    ) {
 7587        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7588            s.move_cursors_with(|map, head, _| {
 7589                (
 7590                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7591                    SelectionGoal::None,
 7592                )
 7593            });
 7594        })
 7595    }
 7596
 7597    pub fn select_to_beginning_of_line(
 7598        &mut self,
 7599        action: &SelectToBeginningOfLine,
 7600        cx: &mut ViewContext<Self>,
 7601    ) {
 7602        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7603            s.move_heads_with(|map, head, _| {
 7604                (
 7605                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7606                    SelectionGoal::None,
 7607                )
 7608            });
 7609        });
 7610    }
 7611
 7612    pub fn delete_to_beginning_of_line(
 7613        &mut self,
 7614        _: &DeleteToBeginningOfLine,
 7615        cx: &mut ViewContext<Self>,
 7616    ) {
 7617        self.transact(cx, |this, cx| {
 7618            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7619                s.move_with(|_, selection| {
 7620                    selection.reversed = true;
 7621                });
 7622            });
 7623
 7624            this.select_to_beginning_of_line(
 7625                &SelectToBeginningOfLine {
 7626                    stop_at_soft_wraps: false,
 7627                },
 7628                cx,
 7629            );
 7630            this.backspace(&Backspace, cx);
 7631        });
 7632    }
 7633
 7634    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7635        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7636            s.move_cursors_with(|map, head, _| {
 7637                (
 7638                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7639                    SelectionGoal::None,
 7640                )
 7641            });
 7642        })
 7643    }
 7644
 7645    pub fn select_to_end_of_line(
 7646        &mut self,
 7647        action: &SelectToEndOfLine,
 7648        cx: &mut ViewContext<Self>,
 7649    ) {
 7650        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7651            s.move_heads_with(|map, head, _| {
 7652                (
 7653                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7654                    SelectionGoal::None,
 7655                )
 7656            });
 7657        })
 7658    }
 7659
 7660    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7661        self.transact(cx, |this, cx| {
 7662            this.select_to_end_of_line(
 7663                &SelectToEndOfLine {
 7664                    stop_at_soft_wraps: false,
 7665                },
 7666                cx,
 7667            );
 7668            this.delete(&Delete, cx);
 7669        });
 7670    }
 7671
 7672    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7673        self.transact(cx, |this, cx| {
 7674            this.select_to_end_of_line(
 7675                &SelectToEndOfLine {
 7676                    stop_at_soft_wraps: false,
 7677                },
 7678                cx,
 7679            );
 7680            this.cut(&Cut, cx);
 7681        });
 7682    }
 7683
 7684    pub fn move_to_start_of_paragraph(
 7685        &mut self,
 7686        _: &MoveToStartOfParagraph,
 7687        cx: &mut ViewContext<Self>,
 7688    ) {
 7689        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7690            cx.propagate();
 7691            return;
 7692        }
 7693
 7694        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7695            s.move_with(|map, selection| {
 7696                selection.collapse_to(
 7697                    movement::start_of_paragraph(map, selection.head(), 1),
 7698                    SelectionGoal::None,
 7699                )
 7700            });
 7701        })
 7702    }
 7703
 7704    pub fn move_to_end_of_paragraph(
 7705        &mut self,
 7706        _: &MoveToEndOfParagraph,
 7707        cx: &mut ViewContext<Self>,
 7708    ) {
 7709        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7710            cx.propagate();
 7711            return;
 7712        }
 7713
 7714        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7715            s.move_with(|map, selection| {
 7716                selection.collapse_to(
 7717                    movement::end_of_paragraph(map, selection.head(), 1),
 7718                    SelectionGoal::None,
 7719                )
 7720            });
 7721        })
 7722    }
 7723
 7724    pub fn select_to_start_of_paragraph(
 7725        &mut self,
 7726        _: &SelectToStartOfParagraph,
 7727        cx: &mut ViewContext<Self>,
 7728    ) {
 7729        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7730            cx.propagate();
 7731            return;
 7732        }
 7733
 7734        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7735            s.move_heads_with(|map, head, _| {
 7736                (
 7737                    movement::start_of_paragraph(map, head, 1),
 7738                    SelectionGoal::None,
 7739                )
 7740            });
 7741        })
 7742    }
 7743
 7744    pub fn select_to_end_of_paragraph(
 7745        &mut self,
 7746        _: &SelectToEndOfParagraph,
 7747        cx: &mut ViewContext<Self>,
 7748    ) {
 7749        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7750            cx.propagate();
 7751            return;
 7752        }
 7753
 7754        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7755            s.move_heads_with(|map, head, _| {
 7756                (
 7757                    movement::end_of_paragraph(map, head, 1),
 7758                    SelectionGoal::None,
 7759                )
 7760            });
 7761        })
 7762    }
 7763
 7764    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7765        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7766            cx.propagate();
 7767            return;
 7768        }
 7769
 7770        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7771            s.select_ranges(vec![0..0]);
 7772        });
 7773    }
 7774
 7775    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7776        let mut selection = self.selections.last::<Point>(cx);
 7777        selection.set_head(Point::zero(), SelectionGoal::None);
 7778
 7779        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7780            s.select(vec![selection]);
 7781        });
 7782    }
 7783
 7784    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7785        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7786            cx.propagate();
 7787            return;
 7788        }
 7789
 7790        let cursor = self.buffer.read(cx).read(cx).len();
 7791        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7792            s.select_ranges(vec![cursor..cursor])
 7793        });
 7794    }
 7795
 7796    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7797        self.nav_history = nav_history;
 7798    }
 7799
 7800    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7801        self.nav_history.as_ref()
 7802    }
 7803
 7804    fn push_to_nav_history(
 7805        &mut self,
 7806        cursor_anchor: Anchor,
 7807        new_position: Option<Point>,
 7808        cx: &mut ViewContext<Self>,
 7809    ) {
 7810        if let Some(nav_history) = self.nav_history.as_mut() {
 7811            let buffer = self.buffer.read(cx).read(cx);
 7812            let cursor_position = cursor_anchor.to_point(&buffer);
 7813            let scroll_state = self.scroll_manager.anchor();
 7814            let scroll_top_row = scroll_state.top_row(&buffer);
 7815            drop(buffer);
 7816
 7817            if let Some(new_position) = new_position {
 7818                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7819                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7820                    return;
 7821                }
 7822            }
 7823
 7824            nav_history.push(
 7825                Some(NavigationData {
 7826                    cursor_anchor,
 7827                    cursor_position,
 7828                    scroll_anchor: scroll_state,
 7829                    scroll_top_row,
 7830                }),
 7831                cx,
 7832            );
 7833        }
 7834    }
 7835
 7836    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7837        let buffer = self.buffer.read(cx).snapshot(cx);
 7838        let mut selection = self.selections.first::<usize>(cx);
 7839        selection.set_head(buffer.len(), SelectionGoal::None);
 7840        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7841            s.select(vec![selection]);
 7842        });
 7843    }
 7844
 7845    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7846        let end = self.buffer.read(cx).read(cx).len();
 7847        self.change_selections(None, cx, |s| {
 7848            s.select_ranges(vec![0..end]);
 7849        });
 7850    }
 7851
 7852    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7853        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7854        let mut selections = self.selections.all::<Point>(cx);
 7855        let max_point = display_map.buffer_snapshot.max_point();
 7856        for selection in &mut selections {
 7857            let rows = selection.spanned_rows(true, &display_map);
 7858            selection.start = Point::new(rows.start.0, 0);
 7859            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7860            selection.reversed = false;
 7861        }
 7862        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7863            s.select(selections);
 7864        });
 7865    }
 7866
 7867    pub fn split_selection_into_lines(
 7868        &mut self,
 7869        _: &SplitSelectionIntoLines,
 7870        cx: &mut ViewContext<Self>,
 7871    ) {
 7872        let mut to_unfold = Vec::new();
 7873        let mut new_selection_ranges = Vec::new();
 7874        {
 7875            let selections = self.selections.all::<Point>(cx);
 7876            let buffer = self.buffer.read(cx).read(cx);
 7877            for selection in selections {
 7878                for row in selection.start.row..selection.end.row {
 7879                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7880                    new_selection_ranges.push(cursor..cursor);
 7881                }
 7882                new_selection_ranges.push(selection.end..selection.end);
 7883                to_unfold.push(selection.start..selection.end);
 7884            }
 7885        }
 7886        self.unfold_ranges(&to_unfold, true, true, cx);
 7887        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7888            s.select_ranges(new_selection_ranges);
 7889        });
 7890    }
 7891
 7892    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7893        self.add_selection(true, cx);
 7894    }
 7895
 7896    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7897        self.add_selection(false, cx);
 7898    }
 7899
 7900    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7901        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7902        let mut selections = self.selections.all::<Point>(cx);
 7903        let text_layout_details = self.text_layout_details(cx);
 7904        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7905            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7906            let range = oldest_selection.display_range(&display_map).sorted();
 7907
 7908            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7909            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7910            let positions = start_x.min(end_x)..start_x.max(end_x);
 7911
 7912            selections.clear();
 7913            let mut stack = Vec::new();
 7914            for row in range.start.row().0..=range.end.row().0 {
 7915                if let Some(selection) = self.selections.build_columnar_selection(
 7916                    &display_map,
 7917                    DisplayRow(row),
 7918                    &positions,
 7919                    oldest_selection.reversed,
 7920                    &text_layout_details,
 7921                ) {
 7922                    stack.push(selection.id);
 7923                    selections.push(selection);
 7924                }
 7925            }
 7926
 7927            if above {
 7928                stack.reverse();
 7929            }
 7930
 7931            AddSelectionsState { above, stack }
 7932        });
 7933
 7934        let last_added_selection = *state.stack.last().unwrap();
 7935        let mut new_selections = Vec::new();
 7936        if above == state.above {
 7937            let end_row = if above {
 7938                DisplayRow(0)
 7939            } else {
 7940                display_map.max_point().row()
 7941            };
 7942
 7943            'outer: for selection in selections {
 7944                if selection.id == last_added_selection {
 7945                    let range = selection.display_range(&display_map).sorted();
 7946                    debug_assert_eq!(range.start.row(), range.end.row());
 7947                    let mut row = range.start.row();
 7948                    let positions =
 7949                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7950                            px(start)..px(end)
 7951                        } else {
 7952                            let start_x =
 7953                                display_map.x_for_display_point(range.start, &text_layout_details);
 7954                            let end_x =
 7955                                display_map.x_for_display_point(range.end, &text_layout_details);
 7956                            start_x.min(end_x)..start_x.max(end_x)
 7957                        };
 7958
 7959                    while row != end_row {
 7960                        if above {
 7961                            row.0 -= 1;
 7962                        } else {
 7963                            row.0 += 1;
 7964                        }
 7965
 7966                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7967                            &display_map,
 7968                            row,
 7969                            &positions,
 7970                            selection.reversed,
 7971                            &text_layout_details,
 7972                        ) {
 7973                            state.stack.push(new_selection.id);
 7974                            if above {
 7975                                new_selections.push(new_selection);
 7976                                new_selections.push(selection);
 7977                            } else {
 7978                                new_selections.push(selection);
 7979                                new_selections.push(new_selection);
 7980                            }
 7981
 7982                            continue 'outer;
 7983                        }
 7984                    }
 7985                }
 7986
 7987                new_selections.push(selection);
 7988            }
 7989        } else {
 7990            new_selections = selections;
 7991            new_selections.retain(|s| s.id != last_added_selection);
 7992            state.stack.pop();
 7993        }
 7994
 7995        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7996            s.select(new_selections);
 7997        });
 7998        if state.stack.len() > 1 {
 7999            self.add_selections_state = Some(state);
 8000        }
 8001    }
 8002
 8003    pub fn select_next_match_internal(
 8004        &mut self,
 8005        display_map: &DisplaySnapshot,
 8006        replace_newest: bool,
 8007        autoscroll: Option<Autoscroll>,
 8008        cx: &mut ViewContext<Self>,
 8009    ) -> Result<()> {
 8010        fn select_next_match_ranges(
 8011            this: &mut Editor,
 8012            range: Range<usize>,
 8013            replace_newest: bool,
 8014            auto_scroll: Option<Autoscroll>,
 8015            cx: &mut ViewContext<Editor>,
 8016        ) {
 8017            this.unfold_ranges(&[range.clone()], false, true, cx);
 8018            this.change_selections(auto_scroll, cx, |s| {
 8019                if replace_newest {
 8020                    s.delete(s.newest_anchor().id);
 8021                }
 8022                s.insert_range(range.clone());
 8023            });
 8024        }
 8025
 8026        let buffer = &display_map.buffer_snapshot;
 8027        let mut selections = self.selections.all::<usize>(cx);
 8028        if let Some(mut select_next_state) = self.select_next_state.take() {
 8029            let query = &select_next_state.query;
 8030            if !select_next_state.done {
 8031                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8032                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8033                let mut next_selected_range = None;
 8034
 8035                let bytes_after_last_selection =
 8036                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8037                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8038                let query_matches = query
 8039                    .stream_find_iter(bytes_after_last_selection)
 8040                    .map(|result| (last_selection.end, result))
 8041                    .chain(
 8042                        query
 8043                            .stream_find_iter(bytes_before_first_selection)
 8044                            .map(|result| (0, result)),
 8045                    );
 8046
 8047                for (start_offset, query_match) in query_matches {
 8048                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8049                    let offset_range =
 8050                        start_offset + query_match.start()..start_offset + query_match.end();
 8051                    let display_range = offset_range.start.to_display_point(display_map)
 8052                        ..offset_range.end.to_display_point(display_map);
 8053
 8054                    if !select_next_state.wordwise
 8055                        || (!movement::is_inside_word(display_map, display_range.start)
 8056                            && !movement::is_inside_word(display_map, display_range.end))
 8057                    {
 8058                        // TODO: This is n^2, because we might check all the selections
 8059                        if !selections
 8060                            .iter()
 8061                            .any(|selection| selection.range().overlaps(&offset_range))
 8062                        {
 8063                            next_selected_range = Some(offset_range);
 8064                            break;
 8065                        }
 8066                    }
 8067                }
 8068
 8069                if let Some(next_selected_range) = next_selected_range {
 8070                    select_next_match_ranges(
 8071                        self,
 8072                        next_selected_range,
 8073                        replace_newest,
 8074                        autoscroll,
 8075                        cx,
 8076                    );
 8077                } else {
 8078                    select_next_state.done = true;
 8079                }
 8080            }
 8081
 8082            self.select_next_state = Some(select_next_state);
 8083        } else {
 8084            let mut only_carets = true;
 8085            let mut same_text_selected = true;
 8086            let mut selected_text = None;
 8087
 8088            let mut selections_iter = selections.iter().peekable();
 8089            while let Some(selection) = selections_iter.next() {
 8090                if selection.start != selection.end {
 8091                    only_carets = false;
 8092                }
 8093
 8094                if same_text_selected {
 8095                    if selected_text.is_none() {
 8096                        selected_text =
 8097                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8098                    }
 8099
 8100                    if let Some(next_selection) = selections_iter.peek() {
 8101                        if next_selection.range().len() == selection.range().len() {
 8102                            let next_selected_text = buffer
 8103                                .text_for_range(next_selection.range())
 8104                                .collect::<String>();
 8105                            if Some(next_selected_text) != selected_text {
 8106                                same_text_selected = false;
 8107                                selected_text = None;
 8108                            }
 8109                        } else {
 8110                            same_text_selected = false;
 8111                            selected_text = None;
 8112                        }
 8113                    }
 8114                }
 8115            }
 8116
 8117            if only_carets {
 8118                for selection in &mut selections {
 8119                    let word_range = movement::surrounding_word(
 8120                        display_map,
 8121                        selection.start.to_display_point(display_map),
 8122                    );
 8123                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8124                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8125                    selection.goal = SelectionGoal::None;
 8126                    selection.reversed = false;
 8127                    select_next_match_ranges(
 8128                        self,
 8129                        selection.start..selection.end,
 8130                        replace_newest,
 8131                        autoscroll,
 8132                        cx,
 8133                    );
 8134                }
 8135
 8136                if selections.len() == 1 {
 8137                    let selection = selections
 8138                        .last()
 8139                        .expect("ensured that there's only one selection");
 8140                    let query = buffer
 8141                        .text_for_range(selection.start..selection.end)
 8142                        .collect::<String>();
 8143                    let is_empty = query.is_empty();
 8144                    let select_state = SelectNextState {
 8145                        query: AhoCorasick::new(&[query])?,
 8146                        wordwise: true,
 8147                        done: is_empty,
 8148                    };
 8149                    self.select_next_state = Some(select_state);
 8150                } else {
 8151                    self.select_next_state = None;
 8152                }
 8153            } else if let Some(selected_text) = selected_text {
 8154                self.select_next_state = Some(SelectNextState {
 8155                    query: AhoCorasick::new(&[selected_text])?,
 8156                    wordwise: false,
 8157                    done: false,
 8158                });
 8159                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8160            }
 8161        }
 8162        Ok(())
 8163    }
 8164
 8165    pub fn select_all_matches(
 8166        &mut self,
 8167        _action: &SelectAllMatches,
 8168        cx: &mut ViewContext<Self>,
 8169    ) -> Result<()> {
 8170        self.push_to_selection_history();
 8171        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8172
 8173        self.select_next_match_internal(&display_map, false, None, cx)?;
 8174        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8175            return Ok(());
 8176        };
 8177        if select_next_state.done {
 8178            return Ok(());
 8179        }
 8180
 8181        let mut new_selections = self.selections.all::<usize>(cx);
 8182
 8183        let buffer = &display_map.buffer_snapshot;
 8184        let query_matches = select_next_state
 8185            .query
 8186            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8187
 8188        for query_match in query_matches {
 8189            let query_match = query_match.unwrap(); // can only fail due to I/O
 8190            let offset_range = query_match.start()..query_match.end();
 8191            let display_range = offset_range.start.to_display_point(&display_map)
 8192                ..offset_range.end.to_display_point(&display_map);
 8193
 8194            if !select_next_state.wordwise
 8195                || (!movement::is_inside_word(&display_map, display_range.start)
 8196                    && !movement::is_inside_word(&display_map, display_range.end))
 8197            {
 8198                self.selections.change_with(cx, |selections| {
 8199                    new_selections.push(Selection {
 8200                        id: selections.new_selection_id(),
 8201                        start: offset_range.start,
 8202                        end: offset_range.end,
 8203                        reversed: false,
 8204                        goal: SelectionGoal::None,
 8205                    });
 8206                });
 8207            }
 8208        }
 8209
 8210        new_selections.sort_by_key(|selection| selection.start);
 8211        let mut ix = 0;
 8212        while ix + 1 < new_selections.len() {
 8213            let current_selection = &new_selections[ix];
 8214            let next_selection = &new_selections[ix + 1];
 8215            if current_selection.range().overlaps(&next_selection.range()) {
 8216                if current_selection.id < next_selection.id {
 8217                    new_selections.remove(ix + 1);
 8218                } else {
 8219                    new_selections.remove(ix);
 8220                }
 8221            } else {
 8222                ix += 1;
 8223            }
 8224        }
 8225
 8226        select_next_state.done = true;
 8227        self.unfold_ranges(
 8228            &new_selections
 8229                .iter()
 8230                .map(|selection| selection.range())
 8231                .collect::<Vec<_>>(),
 8232            false,
 8233            false,
 8234            cx,
 8235        );
 8236        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8237            selections.select(new_selections)
 8238        });
 8239
 8240        Ok(())
 8241    }
 8242
 8243    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8244        self.push_to_selection_history();
 8245        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8246        self.select_next_match_internal(
 8247            &display_map,
 8248            action.replace_newest,
 8249            Some(Autoscroll::newest()),
 8250            cx,
 8251        )?;
 8252        Ok(())
 8253    }
 8254
 8255    pub fn select_previous(
 8256        &mut self,
 8257        action: &SelectPrevious,
 8258        cx: &mut ViewContext<Self>,
 8259    ) -> Result<()> {
 8260        self.push_to_selection_history();
 8261        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8262        let buffer = &display_map.buffer_snapshot;
 8263        let mut selections = self.selections.all::<usize>(cx);
 8264        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8265            let query = &select_prev_state.query;
 8266            if !select_prev_state.done {
 8267                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8268                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8269                let mut next_selected_range = None;
 8270                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8271                let bytes_before_last_selection =
 8272                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8273                let bytes_after_first_selection =
 8274                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8275                let query_matches = query
 8276                    .stream_find_iter(bytes_before_last_selection)
 8277                    .map(|result| (last_selection.start, result))
 8278                    .chain(
 8279                        query
 8280                            .stream_find_iter(bytes_after_first_selection)
 8281                            .map(|result| (buffer.len(), result)),
 8282                    );
 8283                for (end_offset, query_match) in query_matches {
 8284                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8285                    let offset_range =
 8286                        end_offset - query_match.end()..end_offset - query_match.start();
 8287                    let display_range = offset_range.start.to_display_point(&display_map)
 8288                        ..offset_range.end.to_display_point(&display_map);
 8289
 8290                    if !select_prev_state.wordwise
 8291                        || (!movement::is_inside_word(&display_map, display_range.start)
 8292                            && !movement::is_inside_word(&display_map, display_range.end))
 8293                    {
 8294                        next_selected_range = Some(offset_range);
 8295                        break;
 8296                    }
 8297                }
 8298
 8299                if let Some(next_selected_range) = next_selected_range {
 8300                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8301                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8302                        if action.replace_newest {
 8303                            s.delete(s.newest_anchor().id);
 8304                        }
 8305                        s.insert_range(next_selected_range);
 8306                    });
 8307                } else {
 8308                    select_prev_state.done = true;
 8309                }
 8310            }
 8311
 8312            self.select_prev_state = Some(select_prev_state);
 8313        } else {
 8314            let mut only_carets = true;
 8315            let mut same_text_selected = true;
 8316            let mut selected_text = None;
 8317
 8318            let mut selections_iter = selections.iter().peekable();
 8319            while let Some(selection) = selections_iter.next() {
 8320                if selection.start != selection.end {
 8321                    only_carets = false;
 8322                }
 8323
 8324                if same_text_selected {
 8325                    if selected_text.is_none() {
 8326                        selected_text =
 8327                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8328                    }
 8329
 8330                    if let Some(next_selection) = selections_iter.peek() {
 8331                        if next_selection.range().len() == selection.range().len() {
 8332                            let next_selected_text = buffer
 8333                                .text_for_range(next_selection.range())
 8334                                .collect::<String>();
 8335                            if Some(next_selected_text) != selected_text {
 8336                                same_text_selected = false;
 8337                                selected_text = None;
 8338                            }
 8339                        } else {
 8340                            same_text_selected = false;
 8341                            selected_text = None;
 8342                        }
 8343                    }
 8344                }
 8345            }
 8346
 8347            if only_carets {
 8348                for selection in &mut selections {
 8349                    let word_range = movement::surrounding_word(
 8350                        &display_map,
 8351                        selection.start.to_display_point(&display_map),
 8352                    );
 8353                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8354                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8355                    selection.goal = SelectionGoal::None;
 8356                    selection.reversed = false;
 8357                }
 8358                if selections.len() == 1 {
 8359                    let selection = selections
 8360                        .last()
 8361                        .expect("ensured that there's only one selection");
 8362                    let query = buffer
 8363                        .text_for_range(selection.start..selection.end)
 8364                        .collect::<String>();
 8365                    let is_empty = query.is_empty();
 8366                    let select_state = SelectNextState {
 8367                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8368                        wordwise: true,
 8369                        done: is_empty,
 8370                    };
 8371                    self.select_prev_state = Some(select_state);
 8372                } else {
 8373                    self.select_prev_state = None;
 8374                }
 8375
 8376                self.unfold_ranges(
 8377                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8378                    false,
 8379                    true,
 8380                    cx,
 8381                );
 8382                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8383                    s.select(selections);
 8384                });
 8385            } else if let Some(selected_text) = selected_text {
 8386                self.select_prev_state = Some(SelectNextState {
 8387                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8388                    wordwise: false,
 8389                    done: false,
 8390                });
 8391                self.select_previous(action, cx)?;
 8392            }
 8393        }
 8394        Ok(())
 8395    }
 8396
 8397    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8398        if self.read_only(cx) {
 8399            return;
 8400        }
 8401        let text_layout_details = &self.text_layout_details(cx);
 8402        self.transact(cx, |this, cx| {
 8403            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8404            let mut edits = Vec::new();
 8405            let mut selection_edit_ranges = Vec::new();
 8406            let mut last_toggled_row = None;
 8407            let snapshot = this.buffer.read(cx).read(cx);
 8408            let empty_str: Arc<str> = Arc::default();
 8409            let mut suffixes_inserted = Vec::new();
 8410            let ignore_indent = action.ignore_indent;
 8411
 8412            fn comment_prefix_range(
 8413                snapshot: &MultiBufferSnapshot,
 8414                row: MultiBufferRow,
 8415                comment_prefix: &str,
 8416                comment_prefix_whitespace: &str,
 8417                ignore_indent: bool,
 8418            ) -> Range<Point> {
 8419                let indent_size = if ignore_indent {
 8420                    0
 8421                } else {
 8422                    snapshot.indent_size_for_line(row).len
 8423                };
 8424
 8425                let start = Point::new(row.0, indent_size);
 8426
 8427                let mut line_bytes = snapshot
 8428                    .bytes_in_range(start..snapshot.max_point())
 8429                    .flatten()
 8430                    .copied();
 8431
 8432                // If this line currently begins with the line comment prefix, then record
 8433                // the range containing the prefix.
 8434                if line_bytes
 8435                    .by_ref()
 8436                    .take(comment_prefix.len())
 8437                    .eq(comment_prefix.bytes())
 8438                {
 8439                    // Include any whitespace that matches the comment prefix.
 8440                    let matching_whitespace_len = line_bytes
 8441                        .zip(comment_prefix_whitespace.bytes())
 8442                        .take_while(|(a, b)| a == b)
 8443                        .count() as u32;
 8444                    let end = Point::new(
 8445                        start.row,
 8446                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8447                    );
 8448                    start..end
 8449                } else {
 8450                    start..start
 8451                }
 8452            }
 8453
 8454            fn comment_suffix_range(
 8455                snapshot: &MultiBufferSnapshot,
 8456                row: MultiBufferRow,
 8457                comment_suffix: &str,
 8458                comment_suffix_has_leading_space: bool,
 8459            ) -> Range<Point> {
 8460                let end = Point::new(row.0, snapshot.line_len(row));
 8461                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8462
 8463                let mut line_end_bytes = snapshot
 8464                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8465                    .flatten()
 8466                    .copied();
 8467
 8468                let leading_space_len = if suffix_start_column > 0
 8469                    && line_end_bytes.next() == Some(b' ')
 8470                    && comment_suffix_has_leading_space
 8471                {
 8472                    1
 8473                } else {
 8474                    0
 8475                };
 8476
 8477                // If this line currently begins with the line comment prefix, then record
 8478                // the range containing the prefix.
 8479                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8480                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8481                    start..end
 8482                } else {
 8483                    end..end
 8484                }
 8485            }
 8486
 8487            // TODO: Handle selections that cross excerpts
 8488            for selection in &mut selections {
 8489                let start_column = snapshot
 8490                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8491                    .len;
 8492                let language = if let Some(language) =
 8493                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8494                {
 8495                    language
 8496                } else {
 8497                    continue;
 8498                };
 8499
 8500                selection_edit_ranges.clear();
 8501
 8502                // If multiple selections contain a given row, avoid processing that
 8503                // row more than once.
 8504                let mut start_row = MultiBufferRow(selection.start.row);
 8505                if last_toggled_row == Some(start_row) {
 8506                    start_row = start_row.next_row();
 8507                }
 8508                let end_row =
 8509                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8510                        MultiBufferRow(selection.end.row - 1)
 8511                    } else {
 8512                        MultiBufferRow(selection.end.row)
 8513                    };
 8514                last_toggled_row = Some(end_row);
 8515
 8516                if start_row > end_row {
 8517                    continue;
 8518                }
 8519
 8520                // If the language has line comments, toggle those.
 8521                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8522
 8523                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8524                if ignore_indent {
 8525                    full_comment_prefixes = full_comment_prefixes
 8526                        .into_iter()
 8527                        .map(|s| Arc::from(s.trim_end()))
 8528                        .collect();
 8529                }
 8530
 8531                if !full_comment_prefixes.is_empty() {
 8532                    let first_prefix = full_comment_prefixes
 8533                        .first()
 8534                        .expect("prefixes is non-empty");
 8535                    let prefix_trimmed_lengths = full_comment_prefixes
 8536                        .iter()
 8537                        .map(|p| p.trim_end_matches(' ').len())
 8538                        .collect::<SmallVec<[usize; 4]>>();
 8539
 8540                    let mut all_selection_lines_are_comments = true;
 8541
 8542                    for row in start_row.0..=end_row.0 {
 8543                        let row = MultiBufferRow(row);
 8544                        if start_row < end_row && snapshot.is_line_blank(row) {
 8545                            continue;
 8546                        }
 8547
 8548                        let prefix_range = full_comment_prefixes
 8549                            .iter()
 8550                            .zip(prefix_trimmed_lengths.iter().copied())
 8551                            .map(|(prefix, trimmed_prefix_len)| {
 8552                                comment_prefix_range(
 8553                                    snapshot.deref(),
 8554                                    row,
 8555                                    &prefix[..trimmed_prefix_len],
 8556                                    &prefix[trimmed_prefix_len..],
 8557                                    ignore_indent,
 8558                                )
 8559                            })
 8560                            .max_by_key(|range| range.end.column - range.start.column)
 8561                            .expect("prefixes is non-empty");
 8562
 8563                        if prefix_range.is_empty() {
 8564                            all_selection_lines_are_comments = false;
 8565                        }
 8566
 8567                        selection_edit_ranges.push(prefix_range);
 8568                    }
 8569
 8570                    if all_selection_lines_are_comments {
 8571                        edits.extend(
 8572                            selection_edit_ranges
 8573                                .iter()
 8574                                .cloned()
 8575                                .map(|range| (range, empty_str.clone())),
 8576                        );
 8577                    } else {
 8578                        let min_column = selection_edit_ranges
 8579                            .iter()
 8580                            .map(|range| range.start.column)
 8581                            .min()
 8582                            .unwrap_or(0);
 8583                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8584                            let position = Point::new(range.start.row, min_column);
 8585                            (position..position, first_prefix.clone())
 8586                        }));
 8587                    }
 8588                } else if let Some((full_comment_prefix, comment_suffix)) =
 8589                    language.block_comment_delimiters()
 8590                {
 8591                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8592                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8593                    let prefix_range = comment_prefix_range(
 8594                        snapshot.deref(),
 8595                        start_row,
 8596                        comment_prefix,
 8597                        comment_prefix_whitespace,
 8598                        ignore_indent,
 8599                    );
 8600                    let suffix_range = comment_suffix_range(
 8601                        snapshot.deref(),
 8602                        end_row,
 8603                        comment_suffix.trim_start_matches(' '),
 8604                        comment_suffix.starts_with(' '),
 8605                    );
 8606
 8607                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8608                        edits.push((
 8609                            prefix_range.start..prefix_range.start,
 8610                            full_comment_prefix.clone(),
 8611                        ));
 8612                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8613                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8614                    } else {
 8615                        edits.push((prefix_range, empty_str.clone()));
 8616                        edits.push((suffix_range, empty_str.clone()));
 8617                    }
 8618                } else {
 8619                    continue;
 8620                }
 8621            }
 8622
 8623            drop(snapshot);
 8624            this.buffer.update(cx, |buffer, cx| {
 8625                buffer.edit(edits, None, cx);
 8626            });
 8627
 8628            // Adjust selections so that they end before any comment suffixes that
 8629            // were inserted.
 8630            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8631            let mut selections = this.selections.all::<Point>(cx);
 8632            let snapshot = this.buffer.read(cx).read(cx);
 8633            for selection in &mut selections {
 8634                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8635                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8636                        Ordering::Less => {
 8637                            suffixes_inserted.next();
 8638                            continue;
 8639                        }
 8640                        Ordering::Greater => break,
 8641                        Ordering::Equal => {
 8642                            if selection.end.column == snapshot.line_len(row) {
 8643                                if selection.is_empty() {
 8644                                    selection.start.column -= suffix_len as u32;
 8645                                }
 8646                                selection.end.column -= suffix_len as u32;
 8647                            }
 8648                            break;
 8649                        }
 8650                    }
 8651                }
 8652            }
 8653
 8654            drop(snapshot);
 8655            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8656
 8657            let selections = this.selections.all::<Point>(cx);
 8658            let selections_on_single_row = selections.windows(2).all(|selections| {
 8659                selections[0].start.row == selections[1].start.row
 8660                    && selections[0].end.row == selections[1].end.row
 8661                    && selections[0].start.row == selections[0].end.row
 8662            });
 8663            let selections_selecting = selections
 8664                .iter()
 8665                .any(|selection| selection.start != selection.end);
 8666            let advance_downwards = action.advance_downwards
 8667                && selections_on_single_row
 8668                && !selections_selecting
 8669                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8670
 8671            if advance_downwards {
 8672                let snapshot = this.buffer.read(cx).snapshot(cx);
 8673
 8674                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8675                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8676                        let mut point = display_point.to_point(display_snapshot);
 8677                        point.row += 1;
 8678                        point = snapshot.clip_point(point, Bias::Left);
 8679                        let display_point = point.to_display_point(display_snapshot);
 8680                        let goal = SelectionGoal::HorizontalPosition(
 8681                            display_snapshot
 8682                                .x_for_display_point(display_point, text_layout_details)
 8683                                .into(),
 8684                        );
 8685                        (display_point, goal)
 8686                    })
 8687                });
 8688            }
 8689        });
 8690    }
 8691
 8692    pub fn select_enclosing_symbol(
 8693        &mut self,
 8694        _: &SelectEnclosingSymbol,
 8695        cx: &mut ViewContext<Self>,
 8696    ) {
 8697        let buffer = self.buffer.read(cx).snapshot(cx);
 8698        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8699
 8700        fn update_selection(
 8701            selection: &Selection<usize>,
 8702            buffer_snap: &MultiBufferSnapshot,
 8703        ) -> Option<Selection<usize>> {
 8704            let cursor = selection.head();
 8705            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8706            for symbol in symbols.iter().rev() {
 8707                let start = symbol.range.start.to_offset(buffer_snap);
 8708                let end = symbol.range.end.to_offset(buffer_snap);
 8709                let new_range = start..end;
 8710                if start < selection.start || end > selection.end {
 8711                    return Some(Selection {
 8712                        id: selection.id,
 8713                        start: new_range.start,
 8714                        end: new_range.end,
 8715                        goal: SelectionGoal::None,
 8716                        reversed: selection.reversed,
 8717                    });
 8718                }
 8719            }
 8720            None
 8721        }
 8722
 8723        let mut selected_larger_symbol = false;
 8724        let new_selections = old_selections
 8725            .iter()
 8726            .map(|selection| match update_selection(selection, &buffer) {
 8727                Some(new_selection) => {
 8728                    if new_selection.range() != selection.range() {
 8729                        selected_larger_symbol = true;
 8730                    }
 8731                    new_selection
 8732                }
 8733                None => selection.clone(),
 8734            })
 8735            .collect::<Vec<_>>();
 8736
 8737        if selected_larger_symbol {
 8738            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8739                s.select(new_selections);
 8740            });
 8741        }
 8742    }
 8743
 8744    pub fn select_larger_syntax_node(
 8745        &mut self,
 8746        _: &SelectLargerSyntaxNode,
 8747        cx: &mut ViewContext<Self>,
 8748    ) {
 8749        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8750        let buffer = self.buffer.read(cx).snapshot(cx);
 8751        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8752
 8753        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8754        let mut selected_larger_node = false;
 8755        let new_selections = old_selections
 8756            .iter()
 8757            .map(|selection| {
 8758                let old_range = selection.start..selection.end;
 8759                let mut new_range = old_range.clone();
 8760                while let Some(containing_range) =
 8761                    buffer.range_for_syntax_ancestor(new_range.clone())
 8762                {
 8763                    new_range = containing_range;
 8764                    if !display_map.intersects_fold(new_range.start)
 8765                        && !display_map.intersects_fold(new_range.end)
 8766                    {
 8767                        break;
 8768                    }
 8769                }
 8770
 8771                selected_larger_node |= new_range != old_range;
 8772                Selection {
 8773                    id: selection.id,
 8774                    start: new_range.start,
 8775                    end: new_range.end,
 8776                    goal: SelectionGoal::None,
 8777                    reversed: selection.reversed,
 8778                }
 8779            })
 8780            .collect::<Vec<_>>();
 8781
 8782        if selected_larger_node {
 8783            stack.push(old_selections);
 8784            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8785                s.select(new_selections);
 8786            });
 8787        }
 8788        self.select_larger_syntax_node_stack = stack;
 8789    }
 8790
 8791    pub fn select_smaller_syntax_node(
 8792        &mut self,
 8793        _: &SelectSmallerSyntaxNode,
 8794        cx: &mut ViewContext<Self>,
 8795    ) {
 8796        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8797        if let Some(selections) = stack.pop() {
 8798            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8799                s.select(selections.to_vec());
 8800            });
 8801        }
 8802        self.select_larger_syntax_node_stack = stack;
 8803    }
 8804
 8805    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8806        if !EditorSettings::get_global(cx).gutter.runnables {
 8807            self.clear_tasks();
 8808            return Task::ready(());
 8809        }
 8810        let project = self.project.as_ref().map(Model::downgrade);
 8811        cx.spawn(|this, mut cx| async move {
 8812            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8813            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8814                return;
 8815            };
 8816            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8817                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8818            }) else {
 8819                return;
 8820            };
 8821
 8822            let hide_runnables = project
 8823                .update(&mut cx, |project, cx| {
 8824                    // Do not display any test indicators in non-dev server remote projects.
 8825                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8826                })
 8827                .unwrap_or(true);
 8828            if hide_runnables {
 8829                return;
 8830            }
 8831            let new_rows =
 8832                cx.background_executor()
 8833                    .spawn({
 8834                        let snapshot = display_snapshot.clone();
 8835                        async move {
 8836                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8837                        }
 8838                    })
 8839                    .await;
 8840            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8841
 8842            this.update(&mut cx, |this, _| {
 8843                this.clear_tasks();
 8844                for (key, value) in rows {
 8845                    this.insert_tasks(key, value);
 8846                }
 8847            })
 8848            .ok();
 8849        })
 8850    }
 8851    fn fetch_runnable_ranges(
 8852        snapshot: &DisplaySnapshot,
 8853        range: Range<Anchor>,
 8854    ) -> Vec<language::RunnableRange> {
 8855        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8856    }
 8857
 8858    fn runnable_rows(
 8859        project: Model<Project>,
 8860        snapshot: DisplaySnapshot,
 8861        runnable_ranges: Vec<RunnableRange>,
 8862        mut cx: AsyncWindowContext,
 8863    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8864        runnable_ranges
 8865            .into_iter()
 8866            .filter_map(|mut runnable| {
 8867                let tasks = cx
 8868                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8869                    .ok()?;
 8870                if tasks.is_empty() {
 8871                    return None;
 8872                }
 8873
 8874                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8875
 8876                let row = snapshot
 8877                    .buffer_snapshot
 8878                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8879                    .1
 8880                    .start
 8881                    .row;
 8882
 8883                let context_range =
 8884                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8885                Some((
 8886                    (runnable.buffer_id, row),
 8887                    RunnableTasks {
 8888                        templates: tasks,
 8889                        offset: MultiBufferOffset(runnable.run_range.start),
 8890                        context_range,
 8891                        column: point.column,
 8892                        extra_variables: runnable.extra_captures,
 8893                    },
 8894                ))
 8895            })
 8896            .collect()
 8897    }
 8898
 8899    fn templates_with_tags(
 8900        project: &Model<Project>,
 8901        runnable: &mut Runnable,
 8902        cx: &WindowContext<'_>,
 8903    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8904        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8905            let (worktree_id, file) = project
 8906                .buffer_for_id(runnable.buffer, cx)
 8907                .and_then(|buffer| buffer.read(cx).file())
 8908                .map(|file| (file.worktree_id(cx), file.clone()))
 8909                .unzip();
 8910
 8911            (
 8912                project.task_store().read(cx).task_inventory().cloned(),
 8913                worktree_id,
 8914                file,
 8915            )
 8916        });
 8917
 8918        let tags = mem::take(&mut runnable.tags);
 8919        let mut tags: Vec<_> = tags
 8920            .into_iter()
 8921            .flat_map(|tag| {
 8922                let tag = tag.0.clone();
 8923                inventory
 8924                    .as_ref()
 8925                    .into_iter()
 8926                    .flat_map(|inventory| {
 8927                        inventory.read(cx).list_tasks(
 8928                            file.clone(),
 8929                            Some(runnable.language.clone()),
 8930                            worktree_id,
 8931                            cx,
 8932                        )
 8933                    })
 8934                    .filter(move |(_, template)| {
 8935                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8936                    })
 8937            })
 8938            .sorted_by_key(|(kind, _)| kind.to_owned())
 8939            .collect();
 8940        if let Some((leading_tag_source, _)) = tags.first() {
 8941            // Strongest source wins; if we have worktree tag binding, prefer that to
 8942            // global and language bindings;
 8943            // if we have a global binding, prefer that to language binding.
 8944            let first_mismatch = tags
 8945                .iter()
 8946                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8947            if let Some(index) = first_mismatch {
 8948                tags.truncate(index);
 8949            }
 8950        }
 8951
 8952        tags
 8953    }
 8954
 8955    pub fn move_to_enclosing_bracket(
 8956        &mut self,
 8957        _: &MoveToEnclosingBracket,
 8958        cx: &mut ViewContext<Self>,
 8959    ) {
 8960        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8961            s.move_offsets_with(|snapshot, selection| {
 8962                let Some(enclosing_bracket_ranges) =
 8963                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8964                else {
 8965                    return;
 8966                };
 8967
 8968                let mut best_length = usize::MAX;
 8969                let mut best_inside = false;
 8970                let mut best_in_bracket_range = false;
 8971                let mut best_destination = None;
 8972                for (open, close) in enclosing_bracket_ranges {
 8973                    let close = close.to_inclusive();
 8974                    let length = close.end() - open.start;
 8975                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8976                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8977                        || close.contains(&selection.head());
 8978
 8979                    // If best is next to a bracket and current isn't, skip
 8980                    if !in_bracket_range && best_in_bracket_range {
 8981                        continue;
 8982                    }
 8983
 8984                    // Prefer smaller lengths unless best is inside and current isn't
 8985                    if length > best_length && (best_inside || !inside) {
 8986                        continue;
 8987                    }
 8988
 8989                    best_length = length;
 8990                    best_inside = inside;
 8991                    best_in_bracket_range = in_bracket_range;
 8992                    best_destination = Some(
 8993                        if close.contains(&selection.start) && close.contains(&selection.end) {
 8994                            if inside {
 8995                                open.end
 8996                            } else {
 8997                                open.start
 8998                            }
 8999                        } else if inside {
 9000                            *close.start()
 9001                        } else {
 9002                            *close.end()
 9003                        },
 9004                    );
 9005                }
 9006
 9007                if let Some(destination) = best_destination {
 9008                    selection.collapse_to(destination, SelectionGoal::None);
 9009                }
 9010            })
 9011        });
 9012    }
 9013
 9014    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9015        self.end_selection(cx);
 9016        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9017        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9018            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9019            self.select_next_state = entry.select_next_state;
 9020            self.select_prev_state = entry.select_prev_state;
 9021            self.add_selections_state = entry.add_selections_state;
 9022            self.request_autoscroll(Autoscroll::newest(), cx);
 9023        }
 9024        self.selection_history.mode = SelectionHistoryMode::Normal;
 9025    }
 9026
 9027    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9028        self.end_selection(cx);
 9029        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9030        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9031            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9032            self.select_next_state = entry.select_next_state;
 9033            self.select_prev_state = entry.select_prev_state;
 9034            self.add_selections_state = entry.add_selections_state;
 9035            self.request_autoscroll(Autoscroll::newest(), cx);
 9036        }
 9037        self.selection_history.mode = SelectionHistoryMode::Normal;
 9038    }
 9039
 9040    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9041        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9042    }
 9043
 9044    pub fn expand_excerpts_down(
 9045        &mut self,
 9046        action: &ExpandExcerptsDown,
 9047        cx: &mut ViewContext<Self>,
 9048    ) {
 9049        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9050    }
 9051
 9052    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9053        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9054    }
 9055
 9056    pub fn expand_excerpts_for_direction(
 9057        &mut self,
 9058        lines: u32,
 9059        direction: ExpandExcerptDirection,
 9060        cx: &mut ViewContext<Self>,
 9061    ) {
 9062        let selections = self.selections.disjoint_anchors();
 9063
 9064        let lines = if lines == 0 {
 9065            EditorSettings::get_global(cx).expand_excerpt_lines
 9066        } else {
 9067            lines
 9068        };
 9069
 9070        self.buffer.update(cx, |buffer, cx| {
 9071            buffer.expand_excerpts(
 9072                selections
 9073                    .iter()
 9074                    .map(|selection| selection.head().excerpt_id)
 9075                    .dedup(),
 9076                lines,
 9077                direction,
 9078                cx,
 9079            )
 9080        })
 9081    }
 9082
 9083    pub fn expand_excerpt(
 9084        &mut self,
 9085        excerpt: ExcerptId,
 9086        direction: ExpandExcerptDirection,
 9087        cx: &mut ViewContext<Self>,
 9088    ) {
 9089        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9090        self.buffer.update(cx, |buffer, cx| {
 9091            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9092        })
 9093    }
 9094
 9095    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9096        self.go_to_diagnostic_impl(Direction::Next, cx)
 9097    }
 9098
 9099    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9100        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9101    }
 9102
 9103    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9104        let buffer = self.buffer.read(cx).snapshot(cx);
 9105        let selection = self.selections.newest::<usize>(cx);
 9106
 9107        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9108        if direction == Direction::Next {
 9109            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9110                let (group_id, jump_to) = popover.activation_info();
 9111                if self.activate_diagnostics(group_id, cx) {
 9112                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9113                        let mut new_selection = s.newest_anchor().clone();
 9114                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9115                        s.select_anchors(vec![new_selection.clone()]);
 9116                    });
 9117                }
 9118                return;
 9119            }
 9120        }
 9121
 9122        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9123            active_diagnostics
 9124                .primary_range
 9125                .to_offset(&buffer)
 9126                .to_inclusive()
 9127        });
 9128        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9129            if active_primary_range.contains(&selection.head()) {
 9130                *active_primary_range.start()
 9131            } else {
 9132                selection.head()
 9133            }
 9134        } else {
 9135            selection.head()
 9136        };
 9137        let snapshot = self.snapshot(cx);
 9138        loop {
 9139            let diagnostics = if direction == Direction::Prev {
 9140                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9141            } else {
 9142                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9143            }
 9144            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9145            let group = diagnostics
 9146                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9147                // be sorted in a stable way
 9148                // skip until we are at current active diagnostic, if it exists
 9149                .skip_while(|entry| {
 9150                    (match direction {
 9151                        Direction::Prev => entry.range.start >= search_start,
 9152                        Direction::Next => entry.range.start <= search_start,
 9153                    }) && self
 9154                        .active_diagnostics
 9155                        .as_ref()
 9156                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9157                })
 9158                .find_map(|entry| {
 9159                    if entry.diagnostic.is_primary
 9160                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9161                        && !entry.range.is_empty()
 9162                        // if we match with the active diagnostic, skip it
 9163                        && Some(entry.diagnostic.group_id)
 9164                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9165                    {
 9166                        Some((entry.range, entry.diagnostic.group_id))
 9167                    } else {
 9168                        None
 9169                    }
 9170                });
 9171
 9172            if let Some((primary_range, group_id)) = group {
 9173                if self.activate_diagnostics(group_id, cx) {
 9174                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9175                        s.select(vec![Selection {
 9176                            id: selection.id,
 9177                            start: primary_range.start,
 9178                            end: primary_range.start,
 9179                            reversed: false,
 9180                            goal: SelectionGoal::None,
 9181                        }]);
 9182                    });
 9183                }
 9184                break;
 9185            } else {
 9186                // Cycle around to the start of the buffer, potentially moving back to the start of
 9187                // the currently active diagnostic.
 9188                active_primary_range.take();
 9189                if direction == Direction::Prev {
 9190                    if search_start == buffer.len() {
 9191                        break;
 9192                    } else {
 9193                        search_start = buffer.len();
 9194                    }
 9195                } else if search_start == 0 {
 9196                    break;
 9197                } else {
 9198                    search_start = 0;
 9199                }
 9200            }
 9201        }
 9202    }
 9203
 9204    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9205        let snapshot = self.snapshot(cx);
 9206        let selection = self.selections.newest::<Point>(cx);
 9207        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9208    }
 9209
 9210    fn go_to_hunk_after_position(
 9211        &mut self,
 9212        snapshot: &EditorSnapshot,
 9213        position: Point,
 9214        cx: &mut ViewContext<'_, Editor>,
 9215    ) -> Option<MultiBufferDiffHunk> {
 9216        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9217            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9218                snapshot,
 9219                position,
 9220                ix > 0,
 9221                snapshot.diff_map.diff_hunks_in_range(
 9222                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9223                    &snapshot.buffer_snapshot,
 9224                ),
 9225                cx,
 9226            ) {
 9227                return Some(hunk);
 9228            }
 9229        }
 9230        None
 9231    }
 9232
 9233    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9234        let snapshot = self.snapshot(cx);
 9235        let selection = self.selections.newest::<Point>(cx);
 9236        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9237    }
 9238
 9239    fn go_to_hunk_before_position(
 9240        &mut self,
 9241        snapshot: &EditorSnapshot,
 9242        position: Point,
 9243        cx: &mut ViewContext<'_, Editor>,
 9244    ) -> Option<MultiBufferDiffHunk> {
 9245        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9246            .into_iter()
 9247            .enumerate()
 9248        {
 9249            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9250                snapshot,
 9251                position,
 9252                ix > 0,
 9253                snapshot
 9254                    .diff_map
 9255                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9256                cx,
 9257            ) {
 9258                return Some(hunk);
 9259            }
 9260        }
 9261        None
 9262    }
 9263
 9264    fn go_to_next_hunk_in_direction(
 9265        &mut self,
 9266        snapshot: &DisplaySnapshot,
 9267        initial_point: Point,
 9268        is_wrapped: bool,
 9269        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9270        cx: &mut ViewContext<Editor>,
 9271    ) -> Option<MultiBufferDiffHunk> {
 9272        let display_point = initial_point.to_display_point(snapshot);
 9273        let mut hunks = hunks
 9274            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9275            .filter(|(display_hunk, _)| {
 9276                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9277            })
 9278            .dedup();
 9279
 9280        if let Some((display_hunk, hunk)) = hunks.next() {
 9281            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9282                let row = display_hunk.start_display_row();
 9283                let point = DisplayPoint::new(row, 0);
 9284                s.select_display_ranges([point..point]);
 9285            });
 9286
 9287            Some(hunk)
 9288        } else {
 9289            None
 9290        }
 9291    }
 9292
 9293    pub fn go_to_definition(
 9294        &mut self,
 9295        _: &GoToDefinition,
 9296        cx: &mut ViewContext<Self>,
 9297    ) -> Task<Result<Navigated>> {
 9298        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9299        cx.spawn(|editor, mut cx| async move {
 9300            if definition.await? == Navigated::Yes {
 9301                return Ok(Navigated::Yes);
 9302            }
 9303            match editor.update(&mut cx, |editor, cx| {
 9304                editor.find_all_references(&FindAllReferences, cx)
 9305            })? {
 9306                Some(references) => references.await,
 9307                None => Ok(Navigated::No),
 9308            }
 9309        })
 9310    }
 9311
 9312    pub fn go_to_declaration(
 9313        &mut self,
 9314        _: &GoToDeclaration,
 9315        cx: &mut ViewContext<Self>,
 9316    ) -> Task<Result<Navigated>> {
 9317        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9318    }
 9319
 9320    pub fn go_to_declaration_split(
 9321        &mut self,
 9322        _: &GoToDeclaration,
 9323        cx: &mut ViewContext<Self>,
 9324    ) -> Task<Result<Navigated>> {
 9325        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9326    }
 9327
 9328    pub fn go_to_implementation(
 9329        &mut self,
 9330        _: &GoToImplementation,
 9331        cx: &mut ViewContext<Self>,
 9332    ) -> Task<Result<Navigated>> {
 9333        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9334    }
 9335
 9336    pub fn go_to_implementation_split(
 9337        &mut self,
 9338        _: &GoToImplementationSplit,
 9339        cx: &mut ViewContext<Self>,
 9340    ) -> Task<Result<Navigated>> {
 9341        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9342    }
 9343
 9344    pub fn go_to_type_definition(
 9345        &mut self,
 9346        _: &GoToTypeDefinition,
 9347        cx: &mut ViewContext<Self>,
 9348    ) -> Task<Result<Navigated>> {
 9349        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9350    }
 9351
 9352    pub fn go_to_definition_split(
 9353        &mut self,
 9354        _: &GoToDefinitionSplit,
 9355        cx: &mut ViewContext<Self>,
 9356    ) -> Task<Result<Navigated>> {
 9357        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9358    }
 9359
 9360    pub fn go_to_type_definition_split(
 9361        &mut self,
 9362        _: &GoToTypeDefinitionSplit,
 9363        cx: &mut ViewContext<Self>,
 9364    ) -> Task<Result<Navigated>> {
 9365        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9366    }
 9367
 9368    fn go_to_definition_of_kind(
 9369        &mut self,
 9370        kind: GotoDefinitionKind,
 9371        split: bool,
 9372        cx: &mut ViewContext<Self>,
 9373    ) -> Task<Result<Navigated>> {
 9374        let Some(provider) = self.semantics_provider.clone() else {
 9375            return Task::ready(Ok(Navigated::No));
 9376        };
 9377        let head = self.selections.newest::<usize>(cx).head();
 9378        let buffer = self.buffer.read(cx);
 9379        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9380            text_anchor
 9381        } else {
 9382            return Task::ready(Ok(Navigated::No));
 9383        };
 9384
 9385        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9386            return Task::ready(Ok(Navigated::No));
 9387        };
 9388
 9389        cx.spawn(|editor, mut cx| async move {
 9390            let definitions = definitions.await?;
 9391            let navigated = editor
 9392                .update(&mut cx, |editor, cx| {
 9393                    editor.navigate_to_hover_links(
 9394                        Some(kind),
 9395                        definitions
 9396                            .into_iter()
 9397                            .filter(|location| {
 9398                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9399                            })
 9400                            .map(HoverLink::Text)
 9401                            .collect::<Vec<_>>(),
 9402                        split,
 9403                        cx,
 9404                    )
 9405                })?
 9406                .await?;
 9407            anyhow::Ok(navigated)
 9408        })
 9409    }
 9410
 9411    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9412        let selection = self.selections.newest_anchor();
 9413        let head = selection.head();
 9414        let tail = selection.tail();
 9415
 9416        let Some((buffer, start_position)) =
 9417            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9418        else {
 9419            return;
 9420        };
 9421
 9422        let end_position = if head != tail {
 9423            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9424                return;
 9425            };
 9426            Some(pos)
 9427        } else {
 9428            None
 9429        };
 9430
 9431        let url_finder = cx.spawn(|editor, mut cx| async move {
 9432            let url = if let Some(end_pos) = end_position {
 9433                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9434            } else {
 9435                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9436            };
 9437
 9438            if let Some(url) = url {
 9439                editor.update(&mut cx, |_, cx| {
 9440                    cx.open_url(&url);
 9441                })
 9442            } else {
 9443                Ok(())
 9444            }
 9445        });
 9446
 9447        url_finder.detach();
 9448    }
 9449
 9450    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9451        let Some(workspace) = self.workspace() else {
 9452            return;
 9453        };
 9454
 9455        let position = self.selections.newest_anchor().head();
 9456
 9457        let Some((buffer, buffer_position)) =
 9458            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9459        else {
 9460            return;
 9461        };
 9462
 9463        let project = self.project.clone();
 9464
 9465        cx.spawn(|_, mut cx| async move {
 9466            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9467
 9468            if let Some((_, path)) = result {
 9469                workspace
 9470                    .update(&mut cx, |workspace, cx| {
 9471                        workspace.open_resolved_path(path, cx)
 9472                    })?
 9473                    .await?;
 9474            }
 9475            anyhow::Ok(())
 9476        })
 9477        .detach();
 9478    }
 9479
 9480    pub(crate) fn navigate_to_hover_links(
 9481        &mut self,
 9482        kind: Option<GotoDefinitionKind>,
 9483        mut definitions: Vec<HoverLink>,
 9484        split: bool,
 9485        cx: &mut ViewContext<Editor>,
 9486    ) -> Task<Result<Navigated>> {
 9487        // If there is one definition, just open it directly
 9488        if definitions.len() == 1 {
 9489            let definition = definitions.pop().unwrap();
 9490
 9491            enum TargetTaskResult {
 9492                Location(Option<Location>),
 9493                AlreadyNavigated,
 9494            }
 9495
 9496            let target_task = match definition {
 9497                HoverLink::Text(link) => {
 9498                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9499                }
 9500                HoverLink::InlayHint(lsp_location, server_id) => {
 9501                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9502                    cx.background_executor().spawn(async move {
 9503                        let location = computation.await?;
 9504                        Ok(TargetTaskResult::Location(location))
 9505                    })
 9506                }
 9507                HoverLink::Url(url) => {
 9508                    cx.open_url(&url);
 9509                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9510                }
 9511                HoverLink::File(path) => {
 9512                    if let Some(workspace) = self.workspace() {
 9513                        cx.spawn(|_, mut cx| async move {
 9514                            workspace
 9515                                .update(&mut cx, |workspace, cx| {
 9516                                    workspace.open_resolved_path(path, cx)
 9517                                })?
 9518                                .await
 9519                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9520                        })
 9521                    } else {
 9522                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9523                    }
 9524                }
 9525            };
 9526            cx.spawn(|editor, mut cx| async move {
 9527                let target = match target_task.await.context("target resolution task")? {
 9528                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9529                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9530                    TargetTaskResult::Location(Some(target)) => target,
 9531                };
 9532
 9533                editor.update(&mut cx, |editor, cx| {
 9534                    let Some(workspace) = editor.workspace() else {
 9535                        return Navigated::No;
 9536                    };
 9537                    let pane = workspace.read(cx).active_pane().clone();
 9538
 9539                    let range = target.range.to_offset(target.buffer.read(cx));
 9540                    let range = editor.range_for_match(&range);
 9541
 9542                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9543                        let buffer = target.buffer.read(cx);
 9544                        let range = check_multiline_range(buffer, range);
 9545                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9546                            s.select_ranges([range]);
 9547                        });
 9548                    } else {
 9549                        cx.window_context().defer(move |cx| {
 9550                            let target_editor: View<Self> =
 9551                                workspace.update(cx, |workspace, cx| {
 9552                                    let pane = if split {
 9553                                        workspace.adjacent_pane(cx)
 9554                                    } else {
 9555                                        workspace.active_pane().clone()
 9556                                    };
 9557
 9558                                    workspace.open_project_item(
 9559                                        pane,
 9560                                        target.buffer.clone(),
 9561                                        true,
 9562                                        true,
 9563                                        cx,
 9564                                    )
 9565                                });
 9566                            target_editor.update(cx, |target_editor, cx| {
 9567                                // When selecting a definition in a different buffer, disable the nav history
 9568                                // to avoid creating a history entry at the previous cursor location.
 9569                                pane.update(cx, |pane, _| pane.disable_history());
 9570                                let buffer = target.buffer.read(cx);
 9571                                let range = check_multiline_range(buffer, range);
 9572                                target_editor.change_selections(
 9573                                    Some(Autoscroll::focused()),
 9574                                    cx,
 9575                                    |s| {
 9576                                        s.select_ranges([range]);
 9577                                    },
 9578                                );
 9579                                pane.update(cx, |pane, _| pane.enable_history());
 9580                            });
 9581                        });
 9582                    }
 9583                    Navigated::Yes
 9584                })
 9585            })
 9586        } else if !definitions.is_empty() {
 9587            cx.spawn(|editor, mut cx| async move {
 9588                let (title, location_tasks, workspace) = editor
 9589                    .update(&mut cx, |editor, cx| {
 9590                        let tab_kind = match kind {
 9591                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9592                            _ => "Definitions",
 9593                        };
 9594                        let title = definitions
 9595                            .iter()
 9596                            .find_map(|definition| match definition {
 9597                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9598                                    let buffer = origin.buffer.read(cx);
 9599                                    format!(
 9600                                        "{} for {}",
 9601                                        tab_kind,
 9602                                        buffer
 9603                                            .text_for_range(origin.range.clone())
 9604                                            .collect::<String>()
 9605                                    )
 9606                                }),
 9607                                HoverLink::InlayHint(_, _) => None,
 9608                                HoverLink::Url(_) => None,
 9609                                HoverLink::File(_) => None,
 9610                            })
 9611                            .unwrap_or(tab_kind.to_string());
 9612                        let location_tasks = definitions
 9613                            .into_iter()
 9614                            .map(|definition| match definition {
 9615                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9616                                HoverLink::InlayHint(lsp_location, server_id) => {
 9617                                    editor.compute_target_location(lsp_location, server_id, cx)
 9618                                }
 9619                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9620                                HoverLink::File(_) => Task::ready(Ok(None)),
 9621                            })
 9622                            .collect::<Vec<_>>();
 9623                        (title, location_tasks, editor.workspace().clone())
 9624                    })
 9625                    .context("location tasks preparation")?;
 9626
 9627                let locations = future::join_all(location_tasks)
 9628                    .await
 9629                    .into_iter()
 9630                    .filter_map(|location| location.transpose())
 9631                    .collect::<Result<_>>()
 9632                    .context("location tasks")?;
 9633
 9634                let Some(workspace) = workspace else {
 9635                    return Ok(Navigated::No);
 9636                };
 9637                let opened = workspace
 9638                    .update(&mut cx, |workspace, cx| {
 9639                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9640                    })
 9641                    .ok();
 9642
 9643                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9644            })
 9645        } else {
 9646            Task::ready(Ok(Navigated::No))
 9647        }
 9648    }
 9649
 9650    fn compute_target_location(
 9651        &self,
 9652        lsp_location: lsp::Location,
 9653        server_id: LanguageServerId,
 9654        cx: &mut ViewContext<Self>,
 9655    ) -> Task<anyhow::Result<Option<Location>>> {
 9656        let Some(project) = self.project.clone() else {
 9657            return Task::ready(Ok(None));
 9658        };
 9659
 9660        cx.spawn(move |editor, mut cx| async move {
 9661            let location_task = editor.update(&mut cx, |_, cx| {
 9662                project.update(cx, |project, cx| {
 9663                    let language_server_name = project
 9664                        .language_server_statuses(cx)
 9665                        .find(|(id, _)| server_id == *id)
 9666                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9667                    language_server_name.map(|language_server_name| {
 9668                        project.open_local_buffer_via_lsp(
 9669                            lsp_location.uri.clone(),
 9670                            server_id,
 9671                            language_server_name,
 9672                            cx,
 9673                        )
 9674                    })
 9675                })
 9676            })?;
 9677            let location = match location_task {
 9678                Some(task) => Some({
 9679                    let target_buffer_handle = task.await.context("open local buffer")?;
 9680                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9681                        let target_start = target_buffer
 9682                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9683                        let target_end = target_buffer
 9684                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9685                        target_buffer.anchor_after(target_start)
 9686                            ..target_buffer.anchor_before(target_end)
 9687                    })?;
 9688                    Location {
 9689                        buffer: target_buffer_handle,
 9690                        range,
 9691                    }
 9692                }),
 9693                None => None,
 9694            };
 9695            Ok(location)
 9696        })
 9697    }
 9698
 9699    pub fn find_all_references(
 9700        &mut self,
 9701        _: &FindAllReferences,
 9702        cx: &mut ViewContext<Self>,
 9703    ) -> Option<Task<Result<Navigated>>> {
 9704        let selection = self.selections.newest::<usize>(cx);
 9705        let multi_buffer = self.buffer.read(cx);
 9706        let head = selection.head();
 9707
 9708        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9709        let head_anchor = multi_buffer_snapshot.anchor_at(
 9710            head,
 9711            if head < selection.tail() {
 9712                Bias::Right
 9713            } else {
 9714                Bias::Left
 9715            },
 9716        );
 9717
 9718        match self
 9719            .find_all_references_task_sources
 9720            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9721        {
 9722            Ok(_) => {
 9723                log::info!(
 9724                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9725                );
 9726                return None;
 9727            }
 9728            Err(i) => {
 9729                self.find_all_references_task_sources.insert(i, head_anchor);
 9730            }
 9731        }
 9732
 9733        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9734        let workspace = self.workspace()?;
 9735        let project = workspace.read(cx).project().clone();
 9736        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9737        Some(cx.spawn(|editor, mut cx| async move {
 9738            let _cleanup = defer({
 9739                let mut cx = cx.clone();
 9740                move || {
 9741                    let _ = editor.update(&mut cx, |editor, _| {
 9742                        if let Ok(i) =
 9743                            editor
 9744                                .find_all_references_task_sources
 9745                                .binary_search_by(|anchor| {
 9746                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9747                                })
 9748                        {
 9749                            editor.find_all_references_task_sources.remove(i);
 9750                        }
 9751                    });
 9752                }
 9753            });
 9754
 9755            let locations = references.await?;
 9756            if locations.is_empty() {
 9757                return anyhow::Ok(Navigated::No);
 9758            }
 9759
 9760            workspace.update(&mut cx, |workspace, cx| {
 9761                let title = locations
 9762                    .first()
 9763                    .as_ref()
 9764                    .map(|location| {
 9765                        let buffer = location.buffer.read(cx);
 9766                        format!(
 9767                            "References to `{}`",
 9768                            buffer
 9769                                .text_for_range(location.range.clone())
 9770                                .collect::<String>()
 9771                        )
 9772                    })
 9773                    .unwrap();
 9774                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9775                Navigated::Yes
 9776            })
 9777        }))
 9778    }
 9779
 9780    /// Opens a multibuffer with the given project locations in it
 9781    pub fn open_locations_in_multibuffer(
 9782        workspace: &mut Workspace,
 9783        mut locations: Vec<Location>,
 9784        title: String,
 9785        split: bool,
 9786        cx: &mut ViewContext<Workspace>,
 9787    ) {
 9788        // If there are multiple definitions, open them in a multibuffer
 9789        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9790        let mut locations = locations.into_iter().peekable();
 9791        let mut ranges_to_highlight = Vec::new();
 9792        let capability = workspace.project().read(cx).capability();
 9793
 9794        let excerpt_buffer = cx.new_model(|cx| {
 9795            let mut multibuffer = MultiBuffer::new(capability);
 9796            while let Some(location) = locations.next() {
 9797                let buffer = location.buffer.read(cx);
 9798                let mut ranges_for_buffer = Vec::new();
 9799                let range = location.range.to_offset(buffer);
 9800                ranges_for_buffer.push(range.clone());
 9801
 9802                while let Some(next_location) = locations.peek() {
 9803                    if next_location.buffer == location.buffer {
 9804                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9805                        locations.next();
 9806                    } else {
 9807                        break;
 9808                    }
 9809                }
 9810
 9811                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9812                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9813                    location.buffer.clone(),
 9814                    ranges_for_buffer,
 9815                    DEFAULT_MULTIBUFFER_CONTEXT,
 9816                    cx,
 9817                ))
 9818            }
 9819
 9820            multibuffer.with_title(title)
 9821        });
 9822
 9823        let editor = cx.new_view(|cx| {
 9824            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9825        });
 9826        editor.update(cx, |editor, cx| {
 9827            if let Some(first_range) = ranges_to_highlight.first() {
 9828                editor.change_selections(None, cx, |selections| {
 9829                    selections.clear_disjoint();
 9830                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9831                });
 9832            }
 9833            editor.highlight_background::<Self>(
 9834                &ranges_to_highlight,
 9835                |theme| theme.editor_highlighted_line_background,
 9836                cx,
 9837            );
 9838            editor.register_buffers_with_language_servers(cx);
 9839        });
 9840
 9841        let item = Box::new(editor);
 9842        let item_id = item.item_id();
 9843
 9844        if split {
 9845            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9846        } else {
 9847            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9848                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9849                    pane.close_current_preview_item(cx)
 9850                } else {
 9851                    None
 9852                }
 9853            });
 9854            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9855        }
 9856        workspace.active_pane().update(cx, |pane, cx| {
 9857            pane.set_preview_item_id(Some(item_id), cx);
 9858        });
 9859    }
 9860
 9861    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9862        use language::ToOffset as _;
 9863
 9864        let provider = self.semantics_provider.clone()?;
 9865        let selection = self.selections.newest_anchor().clone();
 9866        let (cursor_buffer, cursor_buffer_position) = self
 9867            .buffer
 9868            .read(cx)
 9869            .text_anchor_for_position(selection.head(), cx)?;
 9870        let (tail_buffer, cursor_buffer_position_end) = self
 9871            .buffer
 9872            .read(cx)
 9873            .text_anchor_for_position(selection.tail(), cx)?;
 9874        if tail_buffer != cursor_buffer {
 9875            return None;
 9876        }
 9877
 9878        let snapshot = cursor_buffer.read(cx).snapshot();
 9879        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9880        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9881        let prepare_rename = provider
 9882            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9883            .unwrap_or_else(|| Task::ready(Ok(None)));
 9884        drop(snapshot);
 9885
 9886        Some(cx.spawn(|this, mut cx| async move {
 9887            let rename_range = if let Some(range) = prepare_rename.await? {
 9888                Some(range)
 9889            } else {
 9890                this.update(&mut cx, |this, cx| {
 9891                    let buffer = this.buffer.read(cx).snapshot(cx);
 9892                    let mut buffer_highlights = this
 9893                        .document_highlights_for_position(selection.head(), &buffer)
 9894                        .filter(|highlight| {
 9895                            highlight.start.excerpt_id == selection.head().excerpt_id
 9896                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9897                        });
 9898                    buffer_highlights
 9899                        .next()
 9900                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9901                })?
 9902            };
 9903            if let Some(rename_range) = rename_range {
 9904                this.update(&mut cx, |this, cx| {
 9905                    let snapshot = cursor_buffer.read(cx).snapshot();
 9906                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9907                    let cursor_offset_in_rename_range =
 9908                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9909                    let cursor_offset_in_rename_range_end =
 9910                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9911
 9912                    this.take_rename(false, cx);
 9913                    let buffer = this.buffer.read(cx).read(cx);
 9914                    let cursor_offset = selection.head().to_offset(&buffer);
 9915                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9916                    let rename_end = rename_start + rename_buffer_range.len();
 9917                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9918                    let mut old_highlight_id = None;
 9919                    let old_name: Arc<str> = buffer
 9920                        .chunks(rename_start..rename_end, true)
 9921                        .map(|chunk| {
 9922                            if old_highlight_id.is_none() {
 9923                                old_highlight_id = chunk.syntax_highlight_id;
 9924                            }
 9925                            chunk.text
 9926                        })
 9927                        .collect::<String>()
 9928                        .into();
 9929
 9930                    drop(buffer);
 9931
 9932                    // Position the selection in the rename editor so that it matches the current selection.
 9933                    this.show_local_selections = false;
 9934                    let rename_editor = cx.new_view(|cx| {
 9935                        let mut editor = Editor::single_line(cx);
 9936                        editor.buffer.update(cx, |buffer, cx| {
 9937                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9938                        });
 9939                        let rename_selection_range = match cursor_offset_in_rename_range
 9940                            .cmp(&cursor_offset_in_rename_range_end)
 9941                        {
 9942                            Ordering::Equal => {
 9943                                editor.select_all(&SelectAll, cx);
 9944                                return editor;
 9945                            }
 9946                            Ordering::Less => {
 9947                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9948                            }
 9949                            Ordering::Greater => {
 9950                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9951                            }
 9952                        };
 9953                        if rename_selection_range.end > old_name.len() {
 9954                            editor.select_all(&SelectAll, cx);
 9955                        } else {
 9956                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9957                                s.select_ranges([rename_selection_range]);
 9958                            });
 9959                        }
 9960                        editor
 9961                    });
 9962                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9963                        if e == &EditorEvent::Focused {
 9964                            cx.emit(EditorEvent::FocusedIn)
 9965                        }
 9966                    })
 9967                    .detach();
 9968
 9969                    let write_highlights =
 9970                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9971                    let read_highlights =
 9972                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9973                    let ranges = write_highlights
 9974                        .iter()
 9975                        .flat_map(|(_, ranges)| ranges.iter())
 9976                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9977                        .cloned()
 9978                        .collect();
 9979
 9980                    this.highlight_text::<Rename>(
 9981                        ranges,
 9982                        HighlightStyle {
 9983                            fade_out: Some(0.6),
 9984                            ..Default::default()
 9985                        },
 9986                        cx,
 9987                    );
 9988                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9989                    cx.focus(&rename_focus_handle);
 9990                    let block_id = this.insert_blocks(
 9991                        [BlockProperties {
 9992                            style: BlockStyle::Flex,
 9993                            placement: BlockPlacement::Below(range.start),
 9994                            height: 1,
 9995                            render: Arc::new({
 9996                                let rename_editor = rename_editor.clone();
 9997                                move |cx: &mut BlockContext| {
 9998                                    let mut text_style = cx.editor_style.text.clone();
 9999                                    if let Some(highlight_style) = old_highlight_id
10000                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10001                                    {
10002                                        text_style = text_style.highlight(highlight_style);
10003                                    }
10004                                    div()
10005                                        .block_mouse_down()
10006                                        .pl(cx.anchor_x)
10007                                        .child(EditorElement::new(
10008                                            &rename_editor,
10009                                            EditorStyle {
10010                                                background: cx.theme().system().transparent,
10011                                                local_player: cx.editor_style.local_player,
10012                                                text: text_style,
10013                                                scrollbar_width: cx.editor_style.scrollbar_width,
10014                                                syntax: cx.editor_style.syntax.clone(),
10015                                                status: cx.editor_style.status.clone(),
10016                                                inlay_hints_style: HighlightStyle {
10017                                                    font_weight: Some(FontWeight::BOLD),
10018                                                    ..make_inlay_hints_style(cx)
10019                                                },
10020                                                inline_completion_styles: make_suggestion_styles(
10021                                                    cx,
10022                                                ),
10023                                                ..EditorStyle::default()
10024                                            },
10025                                        ))
10026                                        .into_any_element()
10027                                }
10028                            }),
10029                            priority: 0,
10030                        }],
10031                        Some(Autoscroll::fit()),
10032                        cx,
10033                    )[0];
10034                    this.pending_rename = Some(RenameState {
10035                        range,
10036                        old_name,
10037                        editor: rename_editor,
10038                        block_id,
10039                    });
10040                })?;
10041            }
10042
10043            Ok(())
10044        }))
10045    }
10046
10047    pub fn confirm_rename(
10048        &mut self,
10049        _: &ConfirmRename,
10050        cx: &mut ViewContext<Self>,
10051    ) -> Option<Task<Result<()>>> {
10052        let rename = self.take_rename(false, cx)?;
10053        let workspace = self.workspace()?.downgrade();
10054        let (buffer, start) = self
10055            .buffer
10056            .read(cx)
10057            .text_anchor_for_position(rename.range.start, cx)?;
10058        let (end_buffer, _) = self
10059            .buffer
10060            .read(cx)
10061            .text_anchor_for_position(rename.range.end, cx)?;
10062        if buffer != end_buffer {
10063            return None;
10064        }
10065
10066        let old_name = rename.old_name;
10067        let new_name = rename.editor.read(cx).text(cx);
10068
10069        let rename = self.semantics_provider.as_ref()?.perform_rename(
10070            &buffer,
10071            start,
10072            new_name.clone(),
10073            cx,
10074        )?;
10075
10076        Some(cx.spawn(|editor, mut cx| async move {
10077            let project_transaction = rename.await?;
10078            Self::open_project_transaction(
10079                &editor,
10080                workspace,
10081                project_transaction,
10082                format!("Rename: {}{}", old_name, new_name),
10083                cx.clone(),
10084            )
10085            .await?;
10086
10087            editor.update(&mut cx, |editor, cx| {
10088                editor.refresh_document_highlights(cx);
10089            })?;
10090            Ok(())
10091        }))
10092    }
10093
10094    fn take_rename(
10095        &mut self,
10096        moving_cursor: bool,
10097        cx: &mut ViewContext<Self>,
10098    ) -> Option<RenameState> {
10099        let rename = self.pending_rename.take()?;
10100        if rename.editor.focus_handle(cx).is_focused(cx) {
10101            cx.focus(&self.focus_handle);
10102        }
10103
10104        self.remove_blocks(
10105            [rename.block_id].into_iter().collect(),
10106            Some(Autoscroll::fit()),
10107            cx,
10108        );
10109        self.clear_highlights::<Rename>(cx);
10110        self.show_local_selections = true;
10111
10112        if moving_cursor {
10113            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10114                editor.selections.newest::<usize>(cx).head()
10115            });
10116
10117            // Update the selection to match the position of the selection inside
10118            // the rename editor.
10119            let snapshot = self.buffer.read(cx).read(cx);
10120            let rename_range = rename.range.to_offset(&snapshot);
10121            let cursor_in_editor = snapshot
10122                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10123                .min(rename_range.end);
10124            drop(snapshot);
10125
10126            self.change_selections(None, cx, |s| {
10127                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10128            });
10129        } else {
10130            self.refresh_document_highlights(cx);
10131        }
10132
10133        Some(rename)
10134    }
10135
10136    pub fn pending_rename(&self) -> Option<&RenameState> {
10137        self.pending_rename.as_ref()
10138    }
10139
10140    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10141        let project = match &self.project {
10142            Some(project) => project.clone(),
10143            None => return None,
10144        };
10145
10146        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10147    }
10148
10149    fn format_selections(
10150        &mut self,
10151        _: &FormatSelections,
10152        cx: &mut ViewContext<Self>,
10153    ) -> Option<Task<Result<()>>> {
10154        let project = match &self.project {
10155            Some(project) => project.clone(),
10156            None => return None,
10157        };
10158
10159        let selections = self
10160            .selections
10161            .all_adjusted(cx)
10162            .into_iter()
10163            .filter(|s| !s.is_empty())
10164            .collect_vec();
10165
10166        Some(self.perform_format(
10167            project,
10168            FormatTrigger::Manual,
10169            FormatTarget::Ranges(selections),
10170            cx,
10171        ))
10172    }
10173
10174    fn perform_format(
10175        &mut self,
10176        project: Model<Project>,
10177        trigger: FormatTrigger,
10178        target: FormatTarget,
10179        cx: &mut ViewContext<Self>,
10180    ) -> Task<Result<()>> {
10181        let buffer = self.buffer().clone();
10182        let mut buffers = buffer.read(cx).all_buffers();
10183        if trigger == FormatTrigger::Save {
10184            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10185        }
10186
10187        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10188        let format = project.update(cx, |project, cx| {
10189            project.format(buffers, true, trigger, target, cx)
10190        });
10191
10192        cx.spawn(|_, mut cx| async move {
10193            let transaction = futures::select_biased! {
10194                () = timeout => {
10195                    log::warn!("timed out waiting for formatting");
10196                    None
10197                }
10198                transaction = format.log_err().fuse() => transaction,
10199            };
10200
10201            buffer
10202                .update(&mut cx, |buffer, cx| {
10203                    if let Some(transaction) = transaction {
10204                        if !buffer.is_singleton() {
10205                            buffer.push_transaction(&transaction.0, cx);
10206                        }
10207                    }
10208
10209                    cx.notify();
10210                })
10211                .ok();
10212
10213            Ok(())
10214        })
10215    }
10216
10217    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10218        if let Some(project) = self.project.clone() {
10219            self.buffer.update(cx, |multi_buffer, cx| {
10220                project.update(cx, |project, cx| {
10221                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10222                });
10223            })
10224        }
10225    }
10226
10227    fn cancel_language_server_work(
10228        &mut self,
10229        _: &actions::CancelLanguageServerWork,
10230        cx: &mut ViewContext<Self>,
10231    ) {
10232        if let Some(project) = self.project.clone() {
10233            self.buffer.update(cx, |multi_buffer, cx| {
10234                project.update(cx, |project, cx| {
10235                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10236                });
10237            })
10238        }
10239    }
10240
10241    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10242        cx.show_character_palette();
10243    }
10244
10245    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10246        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10247            let buffer = self.buffer.read(cx).snapshot(cx);
10248            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10249            let is_valid = buffer
10250                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10251                .any(|entry| {
10252                    entry.diagnostic.is_primary
10253                        && !entry.range.is_empty()
10254                        && entry.range.start == primary_range_start
10255                        && entry.diagnostic.message == active_diagnostics.primary_message
10256                });
10257
10258            if is_valid != active_diagnostics.is_valid {
10259                active_diagnostics.is_valid = is_valid;
10260                let mut new_styles = HashMap::default();
10261                for (block_id, diagnostic) in &active_diagnostics.blocks {
10262                    new_styles.insert(
10263                        *block_id,
10264                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10265                    );
10266                }
10267                self.display_map.update(cx, |display_map, _cx| {
10268                    display_map.replace_blocks(new_styles)
10269                });
10270            }
10271        }
10272    }
10273
10274    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10275        self.dismiss_diagnostics(cx);
10276        let snapshot = self.snapshot(cx);
10277        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10278            let buffer = self.buffer.read(cx).snapshot(cx);
10279
10280            let mut primary_range = None;
10281            let mut primary_message = None;
10282            let mut group_end = Point::zero();
10283            let diagnostic_group = buffer
10284                .diagnostic_group::<MultiBufferPoint>(group_id)
10285                .filter_map(|entry| {
10286                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10287                        && (entry.range.start.row == entry.range.end.row
10288                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10289                    {
10290                        return None;
10291                    }
10292                    if entry.range.end > group_end {
10293                        group_end = entry.range.end;
10294                    }
10295                    if entry.diagnostic.is_primary {
10296                        primary_range = Some(entry.range.clone());
10297                        primary_message = Some(entry.diagnostic.message.clone());
10298                    }
10299                    Some(entry)
10300                })
10301                .collect::<Vec<_>>();
10302            let primary_range = primary_range?;
10303            let primary_message = primary_message?;
10304            let primary_range =
10305                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10306
10307            let blocks = display_map
10308                .insert_blocks(
10309                    diagnostic_group.iter().map(|entry| {
10310                        let diagnostic = entry.diagnostic.clone();
10311                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10312                        BlockProperties {
10313                            style: BlockStyle::Fixed,
10314                            placement: BlockPlacement::Below(
10315                                buffer.anchor_after(entry.range.start),
10316                            ),
10317                            height: message_height,
10318                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10319                            priority: 0,
10320                        }
10321                    }),
10322                    cx,
10323                )
10324                .into_iter()
10325                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10326                .collect();
10327
10328            Some(ActiveDiagnosticGroup {
10329                primary_range,
10330                primary_message,
10331                group_id,
10332                blocks,
10333                is_valid: true,
10334            })
10335        });
10336        self.active_diagnostics.is_some()
10337    }
10338
10339    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10340        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10341            self.display_map.update(cx, |display_map, cx| {
10342                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10343            });
10344            cx.notify();
10345        }
10346    }
10347
10348    pub fn set_selections_from_remote(
10349        &mut self,
10350        selections: Vec<Selection<Anchor>>,
10351        pending_selection: Option<Selection<Anchor>>,
10352        cx: &mut ViewContext<Self>,
10353    ) {
10354        let old_cursor_position = self.selections.newest_anchor().head();
10355        self.selections.change_with(cx, |s| {
10356            s.select_anchors(selections);
10357            if let Some(pending_selection) = pending_selection {
10358                s.set_pending(pending_selection, SelectMode::Character);
10359            } else {
10360                s.clear_pending();
10361            }
10362        });
10363        self.selections_did_change(false, &old_cursor_position, true, cx);
10364    }
10365
10366    fn push_to_selection_history(&mut self) {
10367        self.selection_history.push(SelectionHistoryEntry {
10368            selections: self.selections.disjoint_anchors(),
10369            select_next_state: self.select_next_state.clone(),
10370            select_prev_state: self.select_prev_state.clone(),
10371            add_selections_state: self.add_selections_state.clone(),
10372        });
10373    }
10374
10375    pub fn transact(
10376        &mut self,
10377        cx: &mut ViewContext<Self>,
10378        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10379    ) -> Option<TransactionId> {
10380        self.start_transaction_at(Instant::now(), cx);
10381        update(self, cx);
10382        self.end_transaction_at(Instant::now(), cx)
10383    }
10384
10385    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10386        self.end_selection(cx);
10387        if let Some(tx_id) = self
10388            .buffer
10389            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10390        {
10391            self.selection_history
10392                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10393            cx.emit(EditorEvent::TransactionBegun {
10394                transaction_id: tx_id,
10395            })
10396        }
10397    }
10398
10399    fn end_transaction_at(
10400        &mut self,
10401        now: Instant,
10402        cx: &mut ViewContext<Self>,
10403    ) -> Option<TransactionId> {
10404        if let Some(transaction_id) = self
10405            .buffer
10406            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10407        {
10408            if let Some((_, end_selections)) =
10409                self.selection_history.transaction_mut(transaction_id)
10410            {
10411                *end_selections = Some(self.selections.disjoint_anchors());
10412            } else {
10413                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10414            }
10415
10416            cx.emit(EditorEvent::Edited { transaction_id });
10417            Some(transaction_id)
10418        } else {
10419            None
10420        }
10421    }
10422
10423    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10424        if self.is_singleton(cx) {
10425            let selection = self.selections.newest::<Point>(cx);
10426
10427            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10428            let range = if selection.is_empty() {
10429                let point = selection.head().to_display_point(&display_map);
10430                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10431                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10432                    .to_point(&display_map);
10433                start..end
10434            } else {
10435                selection.range()
10436            };
10437            if display_map.folds_in_range(range).next().is_some() {
10438                self.unfold_lines(&Default::default(), cx)
10439            } else {
10440                self.fold(&Default::default(), cx)
10441            }
10442        } else {
10443            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10444            let mut toggled_buffers = HashSet::default();
10445            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10446                self.selections
10447                    .disjoint_anchors()
10448                    .into_iter()
10449                    .map(|selection| selection.range()),
10450            ) {
10451                let buffer_id = buffer_snapshot.remote_id();
10452                if toggled_buffers.insert(buffer_id) {
10453                    if self.buffer_folded(buffer_id, cx) {
10454                        self.unfold_buffer(buffer_id, cx);
10455                    } else {
10456                        self.fold_buffer(buffer_id, cx);
10457                    }
10458                }
10459            }
10460        }
10461    }
10462
10463    pub fn toggle_fold_recursive(
10464        &mut self,
10465        _: &actions::ToggleFoldRecursive,
10466        cx: &mut ViewContext<Self>,
10467    ) {
10468        let selection = self.selections.newest::<Point>(cx);
10469
10470        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10471        let range = if selection.is_empty() {
10472            let point = selection.head().to_display_point(&display_map);
10473            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10474            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10475                .to_point(&display_map);
10476            start..end
10477        } else {
10478            selection.range()
10479        };
10480        if display_map.folds_in_range(range).next().is_some() {
10481            self.unfold_recursive(&Default::default(), cx)
10482        } else {
10483            self.fold_recursive(&Default::default(), cx)
10484        }
10485    }
10486
10487    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10488        if self.is_singleton(cx) {
10489            let mut to_fold = Vec::new();
10490            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10491            let selections = self.selections.all_adjusted(cx);
10492
10493            for selection in selections {
10494                let range = selection.range().sorted();
10495                let buffer_start_row = range.start.row;
10496
10497                if range.start.row != range.end.row {
10498                    let mut found = false;
10499                    let mut row = range.start.row;
10500                    while row <= range.end.row {
10501                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10502                        {
10503                            found = true;
10504                            row = crease.range().end.row + 1;
10505                            to_fold.push(crease);
10506                        } else {
10507                            row += 1
10508                        }
10509                    }
10510                    if found {
10511                        continue;
10512                    }
10513                }
10514
10515                for row in (0..=range.start.row).rev() {
10516                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10517                        if crease.range().end.row >= buffer_start_row {
10518                            to_fold.push(crease);
10519                            if row <= range.start.row {
10520                                break;
10521                            }
10522                        }
10523                    }
10524                }
10525            }
10526
10527            self.fold_creases(to_fold, true, cx);
10528        } else {
10529            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10530            let mut folded_buffers = HashSet::default();
10531            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10532                self.selections
10533                    .disjoint_anchors()
10534                    .into_iter()
10535                    .map(|selection| selection.range()),
10536            ) {
10537                let buffer_id = buffer_snapshot.remote_id();
10538                if folded_buffers.insert(buffer_id) {
10539                    self.fold_buffer(buffer_id, cx);
10540                }
10541            }
10542        }
10543    }
10544
10545    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10546        if !self.buffer.read(cx).is_singleton() {
10547            return;
10548        }
10549
10550        let fold_at_level = fold_at.level;
10551        let snapshot = self.buffer.read(cx).snapshot(cx);
10552        let mut to_fold = Vec::new();
10553        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10554
10555        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10556            while start_row < end_row {
10557                match self
10558                    .snapshot(cx)
10559                    .crease_for_buffer_row(MultiBufferRow(start_row))
10560                {
10561                    Some(crease) => {
10562                        let nested_start_row = crease.range().start.row + 1;
10563                        let nested_end_row = crease.range().end.row;
10564
10565                        if current_level < fold_at_level {
10566                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10567                        } else if current_level == fold_at_level {
10568                            to_fold.push(crease);
10569                        }
10570
10571                        start_row = nested_end_row + 1;
10572                    }
10573                    None => start_row += 1,
10574                }
10575            }
10576        }
10577
10578        self.fold_creases(to_fold, true, cx);
10579    }
10580
10581    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10582        if self.buffer.read(cx).is_singleton() {
10583            let mut fold_ranges = Vec::new();
10584            let snapshot = self.buffer.read(cx).snapshot(cx);
10585
10586            for row in 0..snapshot.max_row().0 {
10587                if let Some(foldable_range) =
10588                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10589                {
10590                    fold_ranges.push(foldable_range);
10591                }
10592            }
10593
10594            self.fold_creases(fold_ranges, true, cx);
10595        } else {
10596            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10597                editor
10598                    .update(&mut cx, |editor, cx| {
10599                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10600                            editor.fold_buffer(buffer_id, cx);
10601                        }
10602                    })
10603                    .ok();
10604            });
10605        }
10606    }
10607
10608    pub fn fold_function_bodies(
10609        &mut self,
10610        _: &actions::FoldFunctionBodies,
10611        cx: &mut ViewContext<Self>,
10612    ) {
10613        let snapshot = self.buffer.read(cx).snapshot(cx);
10614        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10615            return;
10616        };
10617        let creases = buffer
10618            .function_body_fold_ranges(0..buffer.len())
10619            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10620            .collect();
10621
10622        self.fold_creases(creases, true, cx);
10623    }
10624
10625    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10626        let mut to_fold = Vec::new();
10627        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10628        let selections = self.selections.all_adjusted(cx);
10629
10630        for selection in selections {
10631            let range = selection.range().sorted();
10632            let buffer_start_row = range.start.row;
10633
10634            if range.start.row != range.end.row {
10635                let mut found = false;
10636                for row in range.start.row..=range.end.row {
10637                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10638                        found = true;
10639                        to_fold.push(crease);
10640                    }
10641                }
10642                if found {
10643                    continue;
10644                }
10645            }
10646
10647            for row in (0..=range.start.row).rev() {
10648                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10649                    if crease.range().end.row >= buffer_start_row {
10650                        to_fold.push(crease);
10651                    } else {
10652                        break;
10653                    }
10654                }
10655            }
10656        }
10657
10658        self.fold_creases(to_fold, true, cx);
10659    }
10660
10661    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10662        let buffer_row = fold_at.buffer_row;
10663        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10664
10665        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10666            let autoscroll = self
10667                .selections
10668                .all::<Point>(cx)
10669                .iter()
10670                .any(|selection| crease.range().overlaps(&selection.range()));
10671
10672            self.fold_creases(vec![crease], autoscroll, cx);
10673        }
10674    }
10675
10676    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10677        if self.is_singleton(cx) {
10678            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10679            let buffer = &display_map.buffer_snapshot;
10680            let selections = self.selections.all::<Point>(cx);
10681            let ranges = selections
10682                .iter()
10683                .map(|s| {
10684                    let range = s.display_range(&display_map).sorted();
10685                    let mut start = range.start.to_point(&display_map);
10686                    let mut end = range.end.to_point(&display_map);
10687                    start.column = 0;
10688                    end.column = buffer.line_len(MultiBufferRow(end.row));
10689                    start..end
10690                })
10691                .collect::<Vec<_>>();
10692
10693            self.unfold_ranges(&ranges, true, true, cx);
10694        } else {
10695            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10696            let mut unfolded_buffers = HashSet::default();
10697            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10698                self.selections
10699                    .disjoint_anchors()
10700                    .into_iter()
10701                    .map(|selection| selection.range()),
10702            ) {
10703                let buffer_id = buffer_snapshot.remote_id();
10704                if unfolded_buffers.insert(buffer_id) {
10705                    self.unfold_buffer(buffer_id, cx);
10706                }
10707            }
10708        }
10709    }
10710
10711    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10712        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10713        let selections = self.selections.all::<Point>(cx);
10714        let ranges = selections
10715            .iter()
10716            .map(|s| {
10717                let mut range = s.display_range(&display_map).sorted();
10718                *range.start.column_mut() = 0;
10719                *range.end.column_mut() = display_map.line_len(range.end.row());
10720                let start = range.start.to_point(&display_map);
10721                let end = range.end.to_point(&display_map);
10722                start..end
10723            })
10724            .collect::<Vec<_>>();
10725
10726        self.unfold_ranges(&ranges, true, true, cx);
10727    }
10728
10729    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10730        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10731
10732        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10733            ..Point::new(
10734                unfold_at.buffer_row.0,
10735                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10736            );
10737
10738        let autoscroll = self
10739            .selections
10740            .all::<Point>(cx)
10741            .iter()
10742            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10743
10744        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10745    }
10746
10747    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10748        if self.buffer.read(cx).is_singleton() {
10749            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10750            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10751        } else {
10752            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10753                editor
10754                    .update(&mut cx, |editor, cx| {
10755                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10756                            editor.unfold_buffer(buffer_id, cx);
10757                        }
10758                    })
10759                    .ok();
10760            });
10761        }
10762    }
10763
10764    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10765        let selections = self.selections.all::<Point>(cx);
10766        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10767        let line_mode = self.selections.line_mode;
10768        let ranges = selections
10769            .into_iter()
10770            .map(|s| {
10771                if line_mode {
10772                    let start = Point::new(s.start.row, 0);
10773                    let end = Point::new(
10774                        s.end.row,
10775                        display_map
10776                            .buffer_snapshot
10777                            .line_len(MultiBufferRow(s.end.row)),
10778                    );
10779                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10780                } else {
10781                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10782                }
10783            })
10784            .collect::<Vec<_>>();
10785        self.fold_creases(ranges, true, cx);
10786    }
10787
10788    pub fn fold_creases<T: ToOffset + Clone>(
10789        &mut self,
10790        creases: Vec<Crease<T>>,
10791        auto_scroll: bool,
10792        cx: &mut ViewContext<Self>,
10793    ) {
10794        if creases.is_empty() {
10795            return;
10796        }
10797
10798        let mut buffers_affected = HashSet::default();
10799        let multi_buffer = self.buffer().read(cx);
10800        for crease in &creases {
10801            if let Some((_, buffer, _)) =
10802                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10803            {
10804                buffers_affected.insert(buffer.read(cx).remote_id());
10805            };
10806        }
10807
10808        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10809
10810        if auto_scroll {
10811            self.request_autoscroll(Autoscroll::fit(), cx);
10812        }
10813
10814        for buffer_id in buffers_affected {
10815            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10816        }
10817
10818        cx.notify();
10819
10820        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10821            // Clear diagnostics block when folding a range that contains it.
10822            let snapshot = self.snapshot(cx);
10823            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10824                drop(snapshot);
10825                self.active_diagnostics = Some(active_diagnostics);
10826                self.dismiss_diagnostics(cx);
10827            } else {
10828                self.active_diagnostics = Some(active_diagnostics);
10829            }
10830        }
10831
10832        self.scrollbar_marker_state.dirty = true;
10833    }
10834
10835    /// Removes any folds whose ranges intersect any of the given ranges.
10836    pub fn unfold_ranges<T: ToOffset + Clone>(
10837        &mut self,
10838        ranges: &[Range<T>],
10839        inclusive: bool,
10840        auto_scroll: bool,
10841        cx: &mut ViewContext<Self>,
10842    ) {
10843        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10844            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10845        });
10846    }
10847
10848    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10849        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10850            return;
10851        }
10852        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10853            return;
10854        };
10855        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10856        self.display_map
10857            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10858        cx.emit(EditorEvent::BufferFoldToggled {
10859            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10860            folded: true,
10861        });
10862        cx.notify();
10863    }
10864
10865    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10866        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10867            return;
10868        }
10869        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10870            return;
10871        };
10872        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10873        self.display_map.update(cx, |display_map, cx| {
10874            display_map.unfold_buffer(buffer_id, cx);
10875        });
10876        cx.emit(EditorEvent::BufferFoldToggled {
10877            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10878            folded: false,
10879        });
10880        cx.notify();
10881    }
10882
10883    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10884        self.display_map.read(cx).buffer_folded(buffer)
10885    }
10886
10887    /// Removes any folds with the given ranges.
10888    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10889        &mut self,
10890        ranges: &[Range<T>],
10891        type_id: TypeId,
10892        auto_scroll: bool,
10893        cx: &mut ViewContext<Self>,
10894    ) {
10895        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10896            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10897        });
10898    }
10899
10900    fn remove_folds_with<T: ToOffset + Clone>(
10901        &mut self,
10902        ranges: &[Range<T>],
10903        auto_scroll: bool,
10904        cx: &mut ViewContext<Self>,
10905        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10906    ) {
10907        if ranges.is_empty() {
10908            return;
10909        }
10910
10911        let mut buffers_affected = HashSet::default();
10912        let multi_buffer = self.buffer().read(cx);
10913        for range in ranges {
10914            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10915                buffers_affected.insert(buffer.read(cx).remote_id());
10916            };
10917        }
10918
10919        self.display_map.update(cx, update);
10920
10921        if auto_scroll {
10922            self.request_autoscroll(Autoscroll::fit(), cx);
10923        }
10924
10925        for buffer_id in buffers_affected {
10926            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10927        }
10928
10929        cx.notify();
10930        self.scrollbar_marker_state.dirty = true;
10931        self.active_indent_guides_state.dirty = true;
10932    }
10933
10934    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10935        self.display_map.read(cx).fold_placeholder.clone()
10936    }
10937
10938    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10939        if hovered != self.gutter_hovered {
10940            self.gutter_hovered = hovered;
10941            cx.notify();
10942        }
10943    }
10944
10945    pub fn insert_blocks(
10946        &mut self,
10947        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10948        autoscroll: Option<Autoscroll>,
10949        cx: &mut ViewContext<Self>,
10950    ) -> Vec<CustomBlockId> {
10951        let blocks = self
10952            .display_map
10953            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10954        if let Some(autoscroll) = autoscroll {
10955            self.request_autoscroll(autoscroll, cx);
10956        }
10957        cx.notify();
10958        blocks
10959    }
10960
10961    pub fn resize_blocks(
10962        &mut self,
10963        heights: HashMap<CustomBlockId, u32>,
10964        autoscroll: Option<Autoscroll>,
10965        cx: &mut ViewContext<Self>,
10966    ) {
10967        self.display_map
10968            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10969        if let Some(autoscroll) = autoscroll {
10970            self.request_autoscroll(autoscroll, cx);
10971        }
10972        cx.notify();
10973    }
10974
10975    pub fn replace_blocks(
10976        &mut self,
10977        renderers: HashMap<CustomBlockId, RenderBlock>,
10978        autoscroll: Option<Autoscroll>,
10979        cx: &mut ViewContext<Self>,
10980    ) {
10981        self.display_map
10982            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10983        if let Some(autoscroll) = autoscroll {
10984            self.request_autoscroll(autoscroll, cx);
10985        }
10986        cx.notify();
10987    }
10988
10989    pub fn remove_blocks(
10990        &mut self,
10991        block_ids: HashSet<CustomBlockId>,
10992        autoscroll: Option<Autoscroll>,
10993        cx: &mut ViewContext<Self>,
10994    ) {
10995        self.display_map.update(cx, |display_map, cx| {
10996            display_map.remove_blocks(block_ids, cx)
10997        });
10998        if let Some(autoscroll) = autoscroll {
10999            self.request_autoscroll(autoscroll, cx);
11000        }
11001        cx.notify();
11002    }
11003
11004    pub fn row_for_block(
11005        &self,
11006        block_id: CustomBlockId,
11007        cx: &mut ViewContext<Self>,
11008    ) -> Option<DisplayRow> {
11009        self.display_map
11010            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11011    }
11012
11013    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11014        self.focused_block = Some(focused_block);
11015    }
11016
11017    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11018        self.focused_block.take()
11019    }
11020
11021    pub fn insert_creases(
11022        &mut self,
11023        creases: impl IntoIterator<Item = Crease<Anchor>>,
11024        cx: &mut ViewContext<Self>,
11025    ) -> Vec<CreaseId> {
11026        self.display_map
11027            .update(cx, |map, cx| map.insert_creases(creases, cx))
11028    }
11029
11030    pub fn remove_creases(
11031        &mut self,
11032        ids: impl IntoIterator<Item = CreaseId>,
11033        cx: &mut ViewContext<Self>,
11034    ) {
11035        self.display_map
11036            .update(cx, |map, cx| map.remove_creases(ids, cx));
11037    }
11038
11039    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11040        self.display_map
11041            .update(cx, |map, cx| map.snapshot(cx))
11042            .longest_row()
11043    }
11044
11045    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11046        self.display_map
11047            .update(cx, |map, cx| map.snapshot(cx))
11048            .max_point()
11049    }
11050
11051    pub fn text(&self, cx: &AppContext) -> String {
11052        self.buffer.read(cx).read(cx).text()
11053    }
11054
11055    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11056        let text = self.text(cx);
11057        let text = text.trim();
11058
11059        if text.is_empty() {
11060            return None;
11061        }
11062
11063        Some(text.to_string())
11064    }
11065
11066    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11067        self.transact(cx, |this, cx| {
11068            this.buffer
11069                .read(cx)
11070                .as_singleton()
11071                .expect("you can only call set_text on editors for singleton buffers")
11072                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11073        });
11074    }
11075
11076    pub fn display_text(&self, cx: &mut AppContext) -> String {
11077        self.display_map
11078            .update(cx, |map, cx| map.snapshot(cx))
11079            .text()
11080    }
11081
11082    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11083        let mut wrap_guides = smallvec::smallvec![];
11084
11085        if self.show_wrap_guides == Some(false) {
11086            return wrap_guides;
11087        }
11088
11089        let settings = self.buffer.read(cx).settings_at(0, cx);
11090        if settings.show_wrap_guides {
11091            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11092                wrap_guides.push((soft_wrap as usize, true));
11093            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11094                wrap_guides.push((soft_wrap as usize, true));
11095            }
11096            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11097        }
11098
11099        wrap_guides
11100    }
11101
11102    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11103        let settings = self.buffer.read(cx).settings_at(0, cx);
11104        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11105        match mode {
11106            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11107                SoftWrap::None
11108            }
11109            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11110            language_settings::SoftWrap::PreferredLineLength => {
11111                SoftWrap::Column(settings.preferred_line_length)
11112            }
11113            language_settings::SoftWrap::Bounded => {
11114                SoftWrap::Bounded(settings.preferred_line_length)
11115            }
11116        }
11117    }
11118
11119    pub fn set_soft_wrap_mode(
11120        &mut self,
11121        mode: language_settings::SoftWrap,
11122        cx: &mut ViewContext<Self>,
11123    ) {
11124        self.soft_wrap_mode_override = Some(mode);
11125        cx.notify();
11126    }
11127
11128    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11129        self.text_style_refinement = Some(style);
11130    }
11131
11132    /// called by the Element so we know what style we were most recently rendered with.
11133    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11134        let rem_size = cx.rem_size();
11135        self.display_map.update(cx, |map, cx| {
11136            map.set_font(
11137                style.text.font(),
11138                style.text.font_size.to_pixels(rem_size),
11139                cx,
11140            )
11141        });
11142        self.style = Some(style);
11143    }
11144
11145    pub fn style(&self) -> Option<&EditorStyle> {
11146        self.style.as_ref()
11147    }
11148
11149    // Called by the element. This method is not designed to be called outside of the editor
11150    // element's layout code because it does not notify when rewrapping is computed synchronously.
11151    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11152        self.display_map
11153            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11154    }
11155
11156    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11157        if self.soft_wrap_mode_override.is_some() {
11158            self.soft_wrap_mode_override.take();
11159        } else {
11160            let soft_wrap = match self.soft_wrap_mode(cx) {
11161                SoftWrap::GitDiff => return,
11162                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11163                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11164                    language_settings::SoftWrap::None
11165                }
11166            };
11167            self.soft_wrap_mode_override = Some(soft_wrap);
11168        }
11169        cx.notify();
11170    }
11171
11172    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11173        let Some(workspace) = self.workspace() else {
11174            return;
11175        };
11176        let fs = workspace.read(cx).app_state().fs.clone();
11177        let current_show = TabBarSettings::get_global(cx).show;
11178        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11179            setting.show = Some(!current_show);
11180        });
11181    }
11182
11183    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11184        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11185            self.buffer
11186                .read(cx)
11187                .settings_at(0, cx)
11188                .indent_guides
11189                .enabled
11190        });
11191        self.show_indent_guides = Some(!currently_enabled);
11192        cx.notify();
11193    }
11194
11195    fn should_show_indent_guides(&self) -> Option<bool> {
11196        self.show_indent_guides
11197    }
11198
11199    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11200        let mut editor_settings = EditorSettings::get_global(cx).clone();
11201        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11202        EditorSettings::override_global(editor_settings, cx);
11203    }
11204
11205    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11206        self.use_relative_line_numbers
11207            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11208    }
11209
11210    pub fn toggle_relative_line_numbers(
11211        &mut self,
11212        _: &ToggleRelativeLineNumbers,
11213        cx: &mut ViewContext<Self>,
11214    ) {
11215        let is_relative = self.should_use_relative_line_numbers(cx);
11216        self.set_relative_line_number(Some(!is_relative), cx)
11217    }
11218
11219    pub fn set_relative_line_number(
11220        &mut self,
11221        is_relative: Option<bool>,
11222        cx: &mut ViewContext<Self>,
11223    ) {
11224        self.use_relative_line_numbers = is_relative;
11225        cx.notify();
11226    }
11227
11228    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11229        self.show_gutter = show_gutter;
11230        cx.notify();
11231    }
11232
11233    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11234        self.show_line_numbers = Some(show_line_numbers);
11235        cx.notify();
11236    }
11237
11238    pub fn set_show_git_diff_gutter(
11239        &mut self,
11240        show_git_diff_gutter: bool,
11241        cx: &mut ViewContext<Self>,
11242    ) {
11243        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11244        cx.notify();
11245    }
11246
11247    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11248        self.show_code_actions = Some(show_code_actions);
11249        cx.notify();
11250    }
11251
11252    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11253        self.show_runnables = Some(show_runnables);
11254        cx.notify();
11255    }
11256
11257    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11258        if self.display_map.read(cx).masked != masked {
11259            self.display_map.update(cx, |map, _| map.masked = masked);
11260        }
11261        cx.notify()
11262    }
11263
11264    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11265        self.show_wrap_guides = Some(show_wrap_guides);
11266        cx.notify();
11267    }
11268
11269    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11270        self.show_indent_guides = Some(show_indent_guides);
11271        cx.notify();
11272    }
11273
11274    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11275        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11276            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11277                if let Some(dir) = file.abs_path(cx).parent() {
11278                    return Some(dir.to_owned());
11279                }
11280            }
11281
11282            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11283                return Some(project_path.path.to_path_buf());
11284            }
11285        }
11286
11287        None
11288    }
11289
11290    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11291        self.active_excerpt(cx)?
11292            .1
11293            .read(cx)
11294            .file()
11295            .and_then(|f| f.as_local())
11296    }
11297
11298    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11299        if let Some(target) = self.target_file(cx) {
11300            cx.reveal_path(&target.abs_path(cx));
11301        }
11302    }
11303
11304    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11305        if let Some(file) = self.target_file(cx) {
11306            if let Some(path) = file.abs_path(cx).to_str() {
11307                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11308            }
11309        }
11310    }
11311
11312    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11313        if let Some(file) = self.target_file(cx) {
11314            if let Some(path) = file.path().to_str() {
11315                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11316            }
11317        }
11318    }
11319
11320    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11321        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11322
11323        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11324            self.start_git_blame(true, cx);
11325        }
11326
11327        cx.notify();
11328    }
11329
11330    pub fn toggle_git_blame_inline(
11331        &mut self,
11332        _: &ToggleGitBlameInline,
11333        cx: &mut ViewContext<Self>,
11334    ) {
11335        self.toggle_git_blame_inline_internal(true, cx);
11336        cx.notify();
11337    }
11338
11339    pub fn git_blame_inline_enabled(&self) -> bool {
11340        self.git_blame_inline_enabled
11341    }
11342
11343    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11344        self.show_selection_menu = self
11345            .show_selection_menu
11346            .map(|show_selections_menu| !show_selections_menu)
11347            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11348
11349        cx.notify();
11350    }
11351
11352    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11353        self.show_selection_menu
11354            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11355    }
11356
11357    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11358        if let Some(project) = self.project.as_ref() {
11359            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11360                return;
11361            };
11362
11363            if buffer.read(cx).file().is_none() {
11364                return;
11365            }
11366
11367            let focused = self.focus_handle(cx).contains_focused(cx);
11368
11369            let project = project.clone();
11370            let blame =
11371                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11372            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11373            self.blame = Some(blame);
11374        }
11375    }
11376
11377    fn toggle_git_blame_inline_internal(
11378        &mut self,
11379        user_triggered: bool,
11380        cx: &mut ViewContext<Self>,
11381    ) {
11382        if self.git_blame_inline_enabled {
11383            self.git_blame_inline_enabled = false;
11384            self.show_git_blame_inline = false;
11385            self.show_git_blame_inline_delay_task.take();
11386        } else {
11387            self.git_blame_inline_enabled = true;
11388            self.start_git_blame_inline(user_triggered, cx);
11389        }
11390
11391        cx.notify();
11392    }
11393
11394    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11395        self.start_git_blame(user_triggered, cx);
11396
11397        if ProjectSettings::get_global(cx)
11398            .git
11399            .inline_blame_delay()
11400            .is_some()
11401        {
11402            self.start_inline_blame_timer(cx);
11403        } else {
11404            self.show_git_blame_inline = true
11405        }
11406    }
11407
11408    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11409        self.blame.as_ref()
11410    }
11411
11412    pub fn show_git_blame_gutter(&self) -> bool {
11413        self.show_git_blame_gutter
11414    }
11415
11416    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11417        self.show_git_blame_gutter && self.has_blame_entries(cx)
11418    }
11419
11420    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11421        self.show_git_blame_inline
11422            && self.focus_handle.is_focused(cx)
11423            && !self.newest_selection_head_on_empty_line(cx)
11424            && self.has_blame_entries(cx)
11425    }
11426
11427    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11428        self.blame()
11429            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11430    }
11431
11432    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11433        let cursor_anchor = self.selections.newest_anchor().head();
11434
11435        let snapshot = self.buffer.read(cx).snapshot(cx);
11436        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11437
11438        snapshot.line_len(buffer_row) == 0
11439    }
11440
11441    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11442        let buffer_and_selection = maybe!({
11443            let selection = self.selections.newest::<Point>(cx);
11444            let selection_range = selection.range();
11445
11446            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11447                (buffer, selection_range.start.row..selection_range.end.row)
11448            } else {
11449                let buffer_ranges = self
11450                    .buffer()
11451                    .read(cx)
11452                    .range_to_buffer_ranges(selection_range, cx);
11453
11454                let (buffer, range, _) = if selection.reversed {
11455                    buffer_ranges.first()
11456                } else {
11457                    buffer_ranges.last()
11458                }?;
11459
11460                let snapshot = buffer.read(cx).snapshot();
11461                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11462                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11463                (buffer.clone(), selection)
11464            };
11465
11466            Some((buffer, selection))
11467        });
11468
11469        let Some((buffer, selection)) = buffer_and_selection else {
11470            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11471        };
11472
11473        let Some(project) = self.project.as_ref() else {
11474            return Task::ready(Err(anyhow!("editor does not have project")));
11475        };
11476
11477        project.update(cx, |project, cx| {
11478            project.get_permalink_to_line(&buffer, selection, cx)
11479        })
11480    }
11481
11482    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11483        let permalink_task = self.get_permalink_to_line(cx);
11484        let workspace = self.workspace();
11485
11486        cx.spawn(|_, mut cx| async move {
11487            match permalink_task.await {
11488                Ok(permalink) => {
11489                    cx.update(|cx| {
11490                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11491                    })
11492                    .ok();
11493                }
11494                Err(err) => {
11495                    let message = format!("Failed to copy permalink: {err}");
11496
11497                    Err::<(), anyhow::Error>(err).log_err();
11498
11499                    if let Some(workspace) = workspace {
11500                        workspace
11501                            .update(&mut cx, |workspace, cx| {
11502                                struct CopyPermalinkToLine;
11503
11504                                workspace.show_toast(
11505                                    Toast::new(
11506                                        NotificationId::unique::<CopyPermalinkToLine>(),
11507                                        message,
11508                                    ),
11509                                    cx,
11510                                )
11511                            })
11512                            .ok();
11513                    }
11514                }
11515            }
11516        })
11517        .detach();
11518    }
11519
11520    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11521        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11522        if let Some(file) = self.target_file(cx) {
11523            if let Some(path) = file.path().to_str() {
11524                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11525            }
11526        }
11527    }
11528
11529    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11530        let permalink_task = self.get_permalink_to_line(cx);
11531        let workspace = self.workspace();
11532
11533        cx.spawn(|_, mut cx| async move {
11534            match permalink_task.await {
11535                Ok(permalink) => {
11536                    cx.update(|cx| {
11537                        cx.open_url(permalink.as_ref());
11538                    })
11539                    .ok();
11540                }
11541                Err(err) => {
11542                    let message = format!("Failed to open permalink: {err}");
11543
11544                    Err::<(), anyhow::Error>(err).log_err();
11545
11546                    if let Some(workspace) = workspace {
11547                        workspace
11548                            .update(&mut cx, |workspace, cx| {
11549                                struct OpenPermalinkToLine;
11550
11551                                workspace.show_toast(
11552                                    Toast::new(
11553                                        NotificationId::unique::<OpenPermalinkToLine>(),
11554                                        message,
11555                                    ),
11556                                    cx,
11557                                )
11558                            })
11559                            .ok();
11560                    }
11561                }
11562            }
11563        })
11564        .detach();
11565    }
11566
11567    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11568        self.insert_uuid(UuidVersion::V4, cx);
11569    }
11570
11571    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11572        self.insert_uuid(UuidVersion::V7, cx);
11573    }
11574
11575    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11576        self.transact(cx, |this, cx| {
11577            let edits = this
11578                .selections
11579                .all::<Point>(cx)
11580                .into_iter()
11581                .map(|selection| {
11582                    let uuid = match version {
11583                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11584                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11585                    };
11586
11587                    (selection.range(), uuid.to_string())
11588                });
11589            this.edit(edits, cx);
11590            this.refresh_inline_completion(true, false, cx);
11591        });
11592    }
11593
11594    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11595    /// last highlight added will be used.
11596    ///
11597    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11598    pub fn highlight_rows<T: 'static>(
11599        &mut self,
11600        range: Range<Anchor>,
11601        color: Hsla,
11602        should_autoscroll: bool,
11603        cx: &mut ViewContext<Self>,
11604    ) {
11605        let snapshot = self.buffer().read(cx).snapshot(cx);
11606        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11607        let ix = row_highlights.binary_search_by(|highlight| {
11608            Ordering::Equal
11609                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11610                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11611        });
11612
11613        if let Err(mut ix) = ix {
11614            let index = post_inc(&mut self.highlight_order);
11615
11616            // If this range intersects with the preceding highlight, then merge it with
11617            // the preceding highlight. Otherwise insert a new highlight.
11618            let mut merged = false;
11619            if ix > 0 {
11620                let prev_highlight = &mut row_highlights[ix - 1];
11621                if prev_highlight
11622                    .range
11623                    .end
11624                    .cmp(&range.start, &snapshot)
11625                    .is_ge()
11626                {
11627                    ix -= 1;
11628                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11629                        prev_highlight.range.end = range.end;
11630                    }
11631                    merged = true;
11632                    prev_highlight.index = index;
11633                    prev_highlight.color = color;
11634                    prev_highlight.should_autoscroll = should_autoscroll;
11635                }
11636            }
11637
11638            if !merged {
11639                row_highlights.insert(
11640                    ix,
11641                    RowHighlight {
11642                        range: range.clone(),
11643                        index,
11644                        color,
11645                        should_autoscroll,
11646                    },
11647                );
11648            }
11649
11650            // If any of the following highlights intersect with this one, merge them.
11651            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11652                let highlight = &row_highlights[ix];
11653                if next_highlight
11654                    .range
11655                    .start
11656                    .cmp(&highlight.range.end, &snapshot)
11657                    .is_le()
11658                {
11659                    if next_highlight
11660                        .range
11661                        .end
11662                        .cmp(&highlight.range.end, &snapshot)
11663                        .is_gt()
11664                    {
11665                        row_highlights[ix].range.end = next_highlight.range.end;
11666                    }
11667                    row_highlights.remove(ix + 1);
11668                } else {
11669                    break;
11670                }
11671            }
11672        }
11673    }
11674
11675    /// Remove any highlighted row ranges of the given type that intersect the
11676    /// given ranges.
11677    pub fn remove_highlighted_rows<T: 'static>(
11678        &mut self,
11679        ranges_to_remove: Vec<Range<Anchor>>,
11680        cx: &mut ViewContext<Self>,
11681    ) {
11682        let snapshot = self.buffer().read(cx).snapshot(cx);
11683        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11684        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11685        row_highlights.retain(|highlight| {
11686            while let Some(range_to_remove) = ranges_to_remove.peek() {
11687                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11688                    Ordering::Less | Ordering::Equal => {
11689                        ranges_to_remove.next();
11690                    }
11691                    Ordering::Greater => {
11692                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11693                            Ordering::Less | Ordering::Equal => {
11694                                return false;
11695                            }
11696                            Ordering::Greater => break,
11697                        }
11698                    }
11699                }
11700            }
11701
11702            true
11703        })
11704    }
11705
11706    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11707    pub fn clear_row_highlights<T: 'static>(&mut self) {
11708        self.highlighted_rows.remove(&TypeId::of::<T>());
11709    }
11710
11711    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11712    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11713        self.highlighted_rows
11714            .get(&TypeId::of::<T>())
11715            .map_or(&[] as &[_], |vec| vec.as_slice())
11716            .iter()
11717            .map(|highlight| (highlight.range.clone(), highlight.color))
11718    }
11719
11720    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11721    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11722    /// Allows to ignore certain kinds of highlights.
11723    pub fn highlighted_display_rows(
11724        &mut self,
11725        cx: &mut WindowContext,
11726    ) -> BTreeMap<DisplayRow, Hsla> {
11727        let snapshot = self.snapshot(cx);
11728        let mut used_highlight_orders = HashMap::default();
11729        self.highlighted_rows
11730            .iter()
11731            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11732            .fold(
11733                BTreeMap::<DisplayRow, Hsla>::new(),
11734                |mut unique_rows, highlight| {
11735                    let start = highlight.range.start.to_display_point(&snapshot);
11736                    let end = highlight.range.end.to_display_point(&snapshot);
11737                    let start_row = start.row().0;
11738                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11739                        && end.column() == 0
11740                    {
11741                        end.row().0.saturating_sub(1)
11742                    } else {
11743                        end.row().0
11744                    };
11745                    for row in start_row..=end_row {
11746                        let used_index =
11747                            used_highlight_orders.entry(row).or_insert(highlight.index);
11748                        if highlight.index >= *used_index {
11749                            *used_index = highlight.index;
11750                            unique_rows.insert(DisplayRow(row), highlight.color);
11751                        }
11752                    }
11753                    unique_rows
11754                },
11755            )
11756    }
11757
11758    pub fn highlighted_display_row_for_autoscroll(
11759        &self,
11760        snapshot: &DisplaySnapshot,
11761    ) -> Option<DisplayRow> {
11762        self.highlighted_rows
11763            .values()
11764            .flat_map(|highlighted_rows| highlighted_rows.iter())
11765            .filter_map(|highlight| {
11766                if highlight.should_autoscroll {
11767                    Some(highlight.range.start.to_display_point(snapshot).row())
11768                } else {
11769                    None
11770                }
11771            })
11772            .min()
11773    }
11774
11775    pub fn set_search_within_ranges(
11776        &mut self,
11777        ranges: &[Range<Anchor>],
11778        cx: &mut ViewContext<Self>,
11779    ) {
11780        self.highlight_background::<SearchWithinRange>(
11781            ranges,
11782            |colors| colors.editor_document_highlight_read_background,
11783            cx,
11784        )
11785    }
11786
11787    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11788        self.breadcrumb_header = Some(new_header);
11789    }
11790
11791    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11792        self.clear_background_highlights::<SearchWithinRange>(cx);
11793    }
11794
11795    pub fn highlight_background<T: 'static>(
11796        &mut self,
11797        ranges: &[Range<Anchor>],
11798        color_fetcher: fn(&ThemeColors) -> Hsla,
11799        cx: &mut ViewContext<Self>,
11800    ) {
11801        self.background_highlights
11802            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11803        self.scrollbar_marker_state.dirty = true;
11804        cx.notify();
11805    }
11806
11807    pub fn clear_background_highlights<T: 'static>(
11808        &mut self,
11809        cx: &mut ViewContext<Self>,
11810    ) -> Option<BackgroundHighlight> {
11811        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11812        if !text_highlights.1.is_empty() {
11813            self.scrollbar_marker_state.dirty = true;
11814            cx.notify();
11815        }
11816        Some(text_highlights)
11817    }
11818
11819    pub fn highlight_gutter<T: 'static>(
11820        &mut self,
11821        ranges: &[Range<Anchor>],
11822        color_fetcher: fn(&AppContext) -> Hsla,
11823        cx: &mut ViewContext<Self>,
11824    ) {
11825        self.gutter_highlights
11826            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11827        cx.notify();
11828    }
11829
11830    pub fn clear_gutter_highlights<T: 'static>(
11831        &mut self,
11832        cx: &mut ViewContext<Self>,
11833    ) -> Option<GutterHighlight> {
11834        cx.notify();
11835        self.gutter_highlights.remove(&TypeId::of::<T>())
11836    }
11837
11838    #[cfg(feature = "test-support")]
11839    pub fn all_text_background_highlights(
11840        &mut self,
11841        cx: &mut ViewContext<Self>,
11842    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11843        let snapshot = self.snapshot(cx);
11844        let buffer = &snapshot.buffer_snapshot;
11845        let start = buffer.anchor_before(0);
11846        let end = buffer.anchor_after(buffer.len());
11847        let theme = cx.theme().colors();
11848        self.background_highlights_in_range(start..end, &snapshot, theme)
11849    }
11850
11851    #[cfg(feature = "test-support")]
11852    pub fn search_background_highlights(
11853        &mut self,
11854        cx: &mut ViewContext<Self>,
11855    ) -> Vec<Range<Point>> {
11856        let snapshot = self.buffer().read(cx).snapshot(cx);
11857
11858        let highlights = self
11859            .background_highlights
11860            .get(&TypeId::of::<items::BufferSearchHighlights>());
11861
11862        if let Some((_color, ranges)) = highlights {
11863            ranges
11864                .iter()
11865                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11866                .collect_vec()
11867        } else {
11868            vec![]
11869        }
11870    }
11871
11872    fn document_highlights_for_position<'a>(
11873        &'a self,
11874        position: Anchor,
11875        buffer: &'a MultiBufferSnapshot,
11876    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11877        let read_highlights = self
11878            .background_highlights
11879            .get(&TypeId::of::<DocumentHighlightRead>())
11880            .map(|h| &h.1);
11881        let write_highlights = self
11882            .background_highlights
11883            .get(&TypeId::of::<DocumentHighlightWrite>())
11884            .map(|h| &h.1);
11885        let left_position = position.bias_left(buffer);
11886        let right_position = position.bias_right(buffer);
11887        read_highlights
11888            .into_iter()
11889            .chain(write_highlights)
11890            .flat_map(move |ranges| {
11891                let start_ix = match ranges.binary_search_by(|probe| {
11892                    let cmp = probe.end.cmp(&left_position, buffer);
11893                    if cmp.is_ge() {
11894                        Ordering::Greater
11895                    } else {
11896                        Ordering::Less
11897                    }
11898                }) {
11899                    Ok(i) | Err(i) => i,
11900                };
11901
11902                ranges[start_ix..]
11903                    .iter()
11904                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11905            })
11906    }
11907
11908    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11909        self.background_highlights
11910            .get(&TypeId::of::<T>())
11911            .map_or(false, |(_, highlights)| !highlights.is_empty())
11912    }
11913
11914    pub fn background_highlights_in_range(
11915        &self,
11916        search_range: Range<Anchor>,
11917        display_snapshot: &DisplaySnapshot,
11918        theme: &ThemeColors,
11919    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11920        let mut results = Vec::new();
11921        for (color_fetcher, ranges) in self.background_highlights.values() {
11922            let color = color_fetcher(theme);
11923            let start_ix = match ranges.binary_search_by(|probe| {
11924                let cmp = probe
11925                    .end
11926                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11927                if cmp.is_gt() {
11928                    Ordering::Greater
11929                } else {
11930                    Ordering::Less
11931                }
11932            }) {
11933                Ok(i) | Err(i) => i,
11934            };
11935            for range in &ranges[start_ix..] {
11936                if range
11937                    .start
11938                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11939                    .is_ge()
11940                {
11941                    break;
11942                }
11943
11944                let start = range.start.to_display_point(display_snapshot);
11945                let end = range.end.to_display_point(display_snapshot);
11946                results.push((start..end, color))
11947            }
11948        }
11949        results
11950    }
11951
11952    pub fn background_highlight_row_ranges<T: 'static>(
11953        &self,
11954        search_range: Range<Anchor>,
11955        display_snapshot: &DisplaySnapshot,
11956        count: usize,
11957    ) -> Vec<RangeInclusive<DisplayPoint>> {
11958        let mut results = Vec::new();
11959        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11960            return vec![];
11961        };
11962
11963        let start_ix = match ranges.binary_search_by(|probe| {
11964            let cmp = probe
11965                .end
11966                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11967            if cmp.is_gt() {
11968                Ordering::Greater
11969            } else {
11970                Ordering::Less
11971            }
11972        }) {
11973            Ok(i) | Err(i) => i,
11974        };
11975        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11976            if let (Some(start_display), Some(end_display)) = (start, end) {
11977                results.push(
11978                    start_display.to_display_point(display_snapshot)
11979                        ..=end_display.to_display_point(display_snapshot),
11980                );
11981            }
11982        };
11983        let mut start_row: Option<Point> = None;
11984        let mut end_row: Option<Point> = None;
11985        if ranges.len() > count {
11986            return Vec::new();
11987        }
11988        for range in &ranges[start_ix..] {
11989            if range
11990                .start
11991                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11992                .is_ge()
11993            {
11994                break;
11995            }
11996            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11997            if let Some(current_row) = &end_row {
11998                if end.row == current_row.row {
11999                    continue;
12000                }
12001            }
12002            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12003            if start_row.is_none() {
12004                assert_eq!(end_row, None);
12005                start_row = Some(start);
12006                end_row = Some(end);
12007                continue;
12008            }
12009            if let Some(current_end) = end_row.as_mut() {
12010                if start.row > current_end.row + 1 {
12011                    push_region(start_row, end_row);
12012                    start_row = Some(start);
12013                    end_row = Some(end);
12014                } else {
12015                    // Merge two hunks.
12016                    *current_end = end;
12017                }
12018            } else {
12019                unreachable!();
12020            }
12021        }
12022        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12023        push_region(start_row, end_row);
12024        results
12025    }
12026
12027    pub fn gutter_highlights_in_range(
12028        &self,
12029        search_range: Range<Anchor>,
12030        display_snapshot: &DisplaySnapshot,
12031        cx: &AppContext,
12032    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12033        let mut results = Vec::new();
12034        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12035            let color = color_fetcher(cx);
12036            let start_ix = match ranges.binary_search_by(|probe| {
12037                let cmp = probe
12038                    .end
12039                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12040                if cmp.is_gt() {
12041                    Ordering::Greater
12042                } else {
12043                    Ordering::Less
12044                }
12045            }) {
12046                Ok(i) | Err(i) => i,
12047            };
12048            for range in &ranges[start_ix..] {
12049                if range
12050                    .start
12051                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12052                    .is_ge()
12053                {
12054                    break;
12055                }
12056
12057                let start = range.start.to_display_point(display_snapshot);
12058                let end = range.end.to_display_point(display_snapshot);
12059                results.push((start..end, color))
12060            }
12061        }
12062        results
12063    }
12064
12065    /// Get the text ranges corresponding to the redaction query
12066    pub fn redacted_ranges(
12067        &self,
12068        search_range: Range<Anchor>,
12069        display_snapshot: &DisplaySnapshot,
12070        cx: &WindowContext,
12071    ) -> Vec<Range<DisplayPoint>> {
12072        display_snapshot
12073            .buffer_snapshot
12074            .redacted_ranges(search_range, |file| {
12075                if let Some(file) = file {
12076                    file.is_private()
12077                        && EditorSettings::get(
12078                            Some(SettingsLocation {
12079                                worktree_id: file.worktree_id(cx),
12080                                path: file.path().as_ref(),
12081                            }),
12082                            cx,
12083                        )
12084                        .redact_private_values
12085                } else {
12086                    false
12087                }
12088            })
12089            .map(|range| {
12090                range.start.to_display_point(display_snapshot)
12091                    ..range.end.to_display_point(display_snapshot)
12092            })
12093            .collect()
12094    }
12095
12096    pub fn highlight_text<T: 'static>(
12097        &mut self,
12098        ranges: Vec<Range<Anchor>>,
12099        style: HighlightStyle,
12100        cx: &mut ViewContext<Self>,
12101    ) {
12102        self.display_map.update(cx, |map, _| {
12103            map.highlight_text(TypeId::of::<T>(), ranges, style)
12104        });
12105        cx.notify();
12106    }
12107
12108    pub(crate) fn highlight_inlays<T: 'static>(
12109        &mut self,
12110        highlights: Vec<InlayHighlight>,
12111        style: HighlightStyle,
12112        cx: &mut ViewContext<Self>,
12113    ) {
12114        self.display_map.update(cx, |map, _| {
12115            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12116        });
12117        cx.notify();
12118    }
12119
12120    pub fn text_highlights<'a, T: 'static>(
12121        &'a self,
12122        cx: &'a AppContext,
12123    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12124        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12125    }
12126
12127    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12128        let cleared = self
12129            .display_map
12130            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12131        if cleared {
12132            cx.notify();
12133        }
12134    }
12135
12136    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12137        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12138            && self.focus_handle.is_focused(cx)
12139    }
12140
12141    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12142        self.show_cursor_when_unfocused = is_enabled;
12143        cx.notify();
12144    }
12145
12146    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12147        self.project
12148            .as_ref()
12149            .map(|project| project.read(cx).lsp_store())
12150    }
12151
12152    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12153        cx.notify();
12154    }
12155
12156    fn on_buffer_event(
12157        &mut self,
12158        multibuffer: Model<MultiBuffer>,
12159        event: &multi_buffer::Event,
12160        cx: &mut ViewContext<Self>,
12161    ) {
12162        match event {
12163            multi_buffer::Event::Edited {
12164                singleton_buffer_edited,
12165                edited_buffer: buffer_edited,
12166            } => {
12167                self.scrollbar_marker_state.dirty = true;
12168                self.active_indent_guides_state.dirty = true;
12169                self.refresh_active_diagnostics(cx);
12170                self.refresh_code_actions(cx);
12171                if self.has_active_inline_completion() {
12172                    self.update_visible_inline_completion(cx);
12173                }
12174                if let Some(buffer) = buffer_edited {
12175                    let buffer_id = buffer.read(cx).remote_id();
12176                    if !self.registered_buffers.contains_key(&buffer_id) {
12177                        if let Some(lsp_store) = self.lsp_store(cx) {
12178                            lsp_store.update(cx, |lsp_store, cx| {
12179                                self.registered_buffers.insert(
12180                                    buffer_id,
12181                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12182                                );
12183                            })
12184                        }
12185                    }
12186                }
12187                cx.emit(EditorEvent::BufferEdited);
12188                cx.emit(SearchEvent::MatchesInvalidated);
12189                if *singleton_buffer_edited {
12190                    if let Some(project) = &self.project {
12191                        let project = project.read(cx);
12192                        #[allow(clippy::mutable_key_type)]
12193                        let languages_affected = multibuffer
12194                            .read(cx)
12195                            .all_buffers()
12196                            .into_iter()
12197                            .filter_map(|buffer| {
12198                                let buffer = buffer.read(cx);
12199                                let language = buffer.language()?;
12200                                if project.is_local()
12201                                    && project
12202                                        .language_servers_for_local_buffer(buffer, cx)
12203                                        .count()
12204                                        == 0
12205                                {
12206                                    None
12207                                } else {
12208                                    Some(language)
12209                                }
12210                            })
12211                            .cloned()
12212                            .collect::<HashSet<_>>();
12213                        if !languages_affected.is_empty() {
12214                            self.refresh_inlay_hints(
12215                                InlayHintRefreshReason::BufferEdited(languages_affected),
12216                                cx,
12217                            );
12218                        }
12219                    }
12220                }
12221
12222                let Some(project) = &self.project else { return };
12223                let (telemetry, is_via_ssh) = {
12224                    let project = project.read(cx);
12225                    let telemetry = project.client().telemetry().clone();
12226                    let is_via_ssh = project.is_via_ssh();
12227                    (telemetry, is_via_ssh)
12228                };
12229                refresh_linked_ranges(self, cx);
12230                telemetry.log_edit_event("editor", is_via_ssh);
12231            }
12232            multi_buffer::Event::ExcerptsAdded {
12233                buffer,
12234                predecessor,
12235                excerpts,
12236            } => {
12237                self.tasks_update_task = Some(self.refresh_runnables(cx));
12238                let buffer_id = buffer.read(cx).remote_id();
12239                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12240                    if let Some(project) = &self.project {
12241                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12242                    }
12243                }
12244                cx.emit(EditorEvent::ExcerptsAdded {
12245                    buffer: buffer.clone(),
12246                    predecessor: *predecessor,
12247                    excerpts: excerpts.clone(),
12248                });
12249                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12250            }
12251            multi_buffer::Event::ExcerptsRemoved { ids } => {
12252                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12253                let buffer = self.buffer.read(cx);
12254                self.registered_buffers
12255                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12256                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12257            }
12258            multi_buffer::Event::ExcerptsEdited { ids } => {
12259                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12260            }
12261            multi_buffer::Event::ExcerptsExpanded { ids } => {
12262                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12263            }
12264            multi_buffer::Event::Reparsed(buffer_id) => {
12265                self.tasks_update_task = Some(self.refresh_runnables(cx));
12266
12267                cx.emit(EditorEvent::Reparsed(*buffer_id));
12268            }
12269            multi_buffer::Event::LanguageChanged(buffer_id) => {
12270                linked_editing_ranges::refresh_linked_ranges(self, cx);
12271                cx.emit(EditorEvent::Reparsed(*buffer_id));
12272                cx.notify();
12273            }
12274            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12275            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12276            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12277                cx.emit(EditorEvent::TitleChanged)
12278            }
12279            // multi_buffer::Event::DiffBaseChanged => {
12280            //     self.scrollbar_marker_state.dirty = true;
12281            //     cx.emit(EditorEvent::DiffBaseChanged);
12282            //     cx.notify();
12283            // }
12284            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12285            multi_buffer::Event::DiagnosticsUpdated => {
12286                self.refresh_active_diagnostics(cx);
12287                self.scrollbar_marker_state.dirty = true;
12288                cx.notify();
12289            }
12290            _ => {}
12291        };
12292    }
12293
12294    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12295        cx.notify();
12296    }
12297
12298    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12299        self.tasks_update_task = Some(self.refresh_runnables(cx));
12300        self.refresh_inline_completion(true, false, cx);
12301        self.refresh_inlay_hints(
12302            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12303                self.selections.newest_anchor().head(),
12304                &self.buffer.read(cx).snapshot(cx),
12305                cx,
12306            )),
12307            cx,
12308        );
12309
12310        let old_cursor_shape = self.cursor_shape;
12311
12312        {
12313            let editor_settings = EditorSettings::get_global(cx);
12314            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12315            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12316            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12317        }
12318
12319        if old_cursor_shape != self.cursor_shape {
12320            cx.emit(EditorEvent::CursorShapeChanged);
12321        }
12322
12323        let project_settings = ProjectSettings::get_global(cx);
12324        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12325
12326        if self.mode == EditorMode::Full {
12327            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12328            if self.git_blame_inline_enabled != inline_blame_enabled {
12329                self.toggle_git_blame_inline_internal(false, cx);
12330            }
12331        }
12332
12333        cx.notify();
12334    }
12335
12336    pub fn set_searchable(&mut self, searchable: bool) {
12337        self.searchable = searchable;
12338    }
12339
12340    pub fn searchable(&self) -> bool {
12341        self.searchable
12342    }
12343
12344    fn open_proposed_changes_editor(
12345        &mut self,
12346        _: &OpenProposedChangesEditor,
12347        cx: &mut ViewContext<Self>,
12348    ) {
12349        let Some(workspace) = self.workspace() else {
12350            cx.propagate();
12351            return;
12352        };
12353
12354        let selections = self.selections.all::<usize>(cx);
12355        let buffer = self.buffer.read(cx);
12356        let mut new_selections_by_buffer = HashMap::default();
12357        for selection in selections {
12358            for (buffer, range, _) in
12359                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12360            {
12361                let mut range = range.to_point(buffer.read(cx));
12362                range.start.column = 0;
12363                range.end.column = buffer.read(cx).line_len(range.end.row);
12364                new_selections_by_buffer
12365                    .entry(buffer)
12366                    .or_insert(Vec::new())
12367                    .push(range)
12368            }
12369        }
12370
12371        let proposed_changes_buffers = new_selections_by_buffer
12372            .into_iter()
12373            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12374            .collect::<Vec<_>>();
12375        let proposed_changes_editor = cx.new_view(|cx| {
12376            ProposedChangesEditor::new(
12377                "Proposed changes",
12378                proposed_changes_buffers,
12379                self.project.clone(),
12380                cx,
12381            )
12382        });
12383
12384        cx.window_context().defer(move |cx| {
12385            workspace.update(cx, |workspace, cx| {
12386                workspace.active_pane().update(cx, |pane, cx| {
12387                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12388                });
12389            });
12390        });
12391    }
12392
12393    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12394        self.open_excerpts_common(None, true, cx)
12395    }
12396
12397    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12398        self.open_excerpts_common(None, false, cx)
12399    }
12400
12401    fn open_excerpts_common(
12402        &mut self,
12403        jump_data: Option<JumpData>,
12404        split: bool,
12405        cx: &mut ViewContext<Self>,
12406    ) {
12407        let Some(workspace) = self.workspace() else {
12408            cx.propagate();
12409            return;
12410        };
12411
12412        if self.buffer.read(cx).is_singleton() {
12413            cx.propagate();
12414            return;
12415        }
12416
12417        let mut new_selections_by_buffer = HashMap::default();
12418        match &jump_data {
12419            Some(jump_data) => {
12420                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12421                if let Some(buffer) = multi_buffer_snapshot
12422                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12423                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12424                {
12425                    let buffer_snapshot = buffer.read(cx).snapshot();
12426                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12427                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12428                    } else {
12429                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12430                    };
12431                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12432                    new_selections_by_buffer.insert(
12433                        buffer,
12434                        (
12435                            vec![jump_to_offset..jump_to_offset],
12436                            Some(jump_data.line_offset_from_top),
12437                        ),
12438                    );
12439                }
12440            }
12441            None => {
12442                let selections = self.selections.all::<usize>(cx);
12443                let buffer = self.buffer.read(cx);
12444                for selection in selections {
12445                    for (mut buffer_handle, mut range, _) in
12446                        buffer.range_to_buffer_ranges(selection.range(), cx)
12447                    {
12448                        // When editing branch buffers, jump to the corresponding location
12449                        // in their base buffer.
12450                        let buffer = buffer_handle.read(cx);
12451                        if let Some(base_buffer) = buffer.base_buffer() {
12452                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12453                            buffer_handle = base_buffer;
12454                        }
12455
12456                        if selection.reversed {
12457                            mem::swap(&mut range.start, &mut range.end);
12458                        }
12459                        new_selections_by_buffer
12460                            .entry(buffer_handle)
12461                            .or_insert((Vec::new(), None))
12462                            .0
12463                            .push(range)
12464                    }
12465                }
12466            }
12467        }
12468
12469        if new_selections_by_buffer.is_empty() {
12470            return;
12471        }
12472
12473        // We defer the pane interaction because we ourselves are a workspace item
12474        // and activating a new item causes the pane to call a method on us reentrantly,
12475        // which panics if we're on the stack.
12476        cx.window_context().defer(move |cx| {
12477            workspace.update(cx, |workspace, cx| {
12478                let pane = if split {
12479                    workspace.adjacent_pane(cx)
12480                } else {
12481                    workspace.active_pane().clone()
12482                };
12483
12484                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12485                    let editor = buffer
12486                        .read(cx)
12487                        .file()
12488                        .is_none()
12489                        .then(|| {
12490                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12491                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12492                            // Instead, we try to activate the existing editor in the pane first.
12493                            let (editor, pane_item_index) =
12494                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12495                                    let editor = item.downcast::<Editor>()?;
12496                                    let singleton_buffer =
12497                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12498                                    if singleton_buffer == buffer {
12499                                        Some((editor, i))
12500                                    } else {
12501                                        None
12502                                    }
12503                                })?;
12504                            pane.update(cx, |pane, cx| {
12505                                pane.activate_item(pane_item_index, true, true, cx)
12506                            });
12507                            Some(editor)
12508                        })
12509                        .flatten()
12510                        .unwrap_or_else(|| {
12511                            workspace.open_project_item::<Self>(
12512                                pane.clone(),
12513                                buffer,
12514                                true,
12515                                true,
12516                                cx,
12517                            )
12518                        });
12519
12520                    editor.update(cx, |editor, cx| {
12521                        let autoscroll = match scroll_offset {
12522                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12523                            None => Autoscroll::newest(),
12524                        };
12525                        let nav_history = editor.nav_history.take();
12526                        editor.change_selections(Some(autoscroll), cx, |s| {
12527                            s.select_ranges(ranges);
12528                        });
12529                        editor.nav_history = nav_history;
12530                    });
12531                }
12532            })
12533        });
12534    }
12535
12536    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12537        let snapshot = self.buffer.read(cx).read(cx);
12538        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12539        Some(
12540            ranges
12541                .iter()
12542                .map(move |range| {
12543                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12544                })
12545                .collect(),
12546        )
12547    }
12548
12549    fn selection_replacement_ranges(
12550        &self,
12551        range: Range<OffsetUtf16>,
12552        cx: &mut AppContext,
12553    ) -> Vec<Range<OffsetUtf16>> {
12554        let selections = self.selections.all::<OffsetUtf16>(cx);
12555        let newest_selection = selections
12556            .iter()
12557            .max_by_key(|selection| selection.id)
12558            .unwrap();
12559        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12560        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12561        let snapshot = self.buffer.read(cx).read(cx);
12562        selections
12563            .into_iter()
12564            .map(|mut selection| {
12565                selection.start.0 =
12566                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12567                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12568                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12569                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12570            })
12571            .collect()
12572    }
12573
12574    fn report_editor_event(
12575        &self,
12576        event_type: &'static str,
12577        file_extension: Option<String>,
12578        cx: &AppContext,
12579    ) {
12580        if cfg!(any(test, feature = "test-support")) {
12581            return;
12582        }
12583
12584        let Some(project) = &self.project else { return };
12585
12586        // If None, we are in a file without an extension
12587        let file = self
12588            .buffer
12589            .read(cx)
12590            .as_singleton()
12591            .and_then(|b| b.read(cx).file());
12592        let file_extension = file_extension.or(file
12593            .as_ref()
12594            .and_then(|file| Path::new(file.file_name(cx)).extension())
12595            .and_then(|e| e.to_str())
12596            .map(|a| a.to_string()));
12597
12598        let vim_mode = cx
12599            .global::<SettingsStore>()
12600            .raw_user_settings()
12601            .get("vim_mode")
12602            == Some(&serde_json::Value::Bool(true));
12603
12604        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12605            == language::language_settings::InlineCompletionProvider::Copilot;
12606        let copilot_enabled_for_language = self
12607            .buffer
12608            .read(cx)
12609            .settings_at(0, cx)
12610            .show_inline_completions;
12611
12612        let project = project.read(cx);
12613        telemetry::event!(
12614            event_type,
12615            file_extension,
12616            vim_mode,
12617            copilot_enabled,
12618            copilot_enabled_for_language,
12619            is_via_ssh = project.is_via_ssh(),
12620        );
12621    }
12622
12623    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12624    /// with each line being an array of {text, highlight} objects.
12625    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12626        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12627            return;
12628        };
12629
12630        #[derive(Serialize)]
12631        struct Chunk<'a> {
12632            text: String,
12633            highlight: Option<&'a str>,
12634        }
12635
12636        let snapshot = buffer.read(cx).snapshot();
12637        let range = self
12638            .selected_text_range(false, cx)
12639            .and_then(|selection| {
12640                if selection.range.is_empty() {
12641                    None
12642                } else {
12643                    Some(selection.range)
12644                }
12645            })
12646            .unwrap_or_else(|| 0..snapshot.len());
12647
12648        let chunks = snapshot.chunks(range, true);
12649        let mut lines = Vec::new();
12650        let mut line: VecDeque<Chunk> = VecDeque::new();
12651
12652        let Some(style) = self.style.as_ref() else {
12653            return;
12654        };
12655
12656        for chunk in chunks {
12657            let highlight = chunk
12658                .syntax_highlight_id
12659                .and_then(|id| id.name(&style.syntax));
12660            let mut chunk_lines = chunk.text.split('\n').peekable();
12661            while let Some(text) = chunk_lines.next() {
12662                let mut merged_with_last_token = false;
12663                if let Some(last_token) = line.back_mut() {
12664                    if last_token.highlight == highlight {
12665                        last_token.text.push_str(text);
12666                        merged_with_last_token = true;
12667                    }
12668                }
12669
12670                if !merged_with_last_token {
12671                    line.push_back(Chunk {
12672                        text: text.into(),
12673                        highlight,
12674                    });
12675                }
12676
12677                if chunk_lines.peek().is_some() {
12678                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12679                        line.pop_front();
12680                    }
12681                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12682                        line.pop_back();
12683                    }
12684
12685                    lines.push(mem::take(&mut line));
12686                }
12687            }
12688        }
12689
12690        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12691            return;
12692        };
12693        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12694    }
12695
12696    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12697        self.request_autoscroll(Autoscroll::newest(), cx);
12698        let position = self.selections.newest_display(cx).start;
12699        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12700    }
12701
12702    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12703        &self.inlay_hint_cache
12704    }
12705
12706    pub fn replay_insert_event(
12707        &mut self,
12708        text: &str,
12709        relative_utf16_range: Option<Range<isize>>,
12710        cx: &mut ViewContext<Self>,
12711    ) {
12712        if !self.input_enabled {
12713            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12714            return;
12715        }
12716        if let Some(relative_utf16_range) = relative_utf16_range {
12717            let selections = self.selections.all::<OffsetUtf16>(cx);
12718            self.change_selections(None, cx, |s| {
12719                let new_ranges = selections.into_iter().map(|range| {
12720                    let start = OffsetUtf16(
12721                        range
12722                            .head()
12723                            .0
12724                            .saturating_add_signed(relative_utf16_range.start),
12725                    );
12726                    let end = OffsetUtf16(
12727                        range
12728                            .head()
12729                            .0
12730                            .saturating_add_signed(relative_utf16_range.end),
12731                    );
12732                    start..end
12733                });
12734                s.select_ranges(new_ranges);
12735            });
12736        }
12737
12738        self.handle_input(text, cx);
12739    }
12740
12741    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12742        let Some(provider) = self.semantics_provider.as_ref() else {
12743            return false;
12744        };
12745
12746        let mut supports = false;
12747        self.buffer().read(cx).for_each_buffer(|buffer| {
12748            supports |= provider.supports_inlay_hints(buffer, cx);
12749        });
12750        supports
12751    }
12752
12753    pub fn focus(&self, cx: &mut WindowContext) {
12754        cx.focus(&self.focus_handle)
12755    }
12756
12757    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12758        self.focus_handle.is_focused(cx)
12759    }
12760
12761    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12762        cx.emit(EditorEvent::Focused);
12763
12764        if let Some(descendant) = self
12765            .last_focused_descendant
12766            .take()
12767            .and_then(|descendant| descendant.upgrade())
12768        {
12769            cx.focus(&descendant);
12770        } else {
12771            if let Some(blame) = self.blame.as_ref() {
12772                blame.update(cx, GitBlame::focus)
12773            }
12774
12775            self.blink_manager.update(cx, BlinkManager::enable);
12776            self.show_cursor_names(cx);
12777            self.buffer.update(cx, |buffer, cx| {
12778                buffer.finalize_last_transaction(cx);
12779                if self.leader_peer_id.is_none() {
12780                    buffer.set_active_selections(
12781                        &self.selections.disjoint_anchors(),
12782                        self.selections.line_mode,
12783                        self.cursor_shape,
12784                        cx,
12785                    );
12786                }
12787            });
12788        }
12789    }
12790
12791    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12792        cx.emit(EditorEvent::FocusedIn)
12793    }
12794
12795    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12796        if event.blurred != self.focus_handle {
12797            self.last_focused_descendant = Some(event.blurred);
12798        }
12799    }
12800
12801    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12802        self.blink_manager.update(cx, BlinkManager::disable);
12803        self.buffer
12804            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12805
12806        if let Some(blame) = self.blame.as_ref() {
12807            blame.update(cx, GitBlame::blur)
12808        }
12809        if !self.hover_state.focused(cx) {
12810            hide_hover(self, cx);
12811        }
12812
12813        self.hide_context_menu(cx);
12814        cx.emit(EditorEvent::Blurred);
12815        cx.notify();
12816    }
12817
12818    pub fn register_action<A: Action>(
12819        &mut self,
12820        listener: impl Fn(&A, &mut WindowContext) + 'static,
12821    ) -> Subscription {
12822        let id = self.next_editor_action_id.post_inc();
12823        let listener = Arc::new(listener);
12824        self.editor_actions.borrow_mut().insert(
12825            id,
12826            Box::new(move |cx| {
12827                let cx = cx.window_context();
12828                let listener = listener.clone();
12829                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12830                    let action = action.downcast_ref().unwrap();
12831                    if phase == DispatchPhase::Bubble {
12832                        listener(action, cx)
12833                    }
12834                })
12835            }),
12836        );
12837
12838        let editor_actions = self.editor_actions.clone();
12839        Subscription::new(move || {
12840            editor_actions.borrow_mut().remove(&id);
12841        })
12842    }
12843
12844    pub fn file_header_size(&self) -> u32 {
12845        FILE_HEADER_HEIGHT
12846    }
12847
12848    pub fn revert(
12849        &mut self,
12850        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12851        cx: &mut ViewContext<Self>,
12852    ) {
12853        self.buffer().update(cx, |multi_buffer, cx| {
12854            for (buffer_id, changes) in revert_changes {
12855                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12856                    buffer.update(cx, |buffer, cx| {
12857                        buffer.edit(
12858                            changes.into_iter().map(|(range, text)| {
12859                                (range, text.to_string().map(Arc::<str>::from))
12860                            }),
12861                            None,
12862                            cx,
12863                        );
12864                    });
12865                }
12866            }
12867        });
12868        self.change_selections(None, cx, |selections| selections.refresh());
12869    }
12870
12871    pub fn to_pixel_point(
12872        &mut self,
12873        source: multi_buffer::Anchor,
12874        editor_snapshot: &EditorSnapshot,
12875        cx: &mut ViewContext<Self>,
12876    ) -> Option<gpui::Point<Pixels>> {
12877        let source_point = source.to_display_point(editor_snapshot);
12878        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12879    }
12880
12881    pub fn display_to_pixel_point(
12882        &self,
12883        source: DisplayPoint,
12884        editor_snapshot: &EditorSnapshot,
12885        cx: &WindowContext,
12886    ) -> Option<gpui::Point<Pixels>> {
12887        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12888        let text_layout_details = self.text_layout_details(cx);
12889        let scroll_top = text_layout_details
12890            .scroll_anchor
12891            .scroll_position(editor_snapshot)
12892            .y;
12893
12894        if source.row().as_f32() < scroll_top.floor() {
12895            return None;
12896        }
12897        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12898        let source_y = line_height * (source.row().as_f32() - scroll_top);
12899        Some(gpui::Point::new(source_x, source_y))
12900    }
12901
12902    pub fn has_active_completions_menu(&self) -> bool {
12903        self.context_menu.borrow().as_ref().map_or(false, |menu| {
12904            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12905        })
12906    }
12907
12908    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12909        self.addons
12910            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12911    }
12912
12913    pub fn unregister_addon<T: Addon>(&mut self) {
12914        self.addons.remove(&std::any::TypeId::of::<T>());
12915    }
12916
12917    pub fn addon<T: Addon>(&self) -> Option<&T> {
12918        let type_id = std::any::TypeId::of::<T>();
12919        self.addons
12920            .get(&type_id)
12921            .and_then(|item| item.to_any().downcast_ref::<T>())
12922    }
12923
12924    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12925        let text_layout_details = self.text_layout_details(cx);
12926        let style = &text_layout_details.editor_style;
12927        let font_id = cx.text_system().resolve_font(&style.text.font());
12928        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12929        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12930
12931        let em_width = cx
12932            .text_system()
12933            .typographic_bounds(font_id, font_size, 'm')
12934            .unwrap()
12935            .size
12936            .width;
12937
12938        gpui::Point::new(em_width, line_height)
12939    }
12940}
12941
12942fn get_unstaged_changes_for_buffers(
12943    project: &Model<Project>,
12944    buffers: impl IntoIterator<Item = Model<Buffer>>,
12945    cx: &mut ViewContext<Editor>,
12946) {
12947    let mut tasks = Vec::new();
12948    project.update(cx, |project, cx| {
12949        for buffer in buffers {
12950            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12951        }
12952    });
12953    cx.spawn(|this, mut cx| async move {
12954        let change_sets = futures::future::join_all(tasks).await;
12955        this.update(&mut cx, |this, cx| {
12956            for change_set in change_sets {
12957                if let Some(change_set) = change_set.log_err() {
12958                    this.diff_map.add_change_set(change_set, cx);
12959                }
12960            }
12961        })
12962        .ok();
12963    })
12964    .detach();
12965}
12966
12967fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12968    let tab_size = tab_size.get() as usize;
12969    let mut width = offset;
12970
12971    for ch in text.chars() {
12972        width += if ch == '\t' {
12973            tab_size - (width % tab_size)
12974        } else {
12975            1
12976        };
12977    }
12978
12979    width - offset
12980}
12981
12982#[cfg(test)]
12983mod tests {
12984    use super::*;
12985
12986    #[test]
12987    fn test_string_size_with_expanded_tabs() {
12988        let nz = |val| NonZeroU32::new(val).unwrap();
12989        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12990        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12991        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12992        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12993        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
12994        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
12995        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
12996        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
12997    }
12998}
12999
13000/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13001struct WordBreakingTokenizer<'a> {
13002    input: &'a str,
13003}
13004
13005impl<'a> WordBreakingTokenizer<'a> {
13006    fn new(input: &'a str) -> Self {
13007        Self { input }
13008    }
13009}
13010
13011fn is_char_ideographic(ch: char) -> bool {
13012    use unicode_script::Script::*;
13013    use unicode_script::UnicodeScript;
13014    matches!(ch.script(), Han | Tangut | Yi)
13015}
13016
13017fn is_grapheme_ideographic(text: &str) -> bool {
13018    text.chars().any(is_char_ideographic)
13019}
13020
13021fn is_grapheme_whitespace(text: &str) -> bool {
13022    text.chars().any(|x| x.is_whitespace())
13023}
13024
13025fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13026    text.chars().next().map_or(false, |ch| {
13027        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13028    })
13029}
13030
13031#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13032struct WordBreakToken<'a> {
13033    token: &'a str,
13034    grapheme_len: usize,
13035    is_whitespace: bool,
13036}
13037
13038impl<'a> Iterator for WordBreakingTokenizer<'a> {
13039    /// Yields a span, the count of graphemes in the token, and whether it was
13040    /// whitespace. Note that it also breaks at word boundaries.
13041    type Item = WordBreakToken<'a>;
13042
13043    fn next(&mut self) -> Option<Self::Item> {
13044        use unicode_segmentation::UnicodeSegmentation;
13045        if self.input.is_empty() {
13046            return None;
13047        }
13048
13049        let mut iter = self.input.graphemes(true).peekable();
13050        let mut offset = 0;
13051        let mut graphemes = 0;
13052        if let Some(first_grapheme) = iter.next() {
13053            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13054            offset += first_grapheme.len();
13055            graphemes += 1;
13056            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13057                if let Some(grapheme) = iter.peek().copied() {
13058                    if should_stay_with_preceding_ideograph(grapheme) {
13059                        offset += grapheme.len();
13060                        graphemes += 1;
13061                    }
13062                }
13063            } else {
13064                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13065                let mut next_word_bound = words.peek().copied();
13066                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13067                    next_word_bound = words.next();
13068                }
13069                while let Some(grapheme) = iter.peek().copied() {
13070                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13071                        break;
13072                    };
13073                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13074                        break;
13075                    };
13076                    offset += grapheme.len();
13077                    graphemes += 1;
13078                    iter.next();
13079                }
13080            }
13081            let token = &self.input[..offset];
13082            self.input = &self.input[offset..];
13083            if is_whitespace {
13084                Some(WordBreakToken {
13085                    token: " ",
13086                    grapheme_len: 1,
13087                    is_whitespace: true,
13088                })
13089            } else {
13090                Some(WordBreakToken {
13091                    token,
13092                    grapheme_len: graphemes,
13093                    is_whitespace: false,
13094                })
13095            }
13096        } else {
13097            None
13098        }
13099    }
13100}
13101
13102#[test]
13103fn test_word_breaking_tokenizer() {
13104    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13105        ("", &[]),
13106        ("  ", &[(" ", 1, true)]),
13107        ("Ʒ", &[("Ʒ", 1, false)]),
13108        ("Ǽ", &[("Ǽ", 1, false)]),
13109        ("", &[("", 1, false)]),
13110        ("⋑⋑", &[("⋑⋑", 2, false)]),
13111        (
13112            "原理,进而",
13113            &[
13114                ("", 1, false),
13115                ("理,", 2, false),
13116                ("", 1, false),
13117                ("", 1, false),
13118            ],
13119        ),
13120        (
13121            "hello world",
13122            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13123        ),
13124        (
13125            "hello, world",
13126            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13127        ),
13128        (
13129            "  hello world",
13130            &[
13131                (" ", 1, true),
13132                ("hello", 5, false),
13133                (" ", 1, true),
13134                ("world", 5, false),
13135            ],
13136        ),
13137        (
13138            "这是什么 \n 钢笔",
13139            &[
13140                ("", 1, false),
13141                ("", 1, false),
13142                ("", 1, false),
13143                ("", 1, false),
13144                (" ", 1, true),
13145                ("", 1, false),
13146                ("", 1, false),
13147            ],
13148        ),
13149        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13150    ];
13151
13152    for (input, result) in tests {
13153        assert_eq!(
13154            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13155            result
13156                .iter()
13157                .copied()
13158                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13159                    token,
13160                    grapheme_len,
13161                    is_whitespace,
13162                })
13163                .collect::<Vec<_>>()
13164        );
13165    }
13166}
13167
13168fn wrap_with_prefix(
13169    line_prefix: String,
13170    unwrapped_text: String,
13171    wrap_column: usize,
13172    tab_size: NonZeroU32,
13173) -> String {
13174    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13175    let mut wrapped_text = String::new();
13176    let mut current_line = line_prefix.clone();
13177
13178    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13179    let mut current_line_len = line_prefix_len;
13180    for WordBreakToken {
13181        token,
13182        grapheme_len,
13183        is_whitespace,
13184    } in tokenizer
13185    {
13186        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13187            wrapped_text.push_str(current_line.trim_end());
13188            wrapped_text.push('\n');
13189            current_line.truncate(line_prefix.len());
13190            current_line_len = line_prefix_len;
13191            if !is_whitespace {
13192                current_line.push_str(token);
13193                current_line_len += grapheme_len;
13194            }
13195        } else if !is_whitespace {
13196            current_line.push_str(token);
13197            current_line_len += grapheme_len;
13198        } else if current_line_len != line_prefix_len {
13199            current_line.push(' ');
13200            current_line_len += 1;
13201        }
13202    }
13203
13204    if !current_line.is_empty() {
13205        wrapped_text.push_str(&current_line);
13206    }
13207    wrapped_text
13208}
13209
13210#[test]
13211fn test_wrap_with_prefix() {
13212    assert_eq!(
13213        wrap_with_prefix(
13214            "# ".to_string(),
13215            "abcdefg".to_string(),
13216            4,
13217            NonZeroU32::new(4).unwrap()
13218        ),
13219        "# abcdefg"
13220    );
13221    assert_eq!(
13222        wrap_with_prefix(
13223            "".to_string(),
13224            "\thello world".to_string(),
13225            8,
13226            NonZeroU32::new(4).unwrap()
13227        ),
13228        "hello\nworld"
13229    );
13230    assert_eq!(
13231        wrap_with_prefix(
13232            "// ".to_string(),
13233            "xx \nyy zz aa bb cc".to_string(),
13234            12,
13235            NonZeroU32::new(4).unwrap()
13236        ),
13237        "// xx yy zz\n// aa bb cc"
13238    );
13239    assert_eq!(
13240        wrap_with_prefix(
13241            String::new(),
13242            "这是什么 \n 钢笔".to_string(),
13243            3,
13244            NonZeroU32::new(4).unwrap()
13245        ),
13246        "这是什\n么 钢\n"
13247    );
13248}
13249
13250fn hunks_for_selections(
13251    snapshot: &EditorSnapshot,
13252    selections: &[Selection<Point>],
13253) -> Vec<MultiBufferDiffHunk> {
13254    hunks_for_ranges(
13255        selections.iter().map(|selection| selection.range()),
13256        snapshot,
13257    )
13258}
13259
13260pub fn hunks_for_ranges(
13261    ranges: impl Iterator<Item = Range<Point>>,
13262    snapshot: &EditorSnapshot,
13263) -> Vec<MultiBufferDiffHunk> {
13264    let mut hunks = Vec::new();
13265    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13266        HashMap::default();
13267    for query_range in ranges {
13268        let query_rows =
13269            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13270        for hunk in snapshot.diff_map.diff_hunks_in_range(
13271            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13272            &snapshot.buffer_snapshot,
13273        ) {
13274            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13275            // when the caret is just above or just below the deleted hunk.
13276            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13277            let related_to_selection = if allow_adjacent {
13278                hunk.row_range.overlaps(&query_rows)
13279                    || hunk.row_range.start == query_rows.end
13280                    || hunk.row_range.end == query_rows.start
13281            } else {
13282                hunk.row_range.overlaps(&query_rows)
13283            };
13284            if related_to_selection {
13285                if !processed_buffer_rows
13286                    .entry(hunk.buffer_id)
13287                    .or_default()
13288                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13289                {
13290                    continue;
13291                }
13292                hunks.push(hunk);
13293            }
13294        }
13295    }
13296
13297    hunks
13298}
13299
13300pub trait CollaborationHub {
13301    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13302    fn user_participant_indices<'a>(
13303        &self,
13304        cx: &'a AppContext,
13305    ) -> &'a HashMap<u64, ParticipantIndex>;
13306    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13307}
13308
13309impl CollaborationHub for Model<Project> {
13310    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13311        self.read(cx).collaborators()
13312    }
13313
13314    fn user_participant_indices<'a>(
13315        &self,
13316        cx: &'a AppContext,
13317    ) -> &'a HashMap<u64, ParticipantIndex> {
13318        self.read(cx).user_store().read(cx).participant_indices()
13319    }
13320
13321    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13322        let this = self.read(cx);
13323        let user_ids = this.collaborators().values().map(|c| c.user_id);
13324        this.user_store().read_with(cx, |user_store, cx| {
13325            user_store.participant_names(user_ids, cx)
13326        })
13327    }
13328}
13329
13330pub trait SemanticsProvider {
13331    fn hover(
13332        &self,
13333        buffer: &Model<Buffer>,
13334        position: text::Anchor,
13335        cx: &mut AppContext,
13336    ) -> Option<Task<Vec<project::Hover>>>;
13337
13338    fn inlay_hints(
13339        &self,
13340        buffer_handle: Model<Buffer>,
13341        range: Range<text::Anchor>,
13342        cx: &mut AppContext,
13343    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13344
13345    fn resolve_inlay_hint(
13346        &self,
13347        hint: InlayHint,
13348        buffer_handle: Model<Buffer>,
13349        server_id: LanguageServerId,
13350        cx: &mut AppContext,
13351    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13352
13353    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13354
13355    fn document_highlights(
13356        &self,
13357        buffer: &Model<Buffer>,
13358        position: text::Anchor,
13359        cx: &mut AppContext,
13360    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13361
13362    fn definitions(
13363        &self,
13364        buffer: &Model<Buffer>,
13365        position: text::Anchor,
13366        kind: GotoDefinitionKind,
13367        cx: &mut AppContext,
13368    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13369
13370    fn range_for_rename(
13371        &self,
13372        buffer: &Model<Buffer>,
13373        position: text::Anchor,
13374        cx: &mut AppContext,
13375    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13376
13377    fn perform_rename(
13378        &self,
13379        buffer: &Model<Buffer>,
13380        position: text::Anchor,
13381        new_name: String,
13382        cx: &mut AppContext,
13383    ) -> Option<Task<Result<ProjectTransaction>>>;
13384}
13385
13386pub trait CompletionProvider {
13387    fn completions(
13388        &self,
13389        buffer: &Model<Buffer>,
13390        buffer_position: text::Anchor,
13391        trigger: CompletionContext,
13392        cx: &mut ViewContext<Editor>,
13393    ) -> Task<Result<Vec<Completion>>>;
13394
13395    fn resolve_completions(
13396        &self,
13397        buffer: Model<Buffer>,
13398        completion_indices: Vec<usize>,
13399        completions: Rc<RefCell<Box<[Completion]>>>,
13400        cx: &mut ViewContext<Editor>,
13401    ) -> Task<Result<bool>>;
13402
13403    fn apply_additional_edits_for_completion(
13404        &self,
13405        buffer: Model<Buffer>,
13406        completion: Completion,
13407        push_to_history: bool,
13408        cx: &mut ViewContext<Editor>,
13409    ) -> Task<Result<Option<language::Transaction>>>;
13410
13411    fn is_completion_trigger(
13412        &self,
13413        buffer: &Model<Buffer>,
13414        position: language::Anchor,
13415        text: &str,
13416        trigger_in_words: bool,
13417        cx: &mut ViewContext<Editor>,
13418    ) -> bool;
13419
13420    fn sort_completions(&self) -> bool {
13421        true
13422    }
13423}
13424
13425pub trait CodeActionProvider {
13426    fn code_actions(
13427        &self,
13428        buffer: &Model<Buffer>,
13429        range: Range<text::Anchor>,
13430        cx: &mut WindowContext,
13431    ) -> Task<Result<Vec<CodeAction>>>;
13432
13433    fn apply_code_action(
13434        &self,
13435        buffer_handle: Model<Buffer>,
13436        action: CodeAction,
13437        excerpt_id: ExcerptId,
13438        push_to_history: bool,
13439        cx: &mut WindowContext,
13440    ) -> Task<Result<ProjectTransaction>>;
13441}
13442
13443impl CodeActionProvider for Model<Project> {
13444    fn code_actions(
13445        &self,
13446        buffer: &Model<Buffer>,
13447        range: Range<text::Anchor>,
13448        cx: &mut WindowContext,
13449    ) -> Task<Result<Vec<CodeAction>>> {
13450        self.update(cx, |project, cx| {
13451            project.code_actions(buffer, range, None, cx)
13452        })
13453    }
13454
13455    fn apply_code_action(
13456        &self,
13457        buffer_handle: Model<Buffer>,
13458        action: CodeAction,
13459        _excerpt_id: ExcerptId,
13460        push_to_history: bool,
13461        cx: &mut WindowContext,
13462    ) -> Task<Result<ProjectTransaction>> {
13463        self.update(cx, |project, cx| {
13464            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13465        })
13466    }
13467}
13468
13469fn snippet_completions(
13470    project: &Project,
13471    buffer: &Model<Buffer>,
13472    buffer_position: text::Anchor,
13473    cx: &mut AppContext,
13474) -> Task<Result<Vec<Completion>>> {
13475    let language = buffer.read(cx).language_at(buffer_position);
13476    let language_name = language.as_ref().map(|language| language.lsp_id());
13477    let snippet_store = project.snippets().read(cx);
13478    let snippets = snippet_store.snippets_for(language_name, cx);
13479
13480    if snippets.is_empty() {
13481        return Task::ready(Ok(vec![]));
13482    }
13483    let snapshot = buffer.read(cx).text_snapshot();
13484    let chars: String = snapshot
13485        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13486        .collect();
13487
13488    let scope = language.map(|language| language.default_scope());
13489    let executor = cx.background_executor().clone();
13490
13491    cx.background_executor().spawn(async move {
13492        let classifier = CharClassifier::new(scope).for_completion(true);
13493        let mut last_word = chars
13494            .chars()
13495            .take_while(|c| classifier.is_word(*c))
13496            .collect::<String>();
13497        last_word = last_word.chars().rev().collect();
13498
13499        if last_word.is_empty() {
13500            return Ok(vec![]);
13501        }
13502
13503        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13504        let to_lsp = |point: &text::Anchor| {
13505            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13506            point_to_lsp(end)
13507        };
13508        let lsp_end = to_lsp(&buffer_position);
13509
13510        let candidates = snippets
13511            .iter()
13512            .enumerate()
13513            .flat_map(|(ix, snippet)| {
13514                snippet
13515                    .prefix
13516                    .iter()
13517                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13518            })
13519            .collect::<Vec<StringMatchCandidate>>();
13520
13521        let mut matches = fuzzy::match_strings(
13522            &candidates,
13523            &last_word,
13524            last_word.chars().any(|c| c.is_uppercase()),
13525            100,
13526            &Default::default(),
13527            executor,
13528        )
13529        .await;
13530
13531        // Remove all candidates where the query's start does not match the start of any word in the candidate
13532        if let Some(query_start) = last_word.chars().next() {
13533            matches.retain(|string_match| {
13534                split_words(&string_match.string).any(|word| {
13535                    // Check that the first codepoint of the word as lowercase matches the first
13536                    // codepoint of the query as lowercase
13537                    word.chars()
13538                        .flat_map(|codepoint| codepoint.to_lowercase())
13539                        .zip(query_start.to_lowercase())
13540                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13541                })
13542            });
13543        }
13544
13545        let matched_strings = matches
13546            .into_iter()
13547            .map(|m| m.string)
13548            .collect::<HashSet<_>>();
13549
13550        let result: Vec<Completion> = snippets
13551            .into_iter()
13552            .filter_map(|snippet| {
13553                let matching_prefix = snippet
13554                    .prefix
13555                    .iter()
13556                    .find(|prefix| matched_strings.contains(*prefix))?;
13557                let start = as_offset - last_word.len();
13558                let start = snapshot.anchor_before(start);
13559                let range = start..buffer_position;
13560                let lsp_start = to_lsp(&start);
13561                let lsp_range = lsp::Range {
13562                    start: lsp_start,
13563                    end: lsp_end,
13564                };
13565                Some(Completion {
13566                    old_range: range,
13567                    new_text: snippet.body.clone(),
13568                    label: CodeLabel {
13569                        text: matching_prefix.clone(),
13570                        runs: vec![],
13571                        filter_range: 0..matching_prefix.len(),
13572                    },
13573                    server_id: LanguageServerId(usize::MAX),
13574                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13575                    lsp_completion: lsp::CompletionItem {
13576                        label: snippet.prefix.first().unwrap().clone(),
13577                        kind: Some(CompletionItemKind::SNIPPET),
13578                        label_details: snippet.description.as_ref().map(|description| {
13579                            lsp::CompletionItemLabelDetails {
13580                                detail: Some(description.clone()),
13581                                description: None,
13582                            }
13583                        }),
13584                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13585                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13586                            lsp::InsertReplaceEdit {
13587                                new_text: snippet.body.clone(),
13588                                insert: lsp_range,
13589                                replace: lsp_range,
13590                            },
13591                        )),
13592                        filter_text: Some(snippet.body.clone()),
13593                        sort_text: Some(char::MAX.to_string()),
13594                        ..Default::default()
13595                    },
13596                    confirm: None,
13597                })
13598            })
13599            .collect();
13600
13601        Ok(result)
13602    })
13603}
13604
13605impl CompletionProvider for Model<Project> {
13606    fn completions(
13607        &self,
13608        buffer: &Model<Buffer>,
13609        buffer_position: text::Anchor,
13610        options: CompletionContext,
13611        cx: &mut ViewContext<Editor>,
13612    ) -> Task<Result<Vec<Completion>>> {
13613        self.update(cx, |project, cx| {
13614            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13615            let project_completions = project.completions(buffer, buffer_position, options, cx);
13616            cx.background_executor().spawn(async move {
13617                let mut completions = project_completions.await?;
13618                let snippets_completions = snippets.await?;
13619                completions.extend(snippets_completions);
13620                Ok(completions)
13621            })
13622        })
13623    }
13624
13625    fn resolve_completions(
13626        &self,
13627        buffer: Model<Buffer>,
13628        completion_indices: Vec<usize>,
13629        completions: Rc<RefCell<Box<[Completion]>>>,
13630        cx: &mut ViewContext<Editor>,
13631    ) -> Task<Result<bool>> {
13632        self.update(cx, |project, cx| {
13633            project.resolve_completions(buffer, completion_indices, completions, cx)
13634        })
13635    }
13636
13637    fn apply_additional_edits_for_completion(
13638        &self,
13639        buffer: Model<Buffer>,
13640        completion: Completion,
13641        push_to_history: bool,
13642        cx: &mut ViewContext<Editor>,
13643    ) -> Task<Result<Option<language::Transaction>>> {
13644        self.update(cx, |project, cx| {
13645            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13646        })
13647    }
13648
13649    fn is_completion_trigger(
13650        &self,
13651        buffer: &Model<Buffer>,
13652        position: language::Anchor,
13653        text: &str,
13654        trigger_in_words: bool,
13655        cx: &mut ViewContext<Editor>,
13656    ) -> bool {
13657        let mut chars = text.chars();
13658        let char = if let Some(char) = chars.next() {
13659            char
13660        } else {
13661            return false;
13662        };
13663        if chars.next().is_some() {
13664            return false;
13665        }
13666
13667        let buffer = buffer.read(cx);
13668        let snapshot = buffer.snapshot();
13669        if !snapshot.settings_at(position, cx).show_completions_on_input {
13670            return false;
13671        }
13672        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13673        if trigger_in_words && classifier.is_word(char) {
13674            return true;
13675        }
13676
13677        buffer.completion_triggers().contains(text)
13678    }
13679}
13680
13681impl SemanticsProvider for Model<Project> {
13682    fn hover(
13683        &self,
13684        buffer: &Model<Buffer>,
13685        position: text::Anchor,
13686        cx: &mut AppContext,
13687    ) -> Option<Task<Vec<project::Hover>>> {
13688        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13689    }
13690
13691    fn document_highlights(
13692        &self,
13693        buffer: &Model<Buffer>,
13694        position: text::Anchor,
13695        cx: &mut AppContext,
13696    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13697        Some(self.update(cx, |project, cx| {
13698            project.document_highlights(buffer, position, cx)
13699        }))
13700    }
13701
13702    fn definitions(
13703        &self,
13704        buffer: &Model<Buffer>,
13705        position: text::Anchor,
13706        kind: GotoDefinitionKind,
13707        cx: &mut AppContext,
13708    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13709        Some(self.update(cx, |project, cx| match kind {
13710            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13711            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13712            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13713            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13714        }))
13715    }
13716
13717    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13718        // TODO: make this work for remote projects
13719        self.read(cx)
13720            .language_servers_for_local_buffer(buffer.read(cx), cx)
13721            .any(
13722                |(_, server)| match server.capabilities().inlay_hint_provider {
13723                    Some(lsp::OneOf::Left(enabled)) => enabled,
13724                    Some(lsp::OneOf::Right(_)) => true,
13725                    None => false,
13726                },
13727            )
13728    }
13729
13730    fn inlay_hints(
13731        &self,
13732        buffer_handle: Model<Buffer>,
13733        range: Range<text::Anchor>,
13734        cx: &mut AppContext,
13735    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13736        Some(self.update(cx, |project, cx| {
13737            project.inlay_hints(buffer_handle, range, cx)
13738        }))
13739    }
13740
13741    fn resolve_inlay_hint(
13742        &self,
13743        hint: InlayHint,
13744        buffer_handle: Model<Buffer>,
13745        server_id: LanguageServerId,
13746        cx: &mut AppContext,
13747    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13748        Some(self.update(cx, |project, cx| {
13749            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13750        }))
13751    }
13752
13753    fn range_for_rename(
13754        &self,
13755        buffer: &Model<Buffer>,
13756        position: text::Anchor,
13757        cx: &mut AppContext,
13758    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13759        Some(self.update(cx, |project, cx| {
13760            project.prepare_rename(buffer.clone(), position, cx)
13761        }))
13762    }
13763
13764    fn perform_rename(
13765        &self,
13766        buffer: &Model<Buffer>,
13767        position: text::Anchor,
13768        new_name: String,
13769        cx: &mut AppContext,
13770    ) -> Option<Task<Result<ProjectTransaction>>> {
13771        Some(self.update(cx, |project, cx| {
13772            project.perform_rename(buffer.clone(), position, new_name, cx)
13773        }))
13774    }
13775}
13776
13777fn inlay_hint_settings(
13778    location: Anchor,
13779    snapshot: &MultiBufferSnapshot,
13780    cx: &mut ViewContext<'_, Editor>,
13781) -> InlayHintSettings {
13782    let file = snapshot.file_at(location);
13783    let language = snapshot.language_at(location).map(|l| l.name());
13784    language_settings(language, file, cx).inlay_hints
13785}
13786
13787fn consume_contiguous_rows(
13788    contiguous_row_selections: &mut Vec<Selection<Point>>,
13789    selection: &Selection<Point>,
13790    display_map: &DisplaySnapshot,
13791    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13792) -> (MultiBufferRow, MultiBufferRow) {
13793    contiguous_row_selections.push(selection.clone());
13794    let start_row = MultiBufferRow(selection.start.row);
13795    let mut end_row = ending_row(selection, display_map);
13796
13797    while let Some(next_selection) = selections.peek() {
13798        if next_selection.start.row <= end_row.0 {
13799            end_row = ending_row(next_selection, display_map);
13800            contiguous_row_selections.push(selections.next().unwrap().clone());
13801        } else {
13802            break;
13803        }
13804    }
13805    (start_row, end_row)
13806}
13807
13808fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13809    if next_selection.end.column > 0 || next_selection.is_empty() {
13810        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13811    } else {
13812        MultiBufferRow(next_selection.end.row)
13813    }
13814}
13815
13816impl EditorSnapshot {
13817    pub fn remote_selections_in_range<'a>(
13818        &'a self,
13819        range: &'a Range<Anchor>,
13820        collaboration_hub: &dyn CollaborationHub,
13821        cx: &'a AppContext,
13822    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13823        let participant_names = collaboration_hub.user_names(cx);
13824        let participant_indices = collaboration_hub.user_participant_indices(cx);
13825        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13826        let collaborators_by_replica_id = collaborators_by_peer_id
13827            .iter()
13828            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13829            .collect::<HashMap<_, _>>();
13830        self.buffer_snapshot
13831            .selections_in_range(range, false)
13832            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13833                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13834                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13835                let user_name = participant_names.get(&collaborator.user_id).cloned();
13836                Some(RemoteSelection {
13837                    replica_id,
13838                    selection,
13839                    cursor_shape,
13840                    line_mode,
13841                    participant_index,
13842                    peer_id: collaborator.peer_id,
13843                    user_name,
13844                })
13845            })
13846    }
13847
13848    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13849        self.display_snapshot.buffer_snapshot.language_at(position)
13850    }
13851
13852    pub fn is_focused(&self) -> bool {
13853        self.is_focused
13854    }
13855
13856    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13857        self.placeholder_text.as_ref()
13858    }
13859
13860    pub fn scroll_position(&self) -> gpui::Point<f32> {
13861        self.scroll_anchor.scroll_position(&self.display_snapshot)
13862    }
13863
13864    fn gutter_dimensions(
13865        &self,
13866        font_id: FontId,
13867        font_size: Pixels,
13868        em_width: Pixels,
13869        em_advance: Pixels,
13870        max_line_number_width: Pixels,
13871        cx: &AppContext,
13872    ) -> GutterDimensions {
13873        if !self.show_gutter {
13874            return GutterDimensions::default();
13875        }
13876        let descent = cx.text_system().descent(font_id, font_size);
13877
13878        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13879            matches!(
13880                ProjectSettings::get_global(cx).git.git_gutter,
13881                Some(GitGutterSetting::TrackedFiles)
13882            )
13883        });
13884        let gutter_settings = EditorSettings::get_global(cx).gutter;
13885        let show_line_numbers = self
13886            .show_line_numbers
13887            .unwrap_or(gutter_settings.line_numbers);
13888        let line_gutter_width = if show_line_numbers {
13889            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13890            let min_width_for_number_on_gutter = em_advance * 4.0;
13891            max_line_number_width.max(min_width_for_number_on_gutter)
13892        } else {
13893            0.0.into()
13894        };
13895
13896        let show_code_actions = self
13897            .show_code_actions
13898            .unwrap_or(gutter_settings.code_actions);
13899
13900        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13901
13902        let git_blame_entries_width =
13903            self.git_blame_gutter_max_author_length
13904                .map(|max_author_length| {
13905                    // Length of the author name, but also space for the commit hash,
13906                    // the spacing and the timestamp.
13907                    let max_char_count = max_author_length
13908                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13909                        + 7 // length of commit sha
13910                        + 14 // length of max relative timestamp ("60 minutes ago")
13911                        + 4; // gaps and margins
13912
13913                    em_advance * max_char_count
13914                });
13915
13916        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13917        left_padding += if show_code_actions || show_runnables {
13918            em_width * 3.0
13919        } else if show_git_gutter && show_line_numbers {
13920            em_width * 2.0
13921        } else if show_git_gutter || show_line_numbers {
13922            em_width
13923        } else {
13924            px(0.)
13925        };
13926
13927        let right_padding = if gutter_settings.folds && show_line_numbers {
13928            em_width * 4.0
13929        } else if gutter_settings.folds {
13930            em_width * 3.0
13931        } else if show_line_numbers {
13932            em_width
13933        } else {
13934            px(0.)
13935        };
13936
13937        GutterDimensions {
13938            left_padding,
13939            right_padding,
13940            width: line_gutter_width + left_padding + right_padding,
13941            margin: -descent,
13942            git_blame_entries_width,
13943        }
13944    }
13945
13946    pub fn render_crease_toggle(
13947        &self,
13948        buffer_row: MultiBufferRow,
13949        row_contains_cursor: bool,
13950        editor: View<Editor>,
13951        cx: &mut WindowContext,
13952    ) -> Option<AnyElement> {
13953        let folded = self.is_line_folded(buffer_row);
13954        let mut is_foldable = false;
13955
13956        if let Some(crease) = self
13957            .crease_snapshot
13958            .query_row(buffer_row, &self.buffer_snapshot)
13959        {
13960            is_foldable = true;
13961            match crease {
13962                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13963                    if let Some(render_toggle) = render_toggle {
13964                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13965                            if folded {
13966                                editor.update(cx, |editor, cx| {
13967                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13968                                });
13969                            } else {
13970                                editor.update(cx, |editor, cx| {
13971                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13972                                });
13973                            }
13974                        });
13975                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13976                    }
13977                }
13978            }
13979        }
13980
13981        is_foldable |= self.starts_indent(buffer_row);
13982
13983        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13984            Some(
13985                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13986                    .toggle_state(folded)
13987                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13988                        if folded {
13989                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13990                        } else {
13991                            this.fold_at(&FoldAt { buffer_row }, cx);
13992                        }
13993                    }))
13994                    .into_any_element(),
13995            )
13996        } else {
13997            None
13998        }
13999    }
14000
14001    pub fn render_crease_trailer(
14002        &self,
14003        buffer_row: MultiBufferRow,
14004        cx: &mut WindowContext,
14005    ) -> Option<AnyElement> {
14006        let folded = self.is_line_folded(buffer_row);
14007        if let Crease::Inline { render_trailer, .. } = self
14008            .crease_snapshot
14009            .query_row(buffer_row, &self.buffer_snapshot)?
14010        {
14011            let render_trailer = render_trailer.as_ref()?;
14012            Some(render_trailer(buffer_row, folded, cx))
14013        } else {
14014            None
14015        }
14016    }
14017}
14018
14019impl Deref for EditorSnapshot {
14020    type Target = DisplaySnapshot;
14021
14022    fn deref(&self) -> &Self::Target {
14023        &self.display_snapshot
14024    }
14025}
14026
14027#[derive(Clone, Debug, PartialEq, Eq)]
14028pub enum EditorEvent {
14029    InputIgnored {
14030        text: Arc<str>,
14031    },
14032    InputHandled {
14033        utf16_range_to_replace: Option<Range<isize>>,
14034        text: Arc<str>,
14035    },
14036    ExcerptsAdded {
14037        buffer: Model<Buffer>,
14038        predecessor: ExcerptId,
14039        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14040    },
14041    ExcerptsRemoved {
14042        ids: Vec<ExcerptId>,
14043    },
14044    BufferFoldToggled {
14045        ids: Vec<ExcerptId>,
14046        folded: bool,
14047    },
14048    ExcerptsEdited {
14049        ids: Vec<ExcerptId>,
14050    },
14051    ExcerptsExpanded {
14052        ids: Vec<ExcerptId>,
14053    },
14054    BufferEdited,
14055    Edited {
14056        transaction_id: clock::Lamport,
14057    },
14058    Reparsed(BufferId),
14059    Focused,
14060    FocusedIn,
14061    Blurred,
14062    DirtyChanged,
14063    Saved,
14064    TitleChanged,
14065    DiffBaseChanged,
14066    SelectionsChanged {
14067        local: bool,
14068    },
14069    ScrollPositionChanged {
14070        local: bool,
14071        autoscroll: bool,
14072    },
14073    Closed,
14074    TransactionUndone {
14075        transaction_id: clock::Lamport,
14076    },
14077    TransactionBegun {
14078        transaction_id: clock::Lamport,
14079    },
14080    Reloaded,
14081    CursorShapeChanged,
14082}
14083
14084impl EventEmitter<EditorEvent> for Editor {}
14085
14086impl FocusableView for Editor {
14087    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14088        self.focus_handle.clone()
14089    }
14090}
14091
14092impl Render for Editor {
14093    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14094        let settings = ThemeSettings::get_global(cx);
14095
14096        let mut text_style = match self.mode {
14097            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14098                color: cx.theme().colors().editor_foreground,
14099                font_family: settings.ui_font.family.clone(),
14100                font_features: settings.ui_font.features.clone(),
14101                font_fallbacks: settings.ui_font.fallbacks.clone(),
14102                font_size: rems(0.875).into(),
14103                font_weight: settings.ui_font.weight,
14104                line_height: relative(settings.buffer_line_height.value()),
14105                ..Default::default()
14106            },
14107            EditorMode::Full => TextStyle {
14108                color: cx.theme().colors().editor_foreground,
14109                font_family: settings.buffer_font.family.clone(),
14110                font_features: settings.buffer_font.features.clone(),
14111                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14112                font_size: settings.buffer_font_size(cx).into(),
14113                font_weight: settings.buffer_font.weight,
14114                line_height: relative(settings.buffer_line_height.value()),
14115                ..Default::default()
14116            },
14117        };
14118        if let Some(text_style_refinement) = &self.text_style_refinement {
14119            text_style.refine(text_style_refinement)
14120        }
14121
14122        let background = match self.mode {
14123            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14124            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14125            EditorMode::Full => cx.theme().colors().editor_background,
14126        };
14127
14128        EditorElement::new(
14129            cx.view(),
14130            EditorStyle {
14131                background,
14132                local_player: cx.theme().players().local(),
14133                text: text_style,
14134                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14135                syntax: cx.theme().syntax().clone(),
14136                status: cx.theme().status().clone(),
14137                inlay_hints_style: make_inlay_hints_style(cx),
14138                inline_completion_styles: make_suggestion_styles(cx),
14139                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14140            },
14141        )
14142    }
14143}
14144
14145impl ViewInputHandler for Editor {
14146    fn text_for_range(
14147        &mut self,
14148        range_utf16: Range<usize>,
14149        adjusted_range: &mut Option<Range<usize>>,
14150        cx: &mut ViewContext<Self>,
14151    ) -> Option<String> {
14152        let snapshot = self.buffer.read(cx).read(cx);
14153        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14154        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14155        if (start.0..end.0) != range_utf16 {
14156            adjusted_range.replace(start.0..end.0);
14157        }
14158        Some(snapshot.text_for_range(start..end).collect())
14159    }
14160
14161    fn selected_text_range(
14162        &mut self,
14163        ignore_disabled_input: bool,
14164        cx: &mut ViewContext<Self>,
14165    ) -> Option<UTF16Selection> {
14166        // Prevent the IME menu from appearing when holding down an alphabetic key
14167        // while input is disabled.
14168        if !ignore_disabled_input && !self.input_enabled {
14169            return None;
14170        }
14171
14172        let selection = self.selections.newest::<OffsetUtf16>(cx);
14173        let range = selection.range();
14174
14175        Some(UTF16Selection {
14176            range: range.start.0..range.end.0,
14177            reversed: selection.reversed,
14178        })
14179    }
14180
14181    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14182        let snapshot = self.buffer.read(cx).read(cx);
14183        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14184        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14185    }
14186
14187    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14188        self.clear_highlights::<InputComposition>(cx);
14189        self.ime_transaction.take();
14190    }
14191
14192    fn replace_text_in_range(
14193        &mut self,
14194        range_utf16: Option<Range<usize>>,
14195        text: &str,
14196        cx: &mut ViewContext<Self>,
14197    ) {
14198        if !self.input_enabled {
14199            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14200            return;
14201        }
14202
14203        self.transact(cx, |this, cx| {
14204            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14205                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14206                Some(this.selection_replacement_ranges(range_utf16, cx))
14207            } else {
14208                this.marked_text_ranges(cx)
14209            };
14210
14211            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14212                let newest_selection_id = this.selections.newest_anchor().id;
14213                this.selections
14214                    .all::<OffsetUtf16>(cx)
14215                    .iter()
14216                    .zip(ranges_to_replace.iter())
14217                    .find_map(|(selection, range)| {
14218                        if selection.id == newest_selection_id {
14219                            Some(
14220                                (range.start.0 as isize - selection.head().0 as isize)
14221                                    ..(range.end.0 as isize - selection.head().0 as isize),
14222                            )
14223                        } else {
14224                            None
14225                        }
14226                    })
14227            });
14228
14229            cx.emit(EditorEvent::InputHandled {
14230                utf16_range_to_replace: range_to_replace,
14231                text: text.into(),
14232            });
14233
14234            if let Some(new_selected_ranges) = new_selected_ranges {
14235                this.change_selections(None, cx, |selections| {
14236                    selections.select_ranges(new_selected_ranges)
14237                });
14238                this.backspace(&Default::default(), cx);
14239            }
14240
14241            this.handle_input(text, cx);
14242        });
14243
14244        if let Some(transaction) = self.ime_transaction {
14245            self.buffer.update(cx, |buffer, cx| {
14246                buffer.group_until_transaction(transaction, cx);
14247            });
14248        }
14249
14250        self.unmark_text(cx);
14251    }
14252
14253    fn replace_and_mark_text_in_range(
14254        &mut self,
14255        range_utf16: Option<Range<usize>>,
14256        text: &str,
14257        new_selected_range_utf16: Option<Range<usize>>,
14258        cx: &mut ViewContext<Self>,
14259    ) {
14260        if !self.input_enabled {
14261            return;
14262        }
14263
14264        let transaction = self.transact(cx, |this, cx| {
14265            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14266                let snapshot = this.buffer.read(cx).read(cx);
14267                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14268                    for marked_range in &mut marked_ranges {
14269                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14270                        marked_range.start.0 += relative_range_utf16.start;
14271                        marked_range.start =
14272                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14273                        marked_range.end =
14274                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14275                    }
14276                }
14277                Some(marked_ranges)
14278            } else if let Some(range_utf16) = range_utf16 {
14279                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14280                Some(this.selection_replacement_ranges(range_utf16, cx))
14281            } else {
14282                None
14283            };
14284
14285            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14286                let newest_selection_id = this.selections.newest_anchor().id;
14287                this.selections
14288                    .all::<OffsetUtf16>(cx)
14289                    .iter()
14290                    .zip(ranges_to_replace.iter())
14291                    .find_map(|(selection, range)| {
14292                        if selection.id == newest_selection_id {
14293                            Some(
14294                                (range.start.0 as isize - selection.head().0 as isize)
14295                                    ..(range.end.0 as isize - selection.head().0 as isize),
14296                            )
14297                        } else {
14298                            None
14299                        }
14300                    })
14301            });
14302
14303            cx.emit(EditorEvent::InputHandled {
14304                utf16_range_to_replace: range_to_replace,
14305                text: text.into(),
14306            });
14307
14308            if let Some(ranges) = ranges_to_replace {
14309                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14310            }
14311
14312            let marked_ranges = {
14313                let snapshot = this.buffer.read(cx).read(cx);
14314                this.selections
14315                    .disjoint_anchors()
14316                    .iter()
14317                    .map(|selection| {
14318                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14319                    })
14320                    .collect::<Vec<_>>()
14321            };
14322
14323            if text.is_empty() {
14324                this.unmark_text(cx);
14325            } else {
14326                this.highlight_text::<InputComposition>(
14327                    marked_ranges.clone(),
14328                    HighlightStyle {
14329                        underline: Some(UnderlineStyle {
14330                            thickness: px(1.),
14331                            color: None,
14332                            wavy: false,
14333                        }),
14334                        ..Default::default()
14335                    },
14336                    cx,
14337                );
14338            }
14339
14340            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14341            let use_autoclose = this.use_autoclose;
14342            let use_auto_surround = this.use_auto_surround;
14343            this.set_use_autoclose(false);
14344            this.set_use_auto_surround(false);
14345            this.handle_input(text, cx);
14346            this.set_use_autoclose(use_autoclose);
14347            this.set_use_auto_surround(use_auto_surround);
14348
14349            if let Some(new_selected_range) = new_selected_range_utf16 {
14350                let snapshot = this.buffer.read(cx).read(cx);
14351                let new_selected_ranges = marked_ranges
14352                    .into_iter()
14353                    .map(|marked_range| {
14354                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14355                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14356                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14357                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14358                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14359                    })
14360                    .collect::<Vec<_>>();
14361
14362                drop(snapshot);
14363                this.change_selections(None, cx, |selections| {
14364                    selections.select_ranges(new_selected_ranges)
14365                });
14366            }
14367        });
14368
14369        self.ime_transaction = self.ime_transaction.or(transaction);
14370        if let Some(transaction) = self.ime_transaction {
14371            self.buffer.update(cx, |buffer, cx| {
14372                buffer.group_until_transaction(transaction, cx);
14373            });
14374        }
14375
14376        if self.text_highlights::<InputComposition>(cx).is_none() {
14377            self.ime_transaction.take();
14378        }
14379    }
14380
14381    fn bounds_for_range(
14382        &mut self,
14383        range_utf16: Range<usize>,
14384        element_bounds: gpui::Bounds<Pixels>,
14385        cx: &mut ViewContext<Self>,
14386    ) -> Option<gpui::Bounds<Pixels>> {
14387        let text_layout_details = self.text_layout_details(cx);
14388        let gpui::Point {
14389            x: em_width,
14390            y: line_height,
14391        } = self.character_size(cx);
14392
14393        let snapshot = self.snapshot(cx);
14394        let scroll_position = snapshot.scroll_position();
14395        let scroll_left = scroll_position.x * em_width;
14396
14397        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14398        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14399            + self.gutter_dimensions.width
14400            + self.gutter_dimensions.margin;
14401        let y = line_height * (start.row().as_f32() - scroll_position.y);
14402
14403        Some(Bounds {
14404            origin: element_bounds.origin + point(x, y),
14405            size: size(em_width, line_height),
14406        })
14407    }
14408}
14409
14410trait SelectionExt {
14411    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14412    fn spanned_rows(
14413        &self,
14414        include_end_if_at_line_start: bool,
14415        map: &DisplaySnapshot,
14416    ) -> Range<MultiBufferRow>;
14417}
14418
14419impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14420    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14421        let start = self
14422            .start
14423            .to_point(&map.buffer_snapshot)
14424            .to_display_point(map);
14425        let end = self
14426            .end
14427            .to_point(&map.buffer_snapshot)
14428            .to_display_point(map);
14429        if self.reversed {
14430            end..start
14431        } else {
14432            start..end
14433        }
14434    }
14435
14436    fn spanned_rows(
14437        &self,
14438        include_end_if_at_line_start: bool,
14439        map: &DisplaySnapshot,
14440    ) -> Range<MultiBufferRow> {
14441        let start = self.start.to_point(&map.buffer_snapshot);
14442        let mut end = self.end.to_point(&map.buffer_snapshot);
14443        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14444            end.row -= 1;
14445        }
14446
14447        let buffer_start = map.prev_line_boundary(start).0;
14448        let buffer_end = map.next_line_boundary(end).0;
14449        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14450    }
14451}
14452
14453impl<T: InvalidationRegion> InvalidationStack<T> {
14454    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14455    where
14456        S: Clone + ToOffset,
14457    {
14458        while let Some(region) = self.last() {
14459            let all_selections_inside_invalidation_ranges =
14460                if selections.len() == region.ranges().len() {
14461                    selections
14462                        .iter()
14463                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14464                        .all(|(selection, invalidation_range)| {
14465                            let head = selection.head().to_offset(buffer);
14466                            invalidation_range.start <= head && invalidation_range.end >= head
14467                        })
14468                } else {
14469                    false
14470                };
14471
14472            if all_selections_inside_invalidation_ranges {
14473                break;
14474            } else {
14475                self.pop();
14476            }
14477        }
14478    }
14479}
14480
14481impl<T> Default for InvalidationStack<T> {
14482    fn default() -> Self {
14483        Self(Default::default())
14484    }
14485}
14486
14487impl<T> Deref for InvalidationStack<T> {
14488    type Target = Vec<T>;
14489
14490    fn deref(&self) -> &Self::Target {
14491        &self.0
14492    }
14493}
14494
14495impl<T> DerefMut for InvalidationStack<T> {
14496    fn deref_mut(&mut self) -> &mut Self::Target {
14497        &mut self.0
14498    }
14499}
14500
14501impl InvalidationRegion for SnippetState {
14502    fn ranges(&self) -> &[Range<Anchor>] {
14503        &self.ranges[self.active_index]
14504    }
14505}
14506
14507pub fn diagnostic_block_renderer(
14508    diagnostic: Diagnostic,
14509    max_message_rows: Option<u8>,
14510    allow_closing: bool,
14511    _is_valid: bool,
14512) -> RenderBlock {
14513    let (text_without_backticks, code_ranges) =
14514        highlight_diagnostic_message(&diagnostic, max_message_rows);
14515
14516    Arc::new(move |cx: &mut BlockContext| {
14517        let group_id: SharedString = cx.block_id.to_string().into();
14518
14519        let mut text_style = cx.text_style().clone();
14520        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14521        let theme_settings = ThemeSettings::get_global(cx);
14522        text_style.font_family = theme_settings.buffer_font.family.clone();
14523        text_style.font_style = theme_settings.buffer_font.style;
14524        text_style.font_features = theme_settings.buffer_font.features.clone();
14525        text_style.font_weight = theme_settings.buffer_font.weight;
14526
14527        let multi_line_diagnostic = diagnostic.message.contains('\n');
14528
14529        let buttons = |diagnostic: &Diagnostic| {
14530            if multi_line_diagnostic {
14531                v_flex()
14532            } else {
14533                h_flex()
14534            }
14535            .when(allow_closing, |div| {
14536                div.children(diagnostic.is_primary.then(|| {
14537                    IconButton::new("close-block", IconName::XCircle)
14538                        .icon_color(Color::Muted)
14539                        .size(ButtonSize::Compact)
14540                        .style(ButtonStyle::Transparent)
14541                        .visible_on_hover(group_id.clone())
14542                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14543                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14544                }))
14545            })
14546            .child(
14547                IconButton::new("copy-block", IconName::Copy)
14548                    .icon_color(Color::Muted)
14549                    .size(ButtonSize::Compact)
14550                    .style(ButtonStyle::Transparent)
14551                    .visible_on_hover(group_id.clone())
14552                    .on_click({
14553                        let message = diagnostic.message.clone();
14554                        move |_click, cx| {
14555                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14556                        }
14557                    })
14558                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14559            )
14560        };
14561
14562        let icon_size = buttons(&diagnostic)
14563            .into_any_element()
14564            .layout_as_root(AvailableSpace::min_size(), cx);
14565
14566        h_flex()
14567            .id(cx.block_id)
14568            .group(group_id.clone())
14569            .relative()
14570            .size_full()
14571            .block_mouse_down()
14572            .pl(cx.gutter_dimensions.width)
14573            .w(cx.max_width - cx.gutter_dimensions.full_width())
14574            .child(
14575                div()
14576                    .flex()
14577                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14578                    .flex_shrink(),
14579            )
14580            .child(buttons(&diagnostic))
14581            .child(div().flex().flex_shrink_0().child(
14582                StyledText::new(text_without_backticks.clone()).with_highlights(
14583                    &text_style,
14584                    code_ranges.iter().map(|range| {
14585                        (
14586                            range.clone(),
14587                            HighlightStyle {
14588                                font_weight: Some(FontWeight::BOLD),
14589                                ..Default::default()
14590                            },
14591                        )
14592                    }),
14593                ),
14594            ))
14595            .into_any_element()
14596    })
14597}
14598
14599fn inline_completion_edit_text(
14600    editor_snapshot: &EditorSnapshot,
14601    edits: &Vec<(Range<Anchor>, String)>,
14602    cx: &WindowContext,
14603) -> InlineCompletionText {
14604    let edit_start = edits
14605        .first()
14606        .unwrap()
14607        .0
14608        .start
14609        .to_display_point(editor_snapshot);
14610
14611    let mut text = String::new();
14612    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14613    let mut highlights = Vec::new();
14614    for (old_range, new_text) in edits {
14615        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14616        text.extend(
14617            editor_snapshot
14618                .buffer_snapshot
14619                .chunks(offset..old_offset_range.start, false)
14620                .map(|chunk| chunk.text),
14621        );
14622        offset = old_offset_range.end;
14623
14624        let start = text.len();
14625        text.push_str(new_text);
14626        let end = text.len();
14627        highlights.push((
14628            start..end,
14629            HighlightStyle {
14630                background_color: Some(cx.theme().status().created_background),
14631                ..Default::default()
14632            },
14633        ));
14634    }
14635
14636    let edit_end = edits
14637        .last()
14638        .unwrap()
14639        .0
14640        .end
14641        .to_display_point(editor_snapshot);
14642    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14643        .to_offset(editor_snapshot, Bias::Right);
14644    text.extend(
14645        editor_snapshot
14646            .buffer_snapshot
14647            .chunks(offset..end_of_line, false)
14648            .map(|chunk| chunk.text),
14649    );
14650
14651    InlineCompletionText::Edit {
14652        text: text.into(),
14653        highlights,
14654    }
14655}
14656
14657pub fn highlight_diagnostic_message(
14658    diagnostic: &Diagnostic,
14659    mut max_message_rows: Option<u8>,
14660) -> (SharedString, Vec<Range<usize>>) {
14661    let mut text_without_backticks = String::new();
14662    let mut code_ranges = Vec::new();
14663
14664    if let Some(source) = &diagnostic.source {
14665        text_without_backticks.push_str(source);
14666        code_ranges.push(0..source.len());
14667        text_without_backticks.push_str(": ");
14668    }
14669
14670    let mut prev_offset = 0;
14671    let mut in_code_block = false;
14672    let has_row_limit = max_message_rows.is_some();
14673    let mut newline_indices = diagnostic
14674        .message
14675        .match_indices('\n')
14676        .filter(|_| has_row_limit)
14677        .map(|(ix, _)| ix)
14678        .fuse()
14679        .peekable();
14680
14681    for (quote_ix, _) in diagnostic
14682        .message
14683        .match_indices('`')
14684        .chain([(diagnostic.message.len(), "")])
14685    {
14686        let mut first_newline_ix = None;
14687        let mut last_newline_ix = None;
14688        while let Some(newline_ix) = newline_indices.peek() {
14689            if *newline_ix < quote_ix {
14690                if first_newline_ix.is_none() {
14691                    first_newline_ix = Some(*newline_ix);
14692                }
14693                last_newline_ix = Some(*newline_ix);
14694
14695                if let Some(rows_left) = &mut max_message_rows {
14696                    if *rows_left == 0 {
14697                        break;
14698                    } else {
14699                        *rows_left -= 1;
14700                    }
14701                }
14702                let _ = newline_indices.next();
14703            } else {
14704                break;
14705            }
14706        }
14707        let prev_len = text_without_backticks.len();
14708        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14709        text_without_backticks.push_str(new_text);
14710        if in_code_block {
14711            code_ranges.push(prev_len..text_without_backticks.len());
14712        }
14713        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14714        in_code_block = !in_code_block;
14715        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14716            text_without_backticks.push_str("...");
14717            break;
14718        }
14719    }
14720
14721    (text_without_backticks.into(), code_ranges)
14722}
14723
14724fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14725    match severity {
14726        DiagnosticSeverity::ERROR => colors.error,
14727        DiagnosticSeverity::WARNING => colors.warning,
14728        DiagnosticSeverity::INFORMATION => colors.info,
14729        DiagnosticSeverity::HINT => colors.info,
14730        _ => colors.ignored,
14731    }
14732}
14733
14734pub fn styled_runs_for_code_label<'a>(
14735    label: &'a CodeLabel,
14736    syntax_theme: &'a theme::SyntaxTheme,
14737) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14738    let fade_out = HighlightStyle {
14739        fade_out: Some(0.35),
14740        ..Default::default()
14741    };
14742
14743    let mut prev_end = label.filter_range.end;
14744    label
14745        .runs
14746        .iter()
14747        .enumerate()
14748        .flat_map(move |(ix, (range, highlight_id))| {
14749            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14750                style
14751            } else {
14752                return Default::default();
14753            };
14754            let mut muted_style = style;
14755            muted_style.highlight(fade_out);
14756
14757            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14758            if range.start >= label.filter_range.end {
14759                if range.start > prev_end {
14760                    runs.push((prev_end..range.start, fade_out));
14761                }
14762                runs.push((range.clone(), muted_style));
14763            } else if range.end <= label.filter_range.end {
14764                runs.push((range.clone(), style));
14765            } else {
14766                runs.push((range.start..label.filter_range.end, style));
14767                runs.push((label.filter_range.end..range.end, muted_style));
14768            }
14769            prev_end = cmp::max(prev_end, range.end);
14770
14771            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14772                runs.push((prev_end..label.text.len(), fade_out));
14773            }
14774
14775            runs
14776        })
14777}
14778
14779pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14780    let mut prev_index = 0;
14781    let mut prev_codepoint: Option<char> = None;
14782    text.char_indices()
14783        .chain([(text.len(), '\0')])
14784        .filter_map(move |(index, codepoint)| {
14785            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14786            let is_boundary = index == text.len()
14787                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14788                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14789            if is_boundary {
14790                let chunk = &text[prev_index..index];
14791                prev_index = index;
14792                Some(chunk)
14793            } else {
14794                None
14795            }
14796        })
14797}
14798
14799pub trait RangeToAnchorExt: Sized {
14800    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14801
14802    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14803        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14804        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14805    }
14806}
14807
14808impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14809    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14810        let start_offset = self.start.to_offset(snapshot);
14811        let end_offset = self.end.to_offset(snapshot);
14812        if start_offset == end_offset {
14813            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14814        } else {
14815            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14816        }
14817    }
14818}
14819
14820pub trait RowExt {
14821    fn as_f32(&self) -> f32;
14822
14823    fn next_row(&self) -> Self;
14824
14825    fn previous_row(&self) -> Self;
14826
14827    fn minus(&self, other: Self) -> u32;
14828}
14829
14830impl RowExt for DisplayRow {
14831    fn as_f32(&self) -> f32 {
14832        self.0 as f32
14833    }
14834
14835    fn next_row(&self) -> Self {
14836        Self(self.0 + 1)
14837    }
14838
14839    fn previous_row(&self) -> Self {
14840        Self(self.0.saturating_sub(1))
14841    }
14842
14843    fn minus(&self, other: Self) -> u32 {
14844        self.0 - other.0
14845    }
14846}
14847
14848impl RowExt for MultiBufferRow {
14849    fn as_f32(&self) -> f32 {
14850        self.0 as f32
14851    }
14852
14853    fn next_row(&self) -> Self {
14854        Self(self.0 + 1)
14855    }
14856
14857    fn previous_row(&self) -> Self {
14858        Self(self.0.saturating_sub(1))
14859    }
14860
14861    fn minus(&self, other: Self) -> u32 {
14862        self.0 - other.0
14863    }
14864}
14865
14866trait RowRangeExt {
14867    type Row;
14868
14869    fn len(&self) -> usize;
14870
14871    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14872}
14873
14874impl RowRangeExt for Range<MultiBufferRow> {
14875    type Row = MultiBufferRow;
14876
14877    fn len(&self) -> usize {
14878        (self.end.0 - self.start.0) as usize
14879    }
14880
14881    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14882        (self.start.0..self.end.0).map(MultiBufferRow)
14883    }
14884}
14885
14886impl RowRangeExt for Range<DisplayRow> {
14887    type Row = DisplayRow;
14888
14889    fn len(&self) -> usize {
14890        (self.end.0 - self.start.0) as usize
14891    }
14892
14893    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14894        (self.start.0..self.end.0).map(DisplayRow)
14895    }
14896}
14897
14898fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14899    if hunk.diff_base_byte_range.is_empty() {
14900        DiffHunkStatus::Added
14901    } else if hunk.row_range.is_empty() {
14902        DiffHunkStatus::Removed
14903    } else {
14904        DiffHunkStatus::Modified
14905    }
14906}
14907
14908/// If select range has more than one line, we
14909/// just point the cursor to range.start.
14910fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14911    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14912        range
14913    } else {
14914        range.start..range.start
14915    }
14916}
14917
14918pub struct KillRing(ClipboardItem);
14919impl Global for KillRing {}
14920
14921const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);