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            .map(|(range, new_text)| {
 4741                (
 4742                    multibuffer
 4743                        .anchor_in_excerpt(excerpt_id, range.start)
 4744                        .unwrap()
 4745                        ..multibuffer
 4746                            .anchor_in_excerpt(excerpt_id, range.end)
 4747                            .unwrap(),
 4748                    new_text,
 4749                )
 4750            })
 4751            .collect::<Vec<_>>();
 4752        if edits.is_empty() {
 4753            return None;
 4754        }
 4755
 4756        let first_edit_start = edits.first().unwrap().0.start;
 4757        let edit_start_row = first_edit_start
 4758            .to_point(&multibuffer)
 4759            .row
 4760            .saturating_sub(2);
 4761
 4762        let last_edit_end = edits.last().unwrap().0.end;
 4763        let edit_end_row = cmp::min(
 4764            multibuffer.max_point().row,
 4765            last_edit_end.to_point(&multibuffer).row + 2,
 4766        );
 4767
 4768        let cursor_row = cursor.to_point(&multibuffer).row;
 4769
 4770        let mut inlay_ids = Vec::new();
 4771        let invalidation_row_range;
 4772        let completion;
 4773        if cursor_row < edit_start_row {
 4774            invalidation_row_range = cursor_row..edit_end_row;
 4775            completion = InlineCompletion::Move(first_edit_start);
 4776        } else if cursor_row > edit_end_row {
 4777            invalidation_row_range = edit_start_row..cursor_row;
 4778            completion = InlineCompletion::Move(first_edit_start);
 4779        } else {
 4780            if !self.has_active_completions_menu() {
 4781                if edits
 4782                    .iter()
 4783                    .all(|(range, _)| range.to_offset(&multibuffer).is_empty())
 4784                {
 4785                    let mut inlays = Vec::new();
 4786                    for (range, new_text) in &edits {
 4787                        let inlay = Inlay::inline_completion(
 4788                            post_inc(&mut self.next_inlay_id),
 4789                            range.start,
 4790                            new_text.as_str(),
 4791                        );
 4792                        inlay_ids.push(inlay.id);
 4793                        inlays.push(inlay);
 4794                    }
 4795
 4796                    self.splice_inlays(vec![], inlays, cx);
 4797                } else {
 4798                    let background_color = cx.theme().status().deleted_background;
 4799                    self.highlight_text::<InlineCompletionHighlight>(
 4800                        edits.iter().map(|(range, _)| range.clone()).collect(),
 4801                        HighlightStyle {
 4802                            background_color: Some(background_color),
 4803                            ..Default::default()
 4804                        },
 4805                        cx,
 4806                    );
 4807                }
 4808            }
 4809
 4810            invalidation_row_range = edit_start_row..edit_end_row;
 4811            completion = InlineCompletion::Edit(edits);
 4812        };
 4813
 4814        let invalidation_range = multibuffer
 4815            .anchor_before(Point::new(invalidation_row_range.start, 0))
 4816            ..multibuffer.anchor_after(Point::new(
 4817                invalidation_row_range.end,
 4818                multibuffer.line_len(MultiBufferRow(invalidation_row_range.end)),
 4819            ));
 4820
 4821        self.active_inline_completion = Some(InlineCompletionState {
 4822            inlay_ids,
 4823            completion,
 4824            invalidation_range,
 4825        });
 4826
 4827        if self.has_active_completions_menu() {
 4828            if let Some(hint) = self.inline_completion_menu_hint(cx) {
 4829                match self.context_menu.borrow_mut().as_mut() {
 4830                    Some(CodeContextMenu::Completions(menu)) => {
 4831                        menu.show_inline_completion_hint(hint);
 4832                    }
 4833                    _ => {}
 4834                }
 4835            }
 4836        }
 4837
 4838        cx.notify();
 4839
 4840        Some(())
 4841    }
 4842
 4843    fn inline_completion_menu_hint(
 4844        &mut self,
 4845        cx: &mut ViewContext<Self>,
 4846    ) -> Option<InlineCompletionMenuHint> {
 4847        if self.has_active_inline_completion() {
 4848            let provider_name = self.inline_completion_provider()?.display_name();
 4849            let editor_snapshot = self.snapshot(cx);
 4850
 4851            let text = match &self.active_inline_completion.as_ref()?.completion {
 4852                InlineCompletion::Edit(edits) => {
 4853                    inline_completion_edit_text(&editor_snapshot, edits, cx)
 4854                }
 4855                InlineCompletion::Move(target) => {
 4856                    let target_point =
 4857                        target.to_point(&editor_snapshot.display_snapshot.buffer_snapshot);
 4858                    let target_line = target_point.row + 1;
 4859                    InlineCompletionText::Move(
 4860                        format!("Jump to edit in line {}", target_line).into(),
 4861                    )
 4862                }
 4863            };
 4864
 4865            Some(InlineCompletionMenuHint {
 4866                provider_name,
 4867                text,
 4868            })
 4869        } else {
 4870            None
 4871        }
 4872    }
 4873
 4874    fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
 4875        Some(self.inline_completion_provider.as_ref()?.provider.clone())
 4876    }
 4877
 4878    fn render_code_actions_indicator(
 4879        &self,
 4880        _style: &EditorStyle,
 4881        row: DisplayRow,
 4882        is_active: bool,
 4883        cx: &mut ViewContext<Self>,
 4884    ) -> Option<IconButton> {
 4885        if self.available_code_actions.is_some() {
 4886            Some(
 4887                IconButton::new("code_actions_indicator", ui::IconName::Bolt)
 4888                    .shape(ui::IconButtonShape::Square)
 4889                    .icon_size(IconSize::XSmall)
 4890                    .icon_color(Color::Muted)
 4891                    .toggle_state(is_active)
 4892                    .tooltip({
 4893                        let focus_handle = self.focus_handle.clone();
 4894                        move |cx| {
 4895                            Tooltip::for_action_in(
 4896                                "Toggle Code Actions",
 4897                                &ToggleCodeActions {
 4898                                    deployed_from_indicator: None,
 4899                                },
 4900                                &focus_handle,
 4901                                cx,
 4902                            )
 4903                        }
 4904                    })
 4905                    .on_click(cx.listener(move |editor, _e, cx| {
 4906                        editor.focus(cx);
 4907                        editor.toggle_code_actions(
 4908                            &ToggleCodeActions {
 4909                                deployed_from_indicator: Some(row),
 4910                            },
 4911                            cx,
 4912                        );
 4913                    })),
 4914            )
 4915        } else {
 4916            None
 4917        }
 4918    }
 4919
 4920    fn clear_tasks(&mut self) {
 4921        self.tasks.clear()
 4922    }
 4923
 4924    fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
 4925        if self.tasks.insert(key, value).is_some() {
 4926            // This case should hopefully be rare, but just in case...
 4927            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
 4928        }
 4929    }
 4930
 4931    fn build_tasks_context(
 4932        project: &Model<Project>,
 4933        buffer: &Model<Buffer>,
 4934        buffer_row: u32,
 4935        tasks: &Arc<RunnableTasks>,
 4936        cx: &mut ViewContext<Self>,
 4937    ) -> Task<Option<task::TaskContext>> {
 4938        let position = Point::new(buffer_row, tasks.column);
 4939        let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
 4940        let location = Location {
 4941            buffer: buffer.clone(),
 4942            range: range_start..range_start,
 4943        };
 4944        // Fill in the environmental variables from the tree-sitter captures
 4945        let mut captured_task_variables = TaskVariables::default();
 4946        for (capture_name, value) in tasks.extra_variables.clone() {
 4947            captured_task_variables.insert(
 4948                task::VariableName::Custom(capture_name.into()),
 4949                value.clone(),
 4950            );
 4951        }
 4952        project.update(cx, |project, cx| {
 4953            project.task_store().update(cx, |task_store, cx| {
 4954                task_store.task_context_for_location(captured_task_variables, location, cx)
 4955            })
 4956        })
 4957    }
 4958
 4959    pub fn spawn_nearest_task(&mut self, action: &SpawnNearestTask, cx: &mut ViewContext<Self>) {
 4960        let Some((workspace, _)) = self.workspace.clone() else {
 4961            return;
 4962        };
 4963        let Some(project) = self.project.clone() else {
 4964            return;
 4965        };
 4966
 4967        // Try to find a closest, enclosing node using tree-sitter that has a
 4968        // task
 4969        let Some((buffer, buffer_row, tasks)) = self
 4970            .find_enclosing_node_task(cx)
 4971            // Or find the task that's closest in row-distance.
 4972            .or_else(|| self.find_closest_task(cx))
 4973        else {
 4974            return;
 4975        };
 4976
 4977        let reveal_strategy = action.reveal;
 4978        let task_context = Self::build_tasks_context(&project, &buffer, buffer_row, &tasks, cx);
 4979        cx.spawn(|_, mut cx| async move {
 4980            let context = task_context.await?;
 4981            let (task_source_kind, mut resolved_task) = tasks.resolve(&context).next()?;
 4982
 4983            let resolved = resolved_task.resolved.as_mut()?;
 4984            resolved.reveal = reveal_strategy;
 4985
 4986            workspace
 4987                .update(&mut cx, |workspace, cx| {
 4988                    workspace::tasks::schedule_resolved_task(
 4989                        workspace,
 4990                        task_source_kind,
 4991                        resolved_task,
 4992                        false,
 4993                        cx,
 4994                    );
 4995                })
 4996                .ok()
 4997        })
 4998        .detach();
 4999    }
 5000
 5001    fn find_closest_task(
 5002        &mut self,
 5003        cx: &mut ViewContext<Self>,
 5004    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5005        let cursor_row = self.selections.newest_adjusted(cx).head().row;
 5006
 5007        let ((buffer_id, row), tasks) = self
 5008            .tasks
 5009            .iter()
 5010            .min_by_key(|((_, row), _)| cursor_row.abs_diff(*row))?;
 5011
 5012        let buffer = self.buffer.read(cx).buffer(*buffer_id)?;
 5013        let tasks = Arc::new(tasks.to_owned());
 5014        Some((buffer, *row, tasks))
 5015    }
 5016
 5017    fn find_enclosing_node_task(
 5018        &mut self,
 5019        cx: &mut ViewContext<Self>,
 5020    ) -> Option<(Model<Buffer>, u32, Arc<RunnableTasks>)> {
 5021        let snapshot = self.buffer.read(cx).snapshot(cx);
 5022        let offset = self.selections.newest::<usize>(cx).head();
 5023        let excerpt = snapshot.excerpt_containing(offset..offset)?;
 5024        let buffer_id = excerpt.buffer().remote_id();
 5025
 5026        let layer = excerpt.buffer().syntax_layer_at(offset)?;
 5027        let mut cursor = layer.node().walk();
 5028
 5029        while cursor.goto_first_child_for_byte(offset).is_some() {
 5030            if cursor.node().end_byte() == offset {
 5031                cursor.goto_next_sibling();
 5032            }
 5033        }
 5034
 5035        // Ascend to the smallest ancestor that contains the range and has a task.
 5036        loop {
 5037            let node = cursor.node();
 5038            let node_range = node.byte_range();
 5039            let symbol_start_row = excerpt.buffer().offset_to_point(node.start_byte()).row;
 5040
 5041            // Check if this node contains our offset
 5042            if node_range.start <= offset && node_range.end >= offset {
 5043                // If it contains offset, check for task
 5044                if let Some(tasks) = self.tasks.get(&(buffer_id, symbol_start_row)) {
 5045                    let buffer = self.buffer.read(cx).buffer(buffer_id)?;
 5046                    return Some((buffer, symbol_start_row, Arc::new(tasks.to_owned())));
 5047                }
 5048            }
 5049
 5050            if !cursor.goto_parent() {
 5051                break;
 5052            }
 5053        }
 5054        None
 5055    }
 5056
 5057    fn render_run_indicator(
 5058        &self,
 5059        _style: &EditorStyle,
 5060        is_active: bool,
 5061        row: DisplayRow,
 5062        cx: &mut ViewContext<Self>,
 5063    ) -> IconButton {
 5064        IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
 5065            .shape(ui::IconButtonShape::Square)
 5066            .icon_size(IconSize::XSmall)
 5067            .icon_color(Color::Muted)
 5068            .toggle_state(is_active)
 5069            .on_click(cx.listener(move |editor, _e, cx| {
 5070                editor.focus(cx);
 5071                editor.toggle_code_actions(
 5072                    &ToggleCodeActions {
 5073                        deployed_from_indicator: Some(row),
 5074                    },
 5075                    cx,
 5076                );
 5077            }))
 5078    }
 5079
 5080    #[cfg(feature = "test-support")]
 5081    pub fn context_menu_visible(&self) -> bool {
 5082        self.context_menu
 5083            .borrow()
 5084            .as_ref()
 5085            .map_or(false, |menu| menu.visible())
 5086    }
 5087
 5088    #[cfg(feature = "test-support")]
 5089    pub fn context_menu_contains_inline_completion(&self) -> bool {
 5090        self.context_menu
 5091            .borrow()
 5092            .as_ref()
 5093            .map_or(false, |menu| match menu {
 5094                CodeContextMenu::Completions(menu) => menu.entries.first().map_or(false, |entry| {
 5095                    matches!(entry, CompletionEntry::InlineCompletionHint(_))
 5096                }),
 5097                CodeContextMenu::CodeActions(_) => false,
 5098            })
 5099    }
 5100
 5101    fn context_menu_origin(&self, cursor_position: DisplayPoint) -> Option<ContextMenuOrigin> {
 5102        self.context_menu
 5103            .borrow()
 5104            .as_ref()
 5105            .map(|menu| menu.origin(cursor_position))
 5106    }
 5107
 5108    fn render_context_menu(
 5109        &self,
 5110        style: &EditorStyle,
 5111        max_height_in_lines: u32,
 5112        cx: &mut ViewContext<Editor>,
 5113    ) -> Option<AnyElement> {
 5114        self.context_menu.borrow().as_ref().and_then(|menu| {
 5115            if menu.visible() {
 5116                Some(menu.render(style, max_height_in_lines, cx))
 5117            } else {
 5118                None
 5119            }
 5120        })
 5121    }
 5122
 5123    fn render_context_menu_aside(
 5124        &self,
 5125        style: &EditorStyle,
 5126        max_height: Pixels,
 5127        cx: &mut ViewContext<Editor>,
 5128    ) -> Option<AnyElement> {
 5129        self.context_menu.borrow().as_ref().and_then(|menu| {
 5130            if menu.visible() {
 5131                menu.render_aside(
 5132                    style,
 5133                    max_height,
 5134                    self.workspace.as_ref().map(|(w, _)| w.clone()),
 5135                    cx,
 5136                )
 5137            } else {
 5138                None
 5139            }
 5140        })
 5141    }
 5142
 5143    fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<CodeContextMenu> {
 5144        cx.notify();
 5145        self.completion_tasks.clear();
 5146        self.context_menu.borrow_mut().take()
 5147    }
 5148
 5149    fn show_snippet_choices(
 5150        &mut self,
 5151        choices: &Vec<String>,
 5152        selection: Range<Anchor>,
 5153        cx: &mut ViewContext<Self>,
 5154    ) {
 5155        if selection.start.buffer_id.is_none() {
 5156            return;
 5157        }
 5158        let buffer_id = selection.start.buffer_id.unwrap();
 5159        let buffer = self.buffer().read(cx).buffer(buffer_id);
 5160        let id = post_inc(&mut self.next_completion_id);
 5161
 5162        if let Some(buffer) = buffer {
 5163            *self.context_menu.borrow_mut() = Some(CodeContextMenu::Completions(
 5164                CompletionsMenu::new_snippet_choices(id, true, choices, selection, buffer),
 5165            ));
 5166        }
 5167    }
 5168
 5169    pub fn insert_snippet(
 5170        &mut self,
 5171        insertion_ranges: &[Range<usize>],
 5172        snippet: Snippet,
 5173        cx: &mut ViewContext<Self>,
 5174    ) -> Result<()> {
 5175        struct Tabstop<T> {
 5176            is_end_tabstop: bool,
 5177            ranges: Vec<Range<T>>,
 5178            choices: Option<Vec<String>>,
 5179        }
 5180
 5181        let tabstops = self.buffer.update(cx, |buffer, cx| {
 5182            let snippet_text: Arc<str> = snippet.text.clone().into();
 5183            buffer.edit(
 5184                insertion_ranges
 5185                    .iter()
 5186                    .cloned()
 5187                    .map(|range| (range, snippet_text.clone())),
 5188                Some(AutoindentMode::EachLine),
 5189                cx,
 5190            );
 5191
 5192            let snapshot = &*buffer.read(cx);
 5193            let snippet = &snippet;
 5194            snippet
 5195                .tabstops
 5196                .iter()
 5197                .map(|tabstop| {
 5198                    let is_end_tabstop = tabstop.ranges.first().map_or(false, |tabstop| {
 5199                        tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
 5200                    });
 5201                    let mut tabstop_ranges = tabstop
 5202                        .ranges
 5203                        .iter()
 5204                        .flat_map(|tabstop_range| {
 5205                            let mut delta = 0_isize;
 5206                            insertion_ranges.iter().map(move |insertion_range| {
 5207                                let insertion_start = insertion_range.start as isize + delta;
 5208                                delta +=
 5209                                    snippet.text.len() as isize - insertion_range.len() as isize;
 5210
 5211                                let start = ((insertion_start + tabstop_range.start) as usize)
 5212                                    .min(snapshot.len());
 5213                                let end = ((insertion_start + tabstop_range.end) as usize)
 5214                                    .min(snapshot.len());
 5215                                snapshot.anchor_before(start)..snapshot.anchor_after(end)
 5216                            })
 5217                        })
 5218                        .collect::<Vec<_>>();
 5219                    tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
 5220
 5221                    Tabstop {
 5222                        is_end_tabstop,
 5223                        ranges: tabstop_ranges,
 5224                        choices: tabstop.choices.clone(),
 5225                    }
 5226                })
 5227                .collect::<Vec<_>>()
 5228        });
 5229        if let Some(tabstop) = tabstops.first() {
 5230            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5231                s.select_ranges(tabstop.ranges.iter().cloned());
 5232            });
 5233
 5234            if let Some(choices) = &tabstop.choices {
 5235                if let Some(selection) = tabstop.ranges.first() {
 5236                    self.show_snippet_choices(choices, selection.clone(), cx)
 5237                }
 5238            }
 5239
 5240            // If we're already at the last tabstop and it's at the end of the snippet,
 5241            // we're done, we don't need to keep the state around.
 5242            if !tabstop.is_end_tabstop {
 5243                let choices = tabstops
 5244                    .iter()
 5245                    .map(|tabstop| tabstop.choices.clone())
 5246                    .collect();
 5247
 5248                let ranges = tabstops
 5249                    .into_iter()
 5250                    .map(|tabstop| tabstop.ranges)
 5251                    .collect::<Vec<_>>();
 5252
 5253                self.snippet_stack.push(SnippetState {
 5254                    active_index: 0,
 5255                    ranges,
 5256                    choices,
 5257                });
 5258            }
 5259
 5260            // Check whether the just-entered snippet ends with an auto-closable bracket.
 5261            if self.autoclose_regions.is_empty() {
 5262                let snapshot = self.buffer.read(cx).snapshot(cx);
 5263                for selection in &mut self.selections.all::<Point>(cx) {
 5264                    let selection_head = selection.head();
 5265                    let Some(scope) = snapshot.language_scope_at(selection_head) else {
 5266                        continue;
 5267                    };
 5268
 5269                    let mut bracket_pair = None;
 5270                    let next_chars = snapshot.chars_at(selection_head).collect::<String>();
 5271                    let prev_chars = snapshot
 5272                        .reversed_chars_at(selection_head)
 5273                        .collect::<String>();
 5274                    for (pair, enabled) in scope.brackets() {
 5275                        if enabled
 5276                            && pair.close
 5277                            && prev_chars.starts_with(pair.start.as_str())
 5278                            && next_chars.starts_with(pair.end.as_str())
 5279                        {
 5280                            bracket_pair = Some(pair.clone());
 5281                            break;
 5282                        }
 5283                    }
 5284                    if let Some(pair) = bracket_pair {
 5285                        let start = snapshot.anchor_after(selection_head);
 5286                        let end = snapshot.anchor_after(selection_head);
 5287                        self.autoclose_regions.push(AutocloseRegion {
 5288                            selection_id: selection.id,
 5289                            range: start..end,
 5290                            pair,
 5291                        });
 5292                    }
 5293                }
 5294            }
 5295        }
 5296        Ok(())
 5297    }
 5298
 5299    pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5300        self.move_to_snippet_tabstop(Bias::Right, cx)
 5301    }
 5302
 5303    pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
 5304        self.move_to_snippet_tabstop(Bias::Left, cx)
 5305    }
 5306
 5307    pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
 5308        if let Some(mut snippet) = self.snippet_stack.pop() {
 5309            match bias {
 5310                Bias::Left => {
 5311                    if snippet.active_index > 0 {
 5312                        snippet.active_index -= 1;
 5313                    } else {
 5314                        self.snippet_stack.push(snippet);
 5315                        return false;
 5316                    }
 5317                }
 5318                Bias::Right => {
 5319                    if snippet.active_index + 1 < snippet.ranges.len() {
 5320                        snippet.active_index += 1;
 5321                    } else {
 5322                        self.snippet_stack.push(snippet);
 5323                        return false;
 5324                    }
 5325                }
 5326            }
 5327            if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
 5328                self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5329                    s.select_anchor_ranges(current_ranges.iter().cloned())
 5330                });
 5331
 5332                if let Some(choices) = &snippet.choices[snippet.active_index] {
 5333                    if let Some(selection) = current_ranges.first() {
 5334                        self.show_snippet_choices(&choices, selection.clone(), cx);
 5335                    }
 5336                }
 5337
 5338                // If snippet state is not at the last tabstop, push it back on the stack
 5339                if snippet.active_index + 1 < snippet.ranges.len() {
 5340                    self.snippet_stack.push(snippet);
 5341                }
 5342                return true;
 5343            }
 5344        }
 5345
 5346        false
 5347    }
 5348
 5349    pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
 5350        self.transact(cx, |this, cx| {
 5351            this.select_all(&SelectAll, cx);
 5352            this.insert("", cx);
 5353        });
 5354    }
 5355
 5356    pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
 5357        self.transact(cx, |this, cx| {
 5358            this.select_autoclose_pair(cx);
 5359            let mut linked_ranges = HashMap::<_, Vec<_>>::default();
 5360            if !this.linked_edit_ranges.is_empty() {
 5361                let selections = this.selections.all::<MultiBufferPoint>(cx);
 5362                let snapshot = this.buffer.read(cx).snapshot(cx);
 5363
 5364                for selection in selections.iter() {
 5365                    let selection_start = snapshot.anchor_before(selection.start).text_anchor;
 5366                    let selection_end = snapshot.anchor_after(selection.end).text_anchor;
 5367                    if selection_start.buffer_id != selection_end.buffer_id {
 5368                        continue;
 5369                    }
 5370                    if let Some(ranges) =
 5371                        this.linked_editing_ranges_for(selection_start..selection_end, cx)
 5372                    {
 5373                        for (buffer, entries) in ranges {
 5374                            linked_ranges.entry(buffer).or_default().extend(entries);
 5375                        }
 5376                    }
 5377                }
 5378            }
 5379
 5380            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 5381            if !this.selections.line_mode {
 5382                let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
 5383                for selection in &mut selections {
 5384                    if selection.is_empty() {
 5385                        let old_head = selection.head();
 5386                        let mut new_head =
 5387                            movement::left(&display_map, old_head.to_display_point(&display_map))
 5388                                .to_point(&display_map);
 5389                        if let Some((buffer, line_buffer_range)) = display_map
 5390                            .buffer_snapshot
 5391                            .buffer_line_for_row(MultiBufferRow(old_head.row))
 5392                        {
 5393                            let indent_size =
 5394                                buffer.indent_size_for_line(line_buffer_range.start.row);
 5395                            let indent_len = match indent_size.kind {
 5396                                IndentKind::Space => {
 5397                                    buffer.settings_at(line_buffer_range.start, cx).tab_size
 5398                                }
 5399                                IndentKind::Tab => NonZeroU32::new(1).unwrap(),
 5400                            };
 5401                            if old_head.column <= indent_size.len && old_head.column > 0 {
 5402                                let indent_len = indent_len.get();
 5403                                new_head = cmp::min(
 5404                                    new_head,
 5405                                    MultiBufferPoint::new(
 5406                                        old_head.row,
 5407                                        ((old_head.column - 1) / indent_len) * indent_len,
 5408                                    ),
 5409                                );
 5410                            }
 5411                        }
 5412
 5413                        selection.set_head(new_head, SelectionGoal::None);
 5414                    }
 5415                }
 5416            }
 5417
 5418            this.signature_help_state.set_backspace_pressed(true);
 5419            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5420            this.insert("", cx);
 5421            let empty_str: Arc<str> = Arc::from("");
 5422            for (buffer, edits) in linked_ranges {
 5423                let snapshot = buffer.read(cx).snapshot();
 5424                use text::ToPoint as TP;
 5425
 5426                let edits = edits
 5427                    .into_iter()
 5428                    .map(|range| {
 5429                        let end_point = TP::to_point(&range.end, &snapshot);
 5430                        let mut start_point = TP::to_point(&range.start, &snapshot);
 5431
 5432                        if end_point == start_point {
 5433                            let offset = text::ToOffset::to_offset(&range.start, &snapshot)
 5434                                .saturating_sub(1);
 5435                            start_point =
 5436                                snapshot.clip_point(TP::to_point(&offset, &snapshot), Bias::Left);
 5437                        };
 5438
 5439                        (start_point..end_point, empty_str.clone())
 5440                    })
 5441                    .sorted_by_key(|(range, _)| range.start)
 5442                    .collect::<Vec<_>>();
 5443                buffer.update(cx, |this, cx| {
 5444                    this.edit(edits, None, cx);
 5445                })
 5446            }
 5447            this.refresh_inline_completion(true, false, cx);
 5448            linked_editing_ranges::refresh_linked_ranges(this, cx);
 5449        });
 5450    }
 5451
 5452    pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
 5453        self.transact(cx, |this, cx| {
 5454            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5455                let line_mode = s.line_mode;
 5456                s.move_with(|map, selection| {
 5457                    if selection.is_empty() && !line_mode {
 5458                        let cursor = movement::right(map, selection.head());
 5459                        selection.end = cursor;
 5460                        selection.reversed = true;
 5461                        selection.goal = SelectionGoal::None;
 5462                    }
 5463                })
 5464            });
 5465            this.insert("", cx);
 5466            this.refresh_inline_completion(true, false, cx);
 5467        });
 5468    }
 5469
 5470    pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
 5471        if self.move_to_prev_snippet_tabstop(cx) {
 5472            return;
 5473        }
 5474
 5475        self.outdent(&Outdent, cx);
 5476    }
 5477
 5478    pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
 5479        if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
 5480            return;
 5481        }
 5482
 5483        let mut selections = self.selections.all_adjusted(cx);
 5484        let buffer = self.buffer.read(cx);
 5485        let snapshot = buffer.snapshot(cx);
 5486        let rows_iter = selections.iter().map(|s| s.head().row);
 5487        let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
 5488
 5489        let mut edits = Vec::new();
 5490        let mut prev_edited_row = 0;
 5491        let mut row_delta = 0;
 5492        for selection in &mut selections {
 5493            if selection.start.row != prev_edited_row {
 5494                row_delta = 0;
 5495            }
 5496            prev_edited_row = selection.end.row;
 5497
 5498            // If the selection is non-empty, then increase the indentation of the selected lines.
 5499            if !selection.is_empty() {
 5500                row_delta =
 5501                    Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5502                continue;
 5503            }
 5504
 5505            // If the selection is empty and the cursor is in the leading whitespace before the
 5506            // suggested indentation, then auto-indent the line.
 5507            let cursor = selection.head();
 5508            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
 5509            if let Some(suggested_indent) =
 5510                suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
 5511            {
 5512                if cursor.column < suggested_indent.len
 5513                    && cursor.column <= current_indent.len
 5514                    && current_indent.len <= suggested_indent.len
 5515                {
 5516                    selection.start = Point::new(cursor.row, suggested_indent.len);
 5517                    selection.end = selection.start;
 5518                    if row_delta == 0 {
 5519                        edits.extend(Buffer::edit_for_indent_size_adjustment(
 5520                            cursor.row,
 5521                            current_indent,
 5522                            suggested_indent,
 5523                        ));
 5524                        row_delta = suggested_indent.len - current_indent.len;
 5525                    }
 5526                    continue;
 5527                }
 5528            }
 5529
 5530            // Otherwise, insert a hard or soft tab.
 5531            let settings = buffer.settings_at(cursor, cx);
 5532            let tab_size = if settings.hard_tabs {
 5533                IndentSize::tab()
 5534            } else {
 5535                let tab_size = settings.tab_size.get();
 5536                let char_column = snapshot
 5537                    .text_for_range(Point::new(cursor.row, 0)..cursor)
 5538                    .flat_map(str::chars)
 5539                    .count()
 5540                    + row_delta as usize;
 5541                let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
 5542                IndentSize::spaces(chars_to_next_tab_stop)
 5543            };
 5544            selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
 5545            selection.end = selection.start;
 5546            edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
 5547            row_delta += tab_size.len;
 5548        }
 5549
 5550        self.transact(cx, |this, cx| {
 5551            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5552            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5553            this.refresh_inline_completion(true, false, cx);
 5554        });
 5555    }
 5556
 5557    pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
 5558        if self.read_only(cx) {
 5559            return;
 5560        }
 5561        let mut selections = self.selections.all::<Point>(cx);
 5562        let mut prev_edited_row = 0;
 5563        let mut row_delta = 0;
 5564        let mut edits = Vec::new();
 5565        let buffer = self.buffer.read(cx);
 5566        let snapshot = buffer.snapshot(cx);
 5567        for selection in &mut selections {
 5568            if selection.start.row != prev_edited_row {
 5569                row_delta = 0;
 5570            }
 5571            prev_edited_row = selection.end.row;
 5572
 5573            row_delta =
 5574                Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
 5575        }
 5576
 5577        self.transact(cx, |this, cx| {
 5578            this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
 5579            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5580        });
 5581    }
 5582
 5583    fn indent_selection(
 5584        buffer: &MultiBuffer,
 5585        snapshot: &MultiBufferSnapshot,
 5586        selection: &mut Selection<Point>,
 5587        edits: &mut Vec<(Range<Point>, String)>,
 5588        delta_for_start_row: u32,
 5589        cx: &AppContext,
 5590    ) -> u32 {
 5591        let settings = buffer.settings_at(selection.start, cx);
 5592        let tab_size = settings.tab_size.get();
 5593        let indent_kind = if settings.hard_tabs {
 5594            IndentKind::Tab
 5595        } else {
 5596            IndentKind::Space
 5597        };
 5598        let mut start_row = selection.start.row;
 5599        let mut end_row = selection.end.row + 1;
 5600
 5601        // If a selection ends at the beginning of a line, don't indent
 5602        // that last line.
 5603        if selection.end.column == 0 && selection.end.row > selection.start.row {
 5604            end_row -= 1;
 5605        }
 5606
 5607        // Avoid re-indenting a row that has already been indented by a
 5608        // previous selection, but still update this selection's column
 5609        // to reflect that indentation.
 5610        if delta_for_start_row > 0 {
 5611            start_row += 1;
 5612            selection.start.column += delta_for_start_row;
 5613            if selection.end.row == selection.start.row {
 5614                selection.end.column += delta_for_start_row;
 5615            }
 5616        }
 5617
 5618        let mut delta_for_end_row = 0;
 5619        let has_multiple_rows = start_row + 1 != end_row;
 5620        for row in start_row..end_row {
 5621            let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 5622            let indent_delta = match (current_indent.kind, indent_kind) {
 5623                (IndentKind::Space, IndentKind::Space) => {
 5624                    let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
 5625                    IndentSize::spaces(columns_to_next_tab_stop)
 5626                }
 5627                (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
 5628                (_, IndentKind::Tab) => IndentSize::tab(),
 5629            };
 5630
 5631            let start = if has_multiple_rows || current_indent.len < selection.start.column {
 5632                0
 5633            } else {
 5634                selection.start.column
 5635            };
 5636            let row_start = Point::new(row, start);
 5637            edits.push((
 5638                row_start..row_start,
 5639                indent_delta.chars().collect::<String>(),
 5640            ));
 5641
 5642            // Update this selection's endpoints to reflect the indentation.
 5643            if row == selection.start.row {
 5644                selection.start.column += indent_delta.len;
 5645            }
 5646            if row == selection.end.row {
 5647                selection.end.column += indent_delta.len;
 5648                delta_for_end_row = indent_delta.len;
 5649            }
 5650        }
 5651
 5652        if selection.start.row == selection.end.row {
 5653            delta_for_start_row + delta_for_end_row
 5654        } else {
 5655            delta_for_end_row
 5656        }
 5657    }
 5658
 5659    pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
 5660        if self.read_only(cx) {
 5661            return;
 5662        }
 5663        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5664        let selections = self.selections.all::<Point>(cx);
 5665        let mut deletion_ranges = Vec::new();
 5666        let mut last_outdent = None;
 5667        {
 5668            let buffer = self.buffer.read(cx);
 5669            let snapshot = buffer.snapshot(cx);
 5670            for selection in &selections {
 5671                let settings = buffer.settings_at(selection.start, cx);
 5672                let tab_size = settings.tab_size.get();
 5673                let mut rows = selection.spanned_rows(false, &display_map);
 5674
 5675                // Avoid re-outdenting a row that has already been outdented by a
 5676                // previous selection.
 5677                if let Some(last_row) = last_outdent {
 5678                    if last_row == rows.start {
 5679                        rows.start = rows.start.next_row();
 5680                    }
 5681                }
 5682                let has_multiple_rows = rows.len() > 1;
 5683                for row in rows.iter_rows() {
 5684                    let indent_size = snapshot.indent_size_for_line(row);
 5685                    if indent_size.len > 0 {
 5686                        let deletion_len = match indent_size.kind {
 5687                            IndentKind::Space => {
 5688                                let columns_to_prev_tab_stop = indent_size.len % tab_size;
 5689                                if columns_to_prev_tab_stop == 0 {
 5690                                    tab_size
 5691                                } else {
 5692                                    columns_to_prev_tab_stop
 5693                                }
 5694                            }
 5695                            IndentKind::Tab => 1,
 5696                        };
 5697                        let start = if has_multiple_rows
 5698                            || deletion_len > selection.start.column
 5699                            || indent_size.len < selection.start.column
 5700                        {
 5701                            0
 5702                        } else {
 5703                            selection.start.column - deletion_len
 5704                        };
 5705                        deletion_ranges.push(
 5706                            Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
 5707                        );
 5708                        last_outdent = Some(row);
 5709                    }
 5710                }
 5711            }
 5712        }
 5713
 5714        self.transact(cx, |this, cx| {
 5715            this.buffer.update(cx, |buffer, cx| {
 5716                let empty_str: Arc<str> = Arc::default();
 5717                buffer.edit(
 5718                    deletion_ranges
 5719                        .into_iter()
 5720                        .map(|range| (range, empty_str.clone())),
 5721                    None,
 5722                    cx,
 5723                );
 5724            });
 5725            let selections = this.selections.all::<usize>(cx);
 5726            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5727        });
 5728    }
 5729
 5730    pub fn autoindent(&mut self, _: &AutoIndent, cx: &mut ViewContext<Self>) {
 5731        if self.read_only(cx) {
 5732            return;
 5733        }
 5734        let selections = self
 5735            .selections
 5736            .all::<usize>(cx)
 5737            .into_iter()
 5738            .map(|s| s.range());
 5739
 5740        self.transact(cx, |this, cx| {
 5741            this.buffer.update(cx, |buffer, cx| {
 5742                buffer.autoindent_ranges(selections, cx);
 5743            });
 5744            let selections = this.selections.all::<usize>(cx);
 5745            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 5746        });
 5747    }
 5748
 5749    pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
 5750        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 5751        let selections = self.selections.all::<Point>(cx);
 5752
 5753        let mut new_cursors = Vec::new();
 5754        let mut edit_ranges = Vec::new();
 5755        let mut selections = selections.iter().peekable();
 5756        while let Some(selection) = selections.next() {
 5757            let mut rows = selection.spanned_rows(false, &display_map);
 5758            let goal_display_column = selection.head().to_display_point(&display_map).column();
 5759
 5760            // Accumulate contiguous regions of rows that we want to delete.
 5761            while let Some(next_selection) = selections.peek() {
 5762                let next_rows = next_selection.spanned_rows(false, &display_map);
 5763                if next_rows.start <= rows.end {
 5764                    rows.end = next_rows.end;
 5765                    selections.next().unwrap();
 5766                } else {
 5767                    break;
 5768                }
 5769            }
 5770
 5771            let buffer = &display_map.buffer_snapshot;
 5772            let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
 5773            let edit_end;
 5774            let cursor_buffer_row;
 5775            if buffer.max_point().row >= rows.end.0 {
 5776                // If there's a line after the range, delete the \n from the end of the row range
 5777                // and position the cursor on the next line.
 5778                edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
 5779                cursor_buffer_row = rows.end;
 5780            } else {
 5781                // If there isn't a line after the range, delete the \n from the line before the
 5782                // start of the row range and position the cursor there.
 5783                edit_start = edit_start.saturating_sub(1);
 5784                edit_end = buffer.len();
 5785                cursor_buffer_row = rows.start.previous_row();
 5786            }
 5787
 5788            let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
 5789            *cursor.column_mut() =
 5790                cmp::min(goal_display_column, display_map.line_len(cursor.row()));
 5791
 5792            new_cursors.push((
 5793                selection.id,
 5794                buffer.anchor_after(cursor.to_point(&display_map)),
 5795            ));
 5796            edit_ranges.push(edit_start..edit_end);
 5797        }
 5798
 5799        self.transact(cx, |this, cx| {
 5800            let buffer = this.buffer.update(cx, |buffer, cx| {
 5801                let empty_str: Arc<str> = Arc::default();
 5802                buffer.edit(
 5803                    edit_ranges
 5804                        .into_iter()
 5805                        .map(|range| (range, empty_str.clone())),
 5806                    None,
 5807                    cx,
 5808                );
 5809                buffer.snapshot(cx)
 5810            });
 5811            let new_selections = new_cursors
 5812                .into_iter()
 5813                .map(|(id, cursor)| {
 5814                    let cursor = cursor.to_point(&buffer);
 5815                    Selection {
 5816                        id,
 5817                        start: cursor,
 5818                        end: cursor,
 5819                        reversed: false,
 5820                        goal: SelectionGoal::None,
 5821                    }
 5822                })
 5823                .collect();
 5824
 5825            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5826                s.select(new_selections);
 5827            });
 5828        });
 5829    }
 5830
 5831    pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
 5832        if self.read_only(cx) {
 5833            return;
 5834        }
 5835        let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
 5836        for selection in self.selections.all::<Point>(cx) {
 5837            let start = MultiBufferRow(selection.start.row);
 5838            // Treat single line selections as if they include the next line. Otherwise this action
 5839            // would do nothing for single line selections individual cursors.
 5840            let end = if selection.start.row == selection.end.row {
 5841                MultiBufferRow(selection.start.row + 1)
 5842            } else {
 5843                MultiBufferRow(selection.end.row)
 5844            };
 5845
 5846            if let Some(last_row_range) = row_ranges.last_mut() {
 5847                if start <= last_row_range.end {
 5848                    last_row_range.end = end;
 5849                    continue;
 5850                }
 5851            }
 5852            row_ranges.push(start..end);
 5853        }
 5854
 5855        let snapshot = self.buffer.read(cx).snapshot(cx);
 5856        let mut cursor_positions = Vec::new();
 5857        for row_range in &row_ranges {
 5858            let anchor = snapshot.anchor_before(Point::new(
 5859                row_range.end.previous_row().0,
 5860                snapshot.line_len(row_range.end.previous_row()),
 5861            ));
 5862            cursor_positions.push(anchor..anchor);
 5863        }
 5864
 5865        self.transact(cx, |this, cx| {
 5866            for row_range in row_ranges.into_iter().rev() {
 5867                for row in row_range.iter_rows().rev() {
 5868                    let end_of_line = Point::new(row.0, snapshot.line_len(row));
 5869                    let next_line_row = row.next_row();
 5870                    let indent = snapshot.indent_size_for_line(next_line_row);
 5871                    let start_of_next_line = Point::new(next_line_row.0, indent.len);
 5872
 5873                    let replace = if snapshot.line_len(next_line_row) > indent.len {
 5874                        " "
 5875                    } else {
 5876                        ""
 5877                    };
 5878
 5879                    this.buffer.update(cx, |buffer, cx| {
 5880                        buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
 5881                    });
 5882                }
 5883            }
 5884
 5885            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 5886                s.select_anchor_ranges(cursor_positions)
 5887            });
 5888        });
 5889    }
 5890
 5891    pub fn sort_lines_case_sensitive(
 5892        &mut self,
 5893        _: &SortLinesCaseSensitive,
 5894        cx: &mut ViewContext<Self>,
 5895    ) {
 5896        self.manipulate_lines(cx, |lines| lines.sort())
 5897    }
 5898
 5899    pub fn sort_lines_case_insensitive(
 5900        &mut self,
 5901        _: &SortLinesCaseInsensitive,
 5902        cx: &mut ViewContext<Self>,
 5903    ) {
 5904        self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
 5905    }
 5906
 5907    pub fn unique_lines_case_insensitive(
 5908        &mut self,
 5909        _: &UniqueLinesCaseInsensitive,
 5910        cx: &mut ViewContext<Self>,
 5911    ) {
 5912        self.manipulate_lines(cx, |lines| {
 5913            let mut seen = HashSet::default();
 5914            lines.retain(|line| seen.insert(line.to_lowercase()));
 5915        })
 5916    }
 5917
 5918    pub fn unique_lines_case_sensitive(
 5919        &mut self,
 5920        _: &UniqueLinesCaseSensitive,
 5921        cx: &mut ViewContext<Self>,
 5922    ) {
 5923        self.manipulate_lines(cx, |lines| {
 5924            let mut seen = HashSet::default();
 5925            lines.retain(|line| seen.insert(*line));
 5926        })
 5927    }
 5928
 5929    pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
 5930        let mut revert_changes = HashMap::default();
 5931        let snapshot = self.snapshot(cx);
 5932        for hunk in hunks_for_ranges(
 5933            Some(Point::zero()..snapshot.buffer_snapshot.max_point()).into_iter(),
 5934            &snapshot,
 5935        ) {
 5936            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5937        }
 5938        if !revert_changes.is_empty() {
 5939            self.transact(cx, |editor, cx| {
 5940                editor.revert(revert_changes, cx);
 5941            });
 5942        }
 5943    }
 5944
 5945    pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
 5946        let Some(project) = self.project.clone() else {
 5947            return;
 5948        };
 5949        self.reload(project, cx).detach_and_notify_err(cx);
 5950    }
 5951
 5952    pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
 5953        let revert_changes = self.gather_revert_changes(&self.selections.all(cx), cx);
 5954        if !revert_changes.is_empty() {
 5955            self.transact(cx, |editor, cx| {
 5956                editor.revert(revert_changes, cx);
 5957            });
 5958        }
 5959    }
 5960
 5961    fn revert_hunk(&mut self, hunk: HoveredHunk, cx: &mut ViewContext<Editor>) {
 5962        let snapshot = self.buffer.read(cx).read(cx);
 5963        if let Some(hunk) = crate::hunk_diff::to_diff_hunk(&hunk, &snapshot) {
 5964            drop(snapshot);
 5965            let mut revert_changes = HashMap::default();
 5966            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5967            if !revert_changes.is_empty() {
 5968                self.revert(revert_changes, cx)
 5969            }
 5970        }
 5971    }
 5972
 5973    pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
 5974        if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
 5975            let project_path = buffer.read(cx).project_path(cx)?;
 5976            let project = self.project.as_ref()?.read(cx);
 5977            let entry = project.entry_for_path(&project_path, cx)?;
 5978            let parent = match &entry.canonical_path {
 5979                Some(canonical_path) => canonical_path.to_path_buf(),
 5980                None => project.absolute_path(&project_path, cx)?,
 5981            }
 5982            .parent()?
 5983            .to_path_buf();
 5984            Some(parent)
 5985        }) {
 5986            cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
 5987        }
 5988    }
 5989
 5990    fn gather_revert_changes(
 5991        &mut self,
 5992        selections: &[Selection<Point>],
 5993        cx: &mut ViewContext<'_, Editor>,
 5994    ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
 5995        let mut revert_changes = HashMap::default();
 5996        let snapshot = self.snapshot(cx);
 5997        for hunk in hunks_for_selections(&snapshot, selections) {
 5998            self.prepare_revert_change(&mut revert_changes, &hunk, cx);
 5999        }
 6000        revert_changes
 6001    }
 6002
 6003    pub fn prepare_revert_change(
 6004        &mut self,
 6005        revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
 6006        hunk: &MultiBufferDiffHunk,
 6007        cx: &AppContext,
 6008    ) -> Option<()> {
 6009        let buffer = self.buffer.read(cx).buffer(hunk.buffer_id)?;
 6010        let buffer = buffer.read(cx);
 6011        let change_set = &self.diff_map.diff_bases.get(&hunk.buffer_id)?.change_set;
 6012        let original_text = change_set
 6013            .read(cx)
 6014            .base_text
 6015            .as_ref()?
 6016            .read(cx)
 6017            .as_rope()
 6018            .slice(hunk.diff_base_byte_range.clone());
 6019        let buffer_snapshot = buffer.snapshot();
 6020        let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
 6021        if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
 6022            probe
 6023                .0
 6024                .start
 6025                .cmp(&hunk.buffer_range.start, &buffer_snapshot)
 6026                .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
 6027        }) {
 6028            buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
 6029            Some(())
 6030        } else {
 6031            None
 6032        }
 6033    }
 6034
 6035    pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
 6036        self.manipulate_lines(cx, |lines| lines.reverse())
 6037    }
 6038
 6039    pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
 6040        self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
 6041    }
 6042
 6043    fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6044    where
 6045        Fn: FnMut(&mut Vec<&str>),
 6046    {
 6047        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6048        let buffer = self.buffer.read(cx).snapshot(cx);
 6049
 6050        let mut edits = Vec::new();
 6051
 6052        let selections = self.selections.all::<Point>(cx);
 6053        let mut selections = selections.iter().peekable();
 6054        let mut contiguous_row_selections = Vec::new();
 6055        let mut new_selections = Vec::new();
 6056        let mut added_lines = 0;
 6057        let mut removed_lines = 0;
 6058
 6059        while let Some(selection) = selections.next() {
 6060            let (start_row, end_row) = consume_contiguous_rows(
 6061                &mut contiguous_row_selections,
 6062                selection,
 6063                &display_map,
 6064                &mut selections,
 6065            );
 6066
 6067            let start_point = Point::new(start_row.0, 0);
 6068            let end_point = Point::new(
 6069                end_row.previous_row().0,
 6070                buffer.line_len(end_row.previous_row()),
 6071            );
 6072            let text = buffer
 6073                .text_for_range(start_point..end_point)
 6074                .collect::<String>();
 6075
 6076            let mut lines = text.split('\n').collect_vec();
 6077
 6078            let lines_before = lines.len();
 6079            callback(&mut lines);
 6080            let lines_after = lines.len();
 6081
 6082            edits.push((start_point..end_point, lines.join("\n")));
 6083
 6084            // Selections must change based on added and removed line count
 6085            let start_row =
 6086                MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
 6087            let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
 6088            new_selections.push(Selection {
 6089                id: selection.id,
 6090                start: start_row,
 6091                end: end_row,
 6092                goal: SelectionGoal::None,
 6093                reversed: selection.reversed,
 6094            });
 6095
 6096            if lines_after > lines_before {
 6097                added_lines += lines_after - lines_before;
 6098            } else if lines_before > lines_after {
 6099                removed_lines += lines_before - lines_after;
 6100            }
 6101        }
 6102
 6103        self.transact(cx, |this, cx| {
 6104            let buffer = this.buffer.update(cx, |buffer, cx| {
 6105                buffer.edit(edits, None, cx);
 6106                buffer.snapshot(cx)
 6107            });
 6108
 6109            // Recalculate offsets on newly edited buffer
 6110            let new_selections = new_selections
 6111                .iter()
 6112                .map(|s| {
 6113                    let start_point = Point::new(s.start.0, 0);
 6114                    let end_point = Point::new(s.end.0, buffer.line_len(s.end));
 6115                    Selection {
 6116                        id: s.id,
 6117                        start: buffer.point_to_offset(start_point),
 6118                        end: buffer.point_to_offset(end_point),
 6119                        goal: s.goal,
 6120                        reversed: s.reversed,
 6121                    }
 6122                })
 6123                .collect();
 6124
 6125            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6126                s.select(new_selections);
 6127            });
 6128
 6129            this.request_autoscroll(Autoscroll::fit(), cx);
 6130        });
 6131    }
 6132
 6133    pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
 6134        self.manipulate_text(cx, |text| text.to_uppercase())
 6135    }
 6136
 6137    pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
 6138        self.manipulate_text(cx, |text| text.to_lowercase())
 6139    }
 6140
 6141    pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
 6142        self.manipulate_text(cx, |text| {
 6143            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6144            // https://github.com/rutrum/convert-case/issues/16
 6145            text.split('\n')
 6146                .map(|line| line.to_case(Case::Title))
 6147                .join("\n")
 6148        })
 6149    }
 6150
 6151    pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
 6152        self.manipulate_text(cx, |text| text.to_case(Case::Snake))
 6153    }
 6154
 6155    pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
 6156        self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
 6157    }
 6158
 6159    pub fn convert_to_upper_camel_case(
 6160        &mut self,
 6161        _: &ConvertToUpperCamelCase,
 6162        cx: &mut ViewContext<Self>,
 6163    ) {
 6164        self.manipulate_text(cx, |text| {
 6165            // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
 6166            // https://github.com/rutrum/convert-case/issues/16
 6167            text.split('\n')
 6168                .map(|line| line.to_case(Case::UpperCamel))
 6169                .join("\n")
 6170        })
 6171    }
 6172
 6173    pub fn convert_to_lower_camel_case(
 6174        &mut self,
 6175        _: &ConvertToLowerCamelCase,
 6176        cx: &mut ViewContext<Self>,
 6177    ) {
 6178        self.manipulate_text(cx, |text| text.to_case(Case::Camel))
 6179    }
 6180
 6181    pub fn convert_to_opposite_case(
 6182        &mut self,
 6183        _: &ConvertToOppositeCase,
 6184        cx: &mut ViewContext<Self>,
 6185    ) {
 6186        self.manipulate_text(cx, |text| {
 6187            text.chars()
 6188                .fold(String::with_capacity(text.len()), |mut t, c| {
 6189                    if c.is_uppercase() {
 6190                        t.extend(c.to_lowercase());
 6191                    } else {
 6192                        t.extend(c.to_uppercase());
 6193                    }
 6194                    t
 6195                })
 6196        })
 6197    }
 6198
 6199    fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
 6200    where
 6201        Fn: FnMut(&str) -> String,
 6202    {
 6203        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6204        let buffer = self.buffer.read(cx).snapshot(cx);
 6205
 6206        let mut new_selections = Vec::new();
 6207        let mut edits = Vec::new();
 6208        let mut selection_adjustment = 0i32;
 6209
 6210        for selection in self.selections.all::<usize>(cx) {
 6211            let selection_is_empty = selection.is_empty();
 6212
 6213            let (start, end) = if selection_is_empty {
 6214                let word_range = movement::surrounding_word(
 6215                    &display_map,
 6216                    selection.start.to_display_point(&display_map),
 6217                );
 6218                let start = word_range.start.to_offset(&display_map, Bias::Left);
 6219                let end = word_range.end.to_offset(&display_map, Bias::Left);
 6220                (start, end)
 6221            } else {
 6222                (selection.start, selection.end)
 6223            };
 6224
 6225            let text = buffer.text_for_range(start..end).collect::<String>();
 6226            let old_length = text.len() as i32;
 6227            let text = callback(&text);
 6228
 6229            new_selections.push(Selection {
 6230                start: (start as i32 - selection_adjustment) as usize,
 6231                end: ((start + text.len()) as i32 - selection_adjustment) as usize,
 6232                goal: SelectionGoal::None,
 6233                ..selection
 6234            });
 6235
 6236            selection_adjustment += old_length - text.len() as i32;
 6237
 6238            edits.push((start..end, text));
 6239        }
 6240
 6241        self.transact(cx, |this, cx| {
 6242            this.buffer.update(cx, |buffer, cx| {
 6243                buffer.edit(edits, None, cx);
 6244            });
 6245
 6246            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6247                s.select(new_selections);
 6248            });
 6249
 6250            this.request_autoscroll(Autoscroll::fit(), cx);
 6251        });
 6252    }
 6253
 6254    pub fn duplicate(&mut self, upwards: bool, whole_lines: bool, cx: &mut ViewContext<Self>) {
 6255        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6256        let buffer = &display_map.buffer_snapshot;
 6257        let selections = self.selections.all::<Point>(cx);
 6258
 6259        let mut edits = Vec::new();
 6260        let mut selections_iter = selections.iter().peekable();
 6261        while let Some(selection) = selections_iter.next() {
 6262            let mut rows = selection.spanned_rows(false, &display_map);
 6263            // duplicate line-wise
 6264            if whole_lines || selection.start == selection.end {
 6265                // Avoid duplicating the same lines twice.
 6266                while let Some(next_selection) = selections_iter.peek() {
 6267                    let next_rows = next_selection.spanned_rows(false, &display_map);
 6268                    if next_rows.start < rows.end {
 6269                        rows.end = next_rows.end;
 6270                        selections_iter.next().unwrap();
 6271                    } else {
 6272                        break;
 6273                    }
 6274                }
 6275
 6276                // Copy the text from the selected row region and splice it either at the start
 6277                // or end of the region.
 6278                let start = Point::new(rows.start.0, 0);
 6279                let end = Point::new(
 6280                    rows.end.previous_row().0,
 6281                    buffer.line_len(rows.end.previous_row()),
 6282                );
 6283                let text = buffer
 6284                    .text_for_range(start..end)
 6285                    .chain(Some("\n"))
 6286                    .collect::<String>();
 6287                let insert_location = if upwards {
 6288                    Point::new(rows.end.0, 0)
 6289                } else {
 6290                    start
 6291                };
 6292                edits.push((insert_location..insert_location, text));
 6293            } else {
 6294                // duplicate character-wise
 6295                let start = selection.start;
 6296                let end = selection.end;
 6297                let text = buffer.text_for_range(start..end).collect::<String>();
 6298                edits.push((selection.end..selection.end, text));
 6299            }
 6300        }
 6301
 6302        self.transact(cx, |this, cx| {
 6303            this.buffer.update(cx, |buffer, cx| {
 6304                buffer.edit(edits, None, cx);
 6305            });
 6306
 6307            this.request_autoscroll(Autoscroll::fit(), cx);
 6308        });
 6309    }
 6310
 6311    pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
 6312        self.duplicate(true, true, cx);
 6313    }
 6314
 6315    pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
 6316        self.duplicate(false, true, cx);
 6317    }
 6318
 6319    pub fn duplicate_selection(&mut self, _: &DuplicateSelection, cx: &mut ViewContext<Self>) {
 6320        self.duplicate(false, false, cx);
 6321    }
 6322
 6323    pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
 6324        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6325        let buffer = self.buffer.read(cx).snapshot(cx);
 6326
 6327        let mut edits = Vec::new();
 6328        let mut unfold_ranges = Vec::new();
 6329        let mut refold_creases = Vec::new();
 6330
 6331        let selections = self.selections.all::<Point>(cx);
 6332        let mut selections = selections.iter().peekable();
 6333        let mut contiguous_row_selections = Vec::new();
 6334        let mut new_selections = Vec::new();
 6335
 6336        while let Some(selection) = selections.next() {
 6337            // Find all the selections that span a contiguous row range
 6338            let (start_row, end_row) = consume_contiguous_rows(
 6339                &mut contiguous_row_selections,
 6340                selection,
 6341                &display_map,
 6342                &mut selections,
 6343            );
 6344
 6345            // Move the text spanned by the row range to be before the line preceding the row range
 6346            if start_row.0 > 0 {
 6347                let range_to_move = Point::new(
 6348                    start_row.previous_row().0,
 6349                    buffer.line_len(start_row.previous_row()),
 6350                )
 6351                    ..Point::new(
 6352                        end_row.previous_row().0,
 6353                        buffer.line_len(end_row.previous_row()),
 6354                    );
 6355                let insertion_point = display_map
 6356                    .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
 6357                    .0;
 6358
 6359                // Don't move lines across excerpts
 6360                if buffer
 6361                    .excerpt_boundaries_in_range((
 6362                        Bound::Excluded(insertion_point),
 6363                        Bound::Included(range_to_move.end),
 6364                    ))
 6365                    .next()
 6366                    .is_none()
 6367                {
 6368                    let text = buffer
 6369                        .text_for_range(range_to_move.clone())
 6370                        .flat_map(|s| s.chars())
 6371                        .skip(1)
 6372                        .chain(['\n'])
 6373                        .collect::<String>();
 6374
 6375                    edits.push((
 6376                        buffer.anchor_after(range_to_move.start)
 6377                            ..buffer.anchor_before(range_to_move.end),
 6378                        String::new(),
 6379                    ));
 6380                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6381                    edits.push((insertion_anchor..insertion_anchor, text));
 6382
 6383                    let row_delta = range_to_move.start.row - insertion_point.row + 1;
 6384
 6385                    // Move selections up
 6386                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6387                        |mut selection| {
 6388                            selection.start.row -= row_delta;
 6389                            selection.end.row -= row_delta;
 6390                            selection
 6391                        },
 6392                    ));
 6393
 6394                    // Move folds up
 6395                    unfold_ranges.push(range_to_move.clone());
 6396                    for fold in display_map.folds_in_range(
 6397                        buffer.anchor_before(range_to_move.start)
 6398                            ..buffer.anchor_after(range_to_move.end),
 6399                    ) {
 6400                        let mut start = fold.range.start.to_point(&buffer);
 6401                        let mut end = fold.range.end.to_point(&buffer);
 6402                        start.row -= row_delta;
 6403                        end.row -= row_delta;
 6404                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6405                    }
 6406                }
 6407            }
 6408
 6409            // If we didn't move line(s), preserve the existing selections
 6410            new_selections.append(&mut contiguous_row_selections);
 6411        }
 6412
 6413        self.transact(cx, |this, cx| {
 6414            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6415            this.buffer.update(cx, |buffer, cx| {
 6416                for (range, text) in edits {
 6417                    buffer.edit([(range, text)], None, cx);
 6418                }
 6419            });
 6420            this.fold_creases(refold_creases, true, cx);
 6421            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6422                s.select(new_selections);
 6423            })
 6424        });
 6425    }
 6426
 6427    pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
 6428        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 6429        let buffer = self.buffer.read(cx).snapshot(cx);
 6430
 6431        let mut edits = Vec::new();
 6432        let mut unfold_ranges = Vec::new();
 6433        let mut refold_creases = Vec::new();
 6434
 6435        let selections = self.selections.all::<Point>(cx);
 6436        let mut selections = selections.iter().peekable();
 6437        let mut contiguous_row_selections = Vec::new();
 6438        let mut new_selections = Vec::new();
 6439
 6440        while let Some(selection) = selections.next() {
 6441            // Find all the selections that span a contiguous row range
 6442            let (start_row, end_row) = consume_contiguous_rows(
 6443                &mut contiguous_row_selections,
 6444                selection,
 6445                &display_map,
 6446                &mut selections,
 6447            );
 6448
 6449            // Move the text spanned by the row range to be after the last line of the row range
 6450            if end_row.0 <= buffer.max_point().row {
 6451                let range_to_move =
 6452                    MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
 6453                let insertion_point = display_map
 6454                    .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
 6455                    .0;
 6456
 6457                // Don't move lines across excerpt boundaries
 6458                if buffer
 6459                    .excerpt_boundaries_in_range((
 6460                        Bound::Excluded(range_to_move.start),
 6461                        Bound::Included(insertion_point),
 6462                    ))
 6463                    .next()
 6464                    .is_none()
 6465                {
 6466                    let mut text = String::from("\n");
 6467                    text.extend(buffer.text_for_range(range_to_move.clone()));
 6468                    text.pop(); // Drop trailing newline
 6469                    edits.push((
 6470                        buffer.anchor_after(range_to_move.start)
 6471                            ..buffer.anchor_before(range_to_move.end),
 6472                        String::new(),
 6473                    ));
 6474                    let insertion_anchor = buffer.anchor_after(insertion_point);
 6475                    edits.push((insertion_anchor..insertion_anchor, text));
 6476
 6477                    let row_delta = insertion_point.row - range_to_move.end.row + 1;
 6478
 6479                    // Move selections down
 6480                    new_selections.extend(contiguous_row_selections.drain(..).map(
 6481                        |mut selection| {
 6482                            selection.start.row += row_delta;
 6483                            selection.end.row += row_delta;
 6484                            selection
 6485                        },
 6486                    ));
 6487
 6488                    // Move folds down
 6489                    unfold_ranges.push(range_to_move.clone());
 6490                    for fold in display_map.folds_in_range(
 6491                        buffer.anchor_before(range_to_move.start)
 6492                            ..buffer.anchor_after(range_to_move.end),
 6493                    ) {
 6494                        let mut start = fold.range.start.to_point(&buffer);
 6495                        let mut end = fold.range.end.to_point(&buffer);
 6496                        start.row += row_delta;
 6497                        end.row += row_delta;
 6498                        refold_creases.push(Crease::simple(start..end, fold.placeholder.clone()));
 6499                    }
 6500                }
 6501            }
 6502
 6503            // If we didn't move line(s), preserve the existing selections
 6504            new_selections.append(&mut contiguous_row_selections);
 6505        }
 6506
 6507        self.transact(cx, |this, cx| {
 6508            this.unfold_ranges(&unfold_ranges, true, true, cx);
 6509            this.buffer.update(cx, |buffer, cx| {
 6510                for (range, text) in edits {
 6511                    buffer.edit([(range, text)], None, cx);
 6512                }
 6513            });
 6514            this.fold_creases(refold_creases, true, cx);
 6515            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
 6516        });
 6517    }
 6518
 6519    pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
 6520        let text_layout_details = &self.text_layout_details(cx);
 6521        self.transact(cx, |this, cx| {
 6522            let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6523                let mut edits: Vec<(Range<usize>, String)> = Default::default();
 6524                let line_mode = s.line_mode;
 6525                s.move_with(|display_map, selection| {
 6526                    if !selection.is_empty() || line_mode {
 6527                        return;
 6528                    }
 6529
 6530                    let mut head = selection.head();
 6531                    let mut transpose_offset = head.to_offset(display_map, Bias::Right);
 6532                    if head.column() == display_map.line_len(head.row()) {
 6533                        transpose_offset = display_map
 6534                            .buffer_snapshot
 6535                            .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6536                    }
 6537
 6538                    if transpose_offset == 0 {
 6539                        return;
 6540                    }
 6541
 6542                    *head.column_mut() += 1;
 6543                    head = display_map.clip_point(head, Bias::Right);
 6544                    let goal = SelectionGoal::HorizontalPosition(
 6545                        display_map
 6546                            .x_for_display_point(head, text_layout_details)
 6547                            .into(),
 6548                    );
 6549                    selection.collapse_to(head, goal);
 6550
 6551                    let transpose_start = display_map
 6552                        .buffer_snapshot
 6553                        .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
 6554                    if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
 6555                        let transpose_end = display_map
 6556                            .buffer_snapshot
 6557                            .clip_offset(transpose_offset + 1, Bias::Right);
 6558                        if let Some(ch) =
 6559                            display_map.buffer_snapshot.chars_at(transpose_start).next()
 6560                        {
 6561                            edits.push((transpose_start..transpose_offset, String::new()));
 6562                            edits.push((transpose_end..transpose_end, ch.to_string()));
 6563                        }
 6564                    }
 6565                });
 6566                edits
 6567            });
 6568            this.buffer
 6569                .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6570            let selections = this.selections.all::<usize>(cx);
 6571            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6572                s.select(selections);
 6573            });
 6574        });
 6575    }
 6576
 6577    pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
 6578        self.rewrap_impl(IsVimMode::No, cx)
 6579    }
 6580
 6581    pub fn rewrap_impl(&mut self, is_vim_mode: IsVimMode, cx: &mut ViewContext<Self>) {
 6582        let buffer = self.buffer.read(cx).snapshot(cx);
 6583        let selections = self.selections.all::<Point>(cx);
 6584        let mut selections = selections.iter().peekable();
 6585
 6586        let mut edits = Vec::new();
 6587        let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
 6588
 6589        while let Some(selection) = selections.next() {
 6590            let mut start_row = selection.start.row;
 6591            let mut end_row = selection.end.row;
 6592
 6593            // Skip selections that overlap with a range that has already been rewrapped.
 6594            let selection_range = start_row..end_row;
 6595            if rewrapped_row_ranges
 6596                .iter()
 6597                .any(|range| range.overlaps(&selection_range))
 6598            {
 6599                continue;
 6600            }
 6601
 6602            let mut should_rewrap = is_vim_mode == IsVimMode::Yes;
 6603
 6604            if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
 6605                match language_scope.language_name().0.as_ref() {
 6606                    "Markdown" | "Plain Text" => {
 6607                        should_rewrap = true;
 6608                    }
 6609                    _ => {}
 6610                }
 6611            }
 6612
 6613            let tab_size = buffer.settings_at(selection.head(), cx).tab_size;
 6614
 6615            // Since not all lines in the selection may be at the same indent
 6616            // level, choose the indent size that is the most common between all
 6617            // of the lines.
 6618            //
 6619            // If there is a tie, we use the deepest indent.
 6620            let (indent_size, indent_end) = {
 6621                let mut indent_size_occurrences = HashMap::default();
 6622                let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
 6623
 6624                for row in start_row..=end_row {
 6625                    let indent = buffer.indent_size_for_line(MultiBufferRow(row));
 6626                    rows_by_indent_size.entry(indent).or_default().push(row);
 6627                    *indent_size_occurrences.entry(indent).or_insert(0) += 1;
 6628                }
 6629
 6630                let indent_size = indent_size_occurrences
 6631                    .into_iter()
 6632                    .max_by_key(|(indent, count)| (*count, indent.len_with_expanded_tabs(tab_size)))
 6633                    .map(|(indent, _)| indent)
 6634                    .unwrap_or_default();
 6635                let row = rows_by_indent_size[&indent_size][0];
 6636                let indent_end = Point::new(row, indent_size.len);
 6637
 6638                (indent_size, indent_end)
 6639            };
 6640
 6641            let mut line_prefix = indent_size.chars().collect::<String>();
 6642
 6643            if let Some(comment_prefix) =
 6644                buffer
 6645                    .language_scope_at(selection.head())
 6646                    .and_then(|language| {
 6647                        language
 6648                            .line_comment_prefixes()
 6649                            .iter()
 6650                            .find(|prefix| buffer.contains_str_at(indent_end, prefix))
 6651                            .cloned()
 6652                    })
 6653            {
 6654                line_prefix.push_str(&comment_prefix);
 6655                should_rewrap = true;
 6656            }
 6657
 6658            if !should_rewrap {
 6659                continue;
 6660            }
 6661
 6662            if selection.is_empty() {
 6663                'expand_upwards: while start_row > 0 {
 6664                    let prev_row = start_row - 1;
 6665                    if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
 6666                        && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
 6667                    {
 6668                        start_row = prev_row;
 6669                    } else {
 6670                        break 'expand_upwards;
 6671                    }
 6672                }
 6673
 6674                'expand_downwards: while end_row < buffer.max_point().row {
 6675                    let next_row = end_row + 1;
 6676                    if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
 6677                        && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
 6678                    {
 6679                        end_row = next_row;
 6680                    } else {
 6681                        break 'expand_downwards;
 6682                    }
 6683                }
 6684            }
 6685
 6686            let start = Point::new(start_row, 0);
 6687            let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
 6688            let selection_text = buffer.text_for_range(start..end).collect::<String>();
 6689            let Some(lines_without_prefixes) = selection_text
 6690                .lines()
 6691                .map(|line| {
 6692                    line.strip_prefix(&line_prefix)
 6693                        .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
 6694                        .ok_or_else(|| {
 6695                            anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
 6696                        })
 6697                })
 6698                .collect::<Result<Vec<_>, _>>()
 6699                .log_err()
 6700            else {
 6701                continue;
 6702            };
 6703
 6704            let wrap_column = buffer
 6705                .settings_at(Point::new(start_row, 0), cx)
 6706                .preferred_line_length as usize;
 6707            let wrapped_text = wrap_with_prefix(
 6708                line_prefix,
 6709                lines_without_prefixes.join(" "),
 6710                wrap_column,
 6711                tab_size,
 6712            );
 6713
 6714            // TODO: should always use char-based diff while still supporting cursor behavior that
 6715            // matches vim.
 6716            let diff = match is_vim_mode {
 6717                IsVimMode::Yes => TextDiff::from_lines(&selection_text, &wrapped_text),
 6718                IsVimMode::No => TextDiff::from_chars(&selection_text, &wrapped_text),
 6719            };
 6720            let mut offset = start.to_offset(&buffer);
 6721            let mut moved_since_edit = true;
 6722
 6723            for change in diff.iter_all_changes() {
 6724                let value = change.value();
 6725                match change.tag() {
 6726                    ChangeTag::Equal => {
 6727                        offset += value.len();
 6728                        moved_since_edit = true;
 6729                    }
 6730                    ChangeTag::Delete => {
 6731                        let start = buffer.anchor_after(offset);
 6732                        let end = buffer.anchor_before(offset + value.len());
 6733
 6734                        if moved_since_edit {
 6735                            edits.push((start..end, String::new()));
 6736                        } else {
 6737                            edits.last_mut().unwrap().0.end = end;
 6738                        }
 6739
 6740                        offset += value.len();
 6741                        moved_since_edit = false;
 6742                    }
 6743                    ChangeTag::Insert => {
 6744                        if moved_since_edit {
 6745                            let anchor = buffer.anchor_after(offset);
 6746                            edits.push((anchor..anchor, value.to_string()));
 6747                        } else {
 6748                            edits.last_mut().unwrap().1.push_str(value);
 6749                        }
 6750
 6751                        moved_since_edit = false;
 6752                    }
 6753                }
 6754            }
 6755
 6756            rewrapped_row_ranges.push(start_row..=end_row);
 6757        }
 6758
 6759        self.buffer
 6760            .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
 6761    }
 6762
 6763    pub fn cut_common(&mut self, cx: &mut ViewContext<Self>) -> ClipboardItem {
 6764        let mut text = String::new();
 6765        let buffer = self.buffer.read(cx).snapshot(cx);
 6766        let mut selections = self.selections.all::<Point>(cx);
 6767        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6768        {
 6769            let max_point = buffer.max_point();
 6770            let mut is_first = true;
 6771            for selection in &mut selections {
 6772                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6773                if is_entire_line {
 6774                    selection.start = Point::new(selection.start.row, 0);
 6775                    if !selection.is_empty() && selection.end.column == 0 {
 6776                        selection.end = cmp::min(max_point, selection.end);
 6777                    } else {
 6778                        selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
 6779                    }
 6780                    selection.goal = SelectionGoal::None;
 6781                }
 6782                if is_first {
 6783                    is_first = false;
 6784                } else {
 6785                    text += "\n";
 6786                }
 6787                let mut len = 0;
 6788                for chunk in buffer.text_for_range(selection.start..selection.end) {
 6789                    text.push_str(chunk);
 6790                    len += chunk.len();
 6791                }
 6792                clipboard_selections.push(ClipboardSelection {
 6793                    len,
 6794                    is_entire_line,
 6795                    first_line_indent: buffer
 6796                        .indent_size_for_line(MultiBufferRow(selection.start.row))
 6797                        .len,
 6798                });
 6799            }
 6800        }
 6801
 6802        self.transact(cx, |this, cx| {
 6803            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 6804                s.select(selections);
 6805            });
 6806            this.insert("", cx);
 6807        });
 6808        ClipboardItem::new_string_with_json_metadata(text, clipboard_selections)
 6809    }
 6810
 6811    pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
 6812        let item = self.cut_common(cx);
 6813        cx.write_to_clipboard(item);
 6814    }
 6815
 6816    pub fn kill_ring_cut(&mut self, _: &KillRingCut, cx: &mut ViewContext<Self>) {
 6817        self.change_selections(None, cx, |s| {
 6818            s.move_with(|snapshot, sel| {
 6819                if sel.is_empty() {
 6820                    sel.end = DisplayPoint::new(sel.end.row(), snapshot.line_len(sel.end.row()))
 6821                }
 6822            });
 6823        });
 6824        let item = self.cut_common(cx);
 6825        cx.set_global(KillRing(item))
 6826    }
 6827
 6828    pub fn kill_ring_yank(&mut self, _: &KillRingYank, cx: &mut ViewContext<Self>) {
 6829        let (text, metadata) = if let Some(KillRing(item)) = cx.try_global() {
 6830            if let Some(ClipboardEntry::String(kill_ring)) = item.entries().first() {
 6831                (kill_ring.text().to_string(), kill_ring.metadata_json())
 6832            } else {
 6833                return;
 6834            }
 6835        } else {
 6836            return;
 6837        };
 6838        self.do_paste(&text, metadata, false, cx);
 6839    }
 6840
 6841    pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
 6842        let selections = self.selections.all::<Point>(cx);
 6843        let buffer = self.buffer.read(cx).read(cx);
 6844        let mut text = String::new();
 6845
 6846        let mut clipboard_selections = Vec::with_capacity(selections.len());
 6847        {
 6848            let max_point = buffer.max_point();
 6849            let mut is_first = true;
 6850            for selection in selections.iter() {
 6851                let mut start = selection.start;
 6852                let mut end = selection.end;
 6853                let is_entire_line = selection.is_empty() || self.selections.line_mode;
 6854                if is_entire_line {
 6855                    start = Point::new(start.row, 0);
 6856                    end = cmp::min(max_point, Point::new(end.row + 1, 0));
 6857                }
 6858                if is_first {
 6859                    is_first = false;
 6860                } else {
 6861                    text += "\n";
 6862                }
 6863                let mut len = 0;
 6864                for chunk in buffer.text_for_range(start..end) {
 6865                    text.push_str(chunk);
 6866                    len += chunk.len();
 6867                }
 6868                clipboard_selections.push(ClipboardSelection {
 6869                    len,
 6870                    is_entire_line,
 6871                    first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
 6872                });
 6873            }
 6874        }
 6875
 6876        cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
 6877            text,
 6878            clipboard_selections,
 6879        ));
 6880    }
 6881
 6882    pub fn do_paste(
 6883        &mut self,
 6884        text: &String,
 6885        clipboard_selections: Option<Vec<ClipboardSelection>>,
 6886        handle_entire_lines: bool,
 6887        cx: &mut ViewContext<Self>,
 6888    ) {
 6889        if self.read_only(cx) {
 6890            return;
 6891        }
 6892
 6893        let clipboard_text = Cow::Borrowed(text);
 6894
 6895        self.transact(cx, |this, cx| {
 6896            if let Some(mut clipboard_selections) = clipboard_selections {
 6897                let old_selections = this.selections.all::<usize>(cx);
 6898                let all_selections_were_entire_line =
 6899                    clipboard_selections.iter().all(|s| s.is_entire_line);
 6900                let first_selection_indent_column =
 6901                    clipboard_selections.first().map(|s| s.first_line_indent);
 6902                if clipboard_selections.len() != old_selections.len() {
 6903                    clipboard_selections.drain(..);
 6904                }
 6905                let cursor_offset = this.selections.last::<usize>(cx).head();
 6906                let mut auto_indent_on_paste = true;
 6907
 6908                this.buffer.update(cx, |buffer, cx| {
 6909                    let snapshot = buffer.read(cx);
 6910                    auto_indent_on_paste =
 6911                        snapshot.settings_at(cursor_offset, cx).auto_indent_on_paste;
 6912
 6913                    let mut start_offset = 0;
 6914                    let mut edits = Vec::new();
 6915                    let mut original_indent_columns = Vec::new();
 6916                    for (ix, selection) in old_selections.iter().enumerate() {
 6917                        let to_insert;
 6918                        let entire_line;
 6919                        let original_indent_column;
 6920                        if let Some(clipboard_selection) = clipboard_selections.get(ix) {
 6921                            let end_offset = start_offset + clipboard_selection.len;
 6922                            to_insert = &clipboard_text[start_offset..end_offset];
 6923                            entire_line = clipboard_selection.is_entire_line;
 6924                            start_offset = end_offset + 1;
 6925                            original_indent_column = Some(clipboard_selection.first_line_indent);
 6926                        } else {
 6927                            to_insert = clipboard_text.as_str();
 6928                            entire_line = all_selections_were_entire_line;
 6929                            original_indent_column = first_selection_indent_column
 6930                        }
 6931
 6932                        // If the corresponding selection was empty when this slice of the
 6933                        // clipboard text was written, then the entire line containing the
 6934                        // selection was copied. If this selection is also currently empty,
 6935                        // then paste the line before the current line of the buffer.
 6936                        let range = if selection.is_empty() && handle_entire_lines && entire_line {
 6937                            let column = selection.start.to_point(&snapshot).column as usize;
 6938                            let line_start = selection.start - column;
 6939                            line_start..line_start
 6940                        } else {
 6941                            selection.range()
 6942                        };
 6943
 6944                        edits.push((range, to_insert));
 6945                        original_indent_columns.extend(original_indent_column);
 6946                    }
 6947                    drop(snapshot);
 6948
 6949                    buffer.edit(
 6950                        edits,
 6951                        if auto_indent_on_paste {
 6952                            Some(AutoindentMode::Block {
 6953                                original_indent_columns,
 6954                            })
 6955                        } else {
 6956                            None
 6957                        },
 6958                        cx,
 6959                    );
 6960                });
 6961
 6962                let selections = this.selections.all::<usize>(cx);
 6963                this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 6964            } else {
 6965                this.insert(&clipboard_text, cx);
 6966            }
 6967        });
 6968    }
 6969
 6970    pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
 6971        if let Some(item) = cx.read_from_clipboard() {
 6972            let entries = item.entries();
 6973
 6974            match entries.first() {
 6975                // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
 6976                // of all the pasted entries.
 6977                Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
 6978                    .do_paste(
 6979                        clipboard_string.text(),
 6980                        clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
 6981                        true,
 6982                        cx,
 6983                    ),
 6984                _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
 6985            }
 6986        }
 6987    }
 6988
 6989    pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
 6990        if self.read_only(cx) {
 6991            return;
 6992        }
 6993
 6994        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
 6995            if let Some((selections, _)) =
 6996                self.selection_history.transaction(transaction_id).cloned()
 6997            {
 6998                self.change_selections(None, cx, |s| {
 6999                    s.select_anchors(selections.to_vec());
 7000                });
 7001            }
 7002            self.request_autoscroll(Autoscroll::fit(), cx);
 7003            self.unmark_text(cx);
 7004            self.refresh_inline_completion(true, false, cx);
 7005            cx.emit(EditorEvent::Edited { transaction_id });
 7006            cx.emit(EditorEvent::TransactionUndone { transaction_id });
 7007        }
 7008    }
 7009
 7010    pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
 7011        if self.read_only(cx) {
 7012            return;
 7013        }
 7014
 7015        if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
 7016            if let Some((_, Some(selections))) =
 7017                self.selection_history.transaction(transaction_id).cloned()
 7018            {
 7019                self.change_selections(None, cx, |s| {
 7020                    s.select_anchors(selections.to_vec());
 7021                });
 7022            }
 7023            self.request_autoscroll(Autoscroll::fit(), cx);
 7024            self.unmark_text(cx);
 7025            self.refresh_inline_completion(true, false, cx);
 7026            cx.emit(EditorEvent::Edited { transaction_id });
 7027        }
 7028    }
 7029
 7030    pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
 7031        self.buffer
 7032            .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 7033    }
 7034
 7035    pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
 7036        self.buffer
 7037            .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
 7038    }
 7039
 7040    pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
 7041        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7042            let line_mode = s.line_mode;
 7043            s.move_with(|map, selection| {
 7044                let cursor = if selection.is_empty() && !line_mode {
 7045                    movement::left(map, selection.start)
 7046                } else {
 7047                    selection.start
 7048                };
 7049                selection.collapse_to(cursor, SelectionGoal::None);
 7050            });
 7051        })
 7052    }
 7053
 7054    pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
 7055        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7056            s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
 7057        })
 7058    }
 7059
 7060    pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
 7061        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7062            let line_mode = s.line_mode;
 7063            s.move_with(|map, selection| {
 7064                let cursor = if selection.is_empty() && !line_mode {
 7065                    movement::right(map, selection.end)
 7066                } else {
 7067                    selection.end
 7068                };
 7069                selection.collapse_to(cursor, SelectionGoal::None)
 7070            });
 7071        })
 7072    }
 7073
 7074    pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
 7075        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7076            s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
 7077        })
 7078    }
 7079
 7080    pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
 7081        if self.take_rename(true, cx).is_some() {
 7082            return;
 7083        }
 7084
 7085        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7086            cx.propagate();
 7087            return;
 7088        }
 7089
 7090        let text_layout_details = &self.text_layout_details(cx);
 7091        let selection_count = self.selections.count();
 7092        let first_selection = self.selections.first_anchor();
 7093
 7094        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7095            let line_mode = s.line_mode;
 7096            s.move_with(|map, selection| {
 7097                if !selection.is_empty() && !line_mode {
 7098                    selection.goal = SelectionGoal::None;
 7099                }
 7100                let (cursor, goal) = movement::up(
 7101                    map,
 7102                    selection.start,
 7103                    selection.goal,
 7104                    false,
 7105                    text_layout_details,
 7106                );
 7107                selection.collapse_to(cursor, goal);
 7108            });
 7109        });
 7110
 7111        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7112        {
 7113            cx.propagate();
 7114        }
 7115    }
 7116
 7117    pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
 7118        if self.take_rename(true, cx).is_some() {
 7119            return;
 7120        }
 7121
 7122        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7123            cx.propagate();
 7124            return;
 7125        }
 7126
 7127        let text_layout_details = &self.text_layout_details(cx);
 7128
 7129        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7130            let line_mode = s.line_mode;
 7131            s.move_with(|map, selection| {
 7132                if !selection.is_empty() && !line_mode {
 7133                    selection.goal = SelectionGoal::None;
 7134                }
 7135                let (cursor, goal) = movement::up_by_rows(
 7136                    map,
 7137                    selection.start,
 7138                    action.lines,
 7139                    selection.goal,
 7140                    false,
 7141                    text_layout_details,
 7142                );
 7143                selection.collapse_to(cursor, goal);
 7144            });
 7145        })
 7146    }
 7147
 7148    pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
 7149        if self.take_rename(true, cx).is_some() {
 7150            return;
 7151        }
 7152
 7153        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7154            cx.propagate();
 7155            return;
 7156        }
 7157
 7158        let text_layout_details = &self.text_layout_details(cx);
 7159
 7160        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7161            let line_mode = s.line_mode;
 7162            s.move_with(|map, selection| {
 7163                if !selection.is_empty() && !line_mode {
 7164                    selection.goal = SelectionGoal::None;
 7165                }
 7166                let (cursor, goal) = movement::down_by_rows(
 7167                    map,
 7168                    selection.start,
 7169                    action.lines,
 7170                    selection.goal,
 7171                    false,
 7172                    text_layout_details,
 7173                );
 7174                selection.collapse_to(cursor, goal);
 7175            });
 7176        })
 7177    }
 7178
 7179    pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
 7180        let text_layout_details = &self.text_layout_details(cx);
 7181        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7182            s.move_heads_with(|map, head, goal| {
 7183                movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7184            })
 7185        })
 7186    }
 7187
 7188    pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
 7189        let text_layout_details = &self.text_layout_details(cx);
 7190        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7191            s.move_heads_with(|map, head, goal| {
 7192                movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
 7193            })
 7194        })
 7195    }
 7196
 7197    pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
 7198        let Some(row_count) = self.visible_row_count() else {
 7199            return;
 7200        };
 7201
 7202        let text_layout_details = &self.text_layout_details(cx);
 7203
 7204        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7205            s.move_heads_with(|map, head, goal| {
 7206                movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
 7207            })
 7208        })
 7209    }
 7210
 7211    pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
 7212        if self.take_rename(true, cx).is_some() {
 7213            return;
 7214        }
 7215
 7216        if self
 7217            .context_menu
 7218            .borrow_mut()
 7219            .as_mut()
 7220            .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
 7221            .unwrap_or(false)
 7222        {
 7223            return;
 7224        }
 7225
 7226        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7227            cx.propagate();
 7228            return;
 7229        }
 7230
 7231        let Some(row_count) = self.visible_row_count() else {
 7232            return;
 7233        };
 7234
 7235        let autoscroll = if action.center_cursor {
 7236            Autoscroll::center()
 7237        } else {
 7238            Autoscroll::fit()
 7239        };
 7240
 7241        let text_layout_details = &self.text_layout_details(cx);
 7242
 7243        self.change_selections(Some(autoscroll), cx, |s| {
 7244            let line_mode = s.line_mode;
 7245            s.move_with(|map, selection| {
 7246                if !selection.is_empty() && !line_mode {
 7247                    selection.goal = SelectionGoal::None;
 7248                }
 7249                let (cursor, goal) = movement::up_by_rows(
 7250                    map,
 7251                    selection.end,
 7252                    row_count,
 7253                    selection.goal,
 7254                    false,
 7255                    text_layout_details,
 7256                );
 7257                selection.collapse_to(cursor, goal);
 7258            });
 7259        });
 7260    }
 7261
 7262    pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
 7263        let text_layout_details = &self.text_layout_details(cx);
 7264        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7265            s.move_heads_with(|map, head, goal| {
 7266                movement::up(map, head, goal, false, text_layout_details)
 7267            })
 7268        })
 7269    }
 7270
 7271    pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
 7272        self.take_rename(true, cx);
 7273
 7274        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7275            cx.propagate();
 7276            return;
 7277        }
 7278
 7279        let text_layout_details = &self.text_layout_details(cx);
 7280        let selection_count = self.selections.count();
 7281        let first_selection = self.selections.first_anchor();
 7282
 7283        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7284            let line_mode = s.line_mode;
 7285            s.move_with(|map, selection| {
 7286                if !selection.is_empty() && !line_mode {
 7287                    selection.goal = SelectionGoal::None;
 7288                }
 7289                let (cursor, goal) = movement::down(
 7290                    map,
 7291                    selection.end,
 7292                    selection.goal,
 7293                    false,
 7294                    text_layout_details,
 7295                );
 7296                selection.collapse_to(cursor, goal);
 7297            });
 7298        });
 7299
 7300        if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
 7301        {
 7302            cx.propagate();
 7303        }
 7304    }
 7305
 7306    pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
 7307        let Some(row_count) = self.visible_row_count() else {
 7308            return;
 7309        };
 7310
 7311        let text_layout_details = &self.text_layout_details(cx);
 7312
 7313        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7314            s.move_heads_with(|map, head, goal| {
 7315                movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
 7316            })
 7317        })
 7318    }
 7319
 7320    pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
 7321        if self.take_rename(true, cx).is_some() {
 7322            return;
 7323        }
 7324
 7325        if self
 7326            .context_menu
 7327            .borrow_mut()
 7328            .as_mut()
 7329            .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
 7330            .unwrap_or(false)
 7331        {
 7332            return;
 7333        }
 7334
 7335        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7336            cx.propagate();
 7337            return;
 7338        }
 7339
 7340        let Some(row_count) = self.visible_row_count() else {
 7341            return;
 7342        };
 7343
 7344        let autoscroll = if action.center_cursor {
 7345            Autoscroll::center()
 7346        } else {
 7347            Autoscroll::fit()
 7348        };
 7349
 7350        let text_layout_details = &self.text_layout_details(cx);
 7351        self.change_selections(Some(autoscroll), cx, |s| {
 7352            let line_mode = s.line_mode;
 7353            s.move_with(|map, selection| {
 7354                if !selection.is_empty() && !line_mode {
 7355                    selection.goal = SelectionGoal::None;
 7356                }
 7357                let (cursor, goal) = movement::down_by_rows(
 7358                    map,
 7359                    selection.end,
 7360                    row_count,
 7361                    selection.goal,
 7362                    false,
 7363                    text_layout_details,
 7364                );
 7365                selection.collapse_to(cursor, goal);
 7366            });
 7367        });
 7368    }
 7369
 7370    pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
 7371        let text_layout_details = &self.text_layout_details(cx);
 7372        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7373            s.move_heads_with(|map, head, goal| {
 7374                movement::down(map, head, goal, false, text_layout_details)
 7375            })
 7376        });
 7377    }
 7378
 7379    pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
 7380        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7381            context_menu.select_first(self.completion_provider.as_deref(), cx);
 7382        }
 7383    }
 7384
 7385    pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
 7386        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7387            context_menu.select_prev(self.completion_provider.as_deref(), cx);
 7388        }
 7389    }
 7390
 7391    pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
 7392        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7393            context_menu.select_next(self.completion_provider.as_deref(), cx);
 7394        }
 7395    }
 7396
 7397    pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
 7398        if let Some(context_menu) = self.context_menu.borrow_mut().as_mut() {
 7399            context_menu.select_last(self.completion_provider.as_deref(), cx);
 7400        }
 7401    }
 7402
 7403    pub fn move_to_previous_word_start(
 7404        &mut self,
 7405        _: &MoveToPreviousWordStart,
 7406        cx: &mut ViewContext<Self>,
 7407    ) {
 7408        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7409            s.move_cursors_with(|map, head, _| {
 7410                (
 7411                    movement::previous_word_start(map, head),
 7412                    SelectionGoal::None,
 7413                )
 7414            });
 7415        })
 7416    }
 7417
 7418    pub fn move_to_previous_subword_start(
 7419        &mut self,
 7420        _: &MoveToPreviousSubwordStart,
 7421        cx: &mut ViewContext<Self>,
 7422    ) {
 7423        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7424            s.move_cursors_with(|map, head, _| {
 7425                (
 7426                    movement::previous_subword_start(map, head),
 7427                    SelectionGoal::None,
 7428                )
 7429            });
 7430        })
 7431    }
 7432
 7433    pub fn select_to_previous_word_start(
 7434        &mut self,
 7435        _: &SelectToPreviousWordStart,
 7436        cx: &mut ViewContext<Self>,
 7437    ) {
 7438        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7439            s.move_heads_with(|map, head, _| {
 7440                (
 7441                    movement::previous_word_start(map, head),
 7442                    SelectionGoal::None,
 7443                )
 7444            });
 7445        })
 7446    }
 7447
 7448    pub fn select_to_previous_subword_start(
 7449        &mut self,
 7450        _: &SelectToPreviousSubwordStart,
 7451        cx: &mut ViewContext<Self>,
 7452    ) {
 7453        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7454            s.move_heads_with(|map, head, _| {
 7455                (
 7456                    movement::previous_subword_start(map, head),
 7457                    SelectionGoal::None,
 7458                )
 7459            });
 7460        })
 7461    }
 7462
 7463    pub fn delete_to_previous_word_start(
 7464        &mut self,
 7465        action: &DeleteToPreviousWordStart,
 7466        cx: &mut ViewContext<Self>,
 7467    ) {
 7468        self.transact(cx, |this, cx| {
 7469            this.select_autoclose_pair(cx);
 7470            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7471                let line_mode = s.line_mode;
 7472                s.move_with(|map, selection| {
 7473                    if selection.is_empty() && !line_mode {
 7474                        let cursor = if action.ignore_newlines {
 7475                            movement::previous_word_start(map, selection.head())
 7476                        } else {
 7477                            movement::previous_word_start_or_newline(map, selection.head())
 7478                        };
 7479                        selection.set_head(cursor, SelectionGoal::None);
 7480                    }
 7481                });
 7482            });
 7483            this.insert("", cx);
 7484        });
 7485    }
 7486
 7487    pub fn delete_to_previous_subword_start(
 7488        &mut self,
 7489        _: &DeleteToPreviousSubwordStart,
 7490        cx: &mut ViewContext<Self>,
 7491    ) {
 7492        self.transact(cx, |this, cx| {
 7493            this.select_autoclose_pair(cx);
 7494            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7495                let line_mode = s.line_mode;
 7496                s.move_with(|map, selection| {
 7497                    if selection.is_empty() && !line_mode {
 7498                        let cursor = movement::previous_subword_start(map, selection.head());
 7499                        selection.set_head(cursor, SelectionGoal::None);
 7500                    }
 7501                });
 7502            });
 7503            this.insert("", cx);
 7504        });
 7505    }
 7506
 7507    pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
 7508        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7509            s.move_cursors_with(|map, head, _| {
 7510                (movement::next_word_end(map, head), SelectionGoal::None)
 7511            });
 7512        })
 7513    }
 7514
 7515    pub fn move_to_next_subword_end(
 7516        &mut self,
 7517        _: &MoveToNextSubwordEnd,
 7518        cx: &mut ViewContext<Self>,
 7519    ) {
 7520        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7521            s.move_cursors_with(|map, head, _| {
 7522                (movement::next_subword_end(map, head), SelectionGoal::None)
 7523            });
 7524        })
 7525    }
 7526
 7527    pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
 7528        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7529            s.move_heads_with(|map, head, _| {
 7530                (movement::next_word_end(map, head), SelectionGoal::None)
 7531            });
 7532        })
 7533    }
 7534
 7535    pub fn select_to_next_subword_end(
 7536        &mut self,
 7537        _: &SelectToNextSubwordEnd,
 7538        cx: &mut ViewContext<Self>,
 7539    ) {
 7540        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7541            s.move_heads_with(|map, head, _| {
 7542                (movement::next_subword_end(map, head), SelectionGoal::None)
 7543            });
 7544        })
 7545    }
 7546
 7547    pub fn delete_to_next_word_end(
 7548        &mut self,
 7549        action: &DeleteToNextWordEnd,
 7550        cx: &mut ViewContext<Self>,
 7551    ) {
 7552        self.transact(cx, |this, cx| {
 7553            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7554                let line_mode = s.line_mode;
 7555                s.move_with(|map, selection| {
 7556                    if selection.is_empty() && !line_mode {
 7557                        let cursor = if action.ignore_newlines {
 7558                            movement::next_word_end(map, selection.head())
 7559                        } else {
 7560                            movement::next_word_end_or_newline(map, selection.head())
 7561                        };
 7562                        selection.set_head(cursor, SelectionGoal::None);
 7563                    }
 7564                });
 7565            });
 7566            this.insert("", cx);
 7567        });
 7568    }
 7569
 7570    pub fn delete_to_next_subword_end(
 7571        &mut self,
 7572        _: &DeleteToNextSubwordEnd,
 7573        cx: &mut ViewContext<Self>,
 7574    ) {
 7575        self.transact(cx, |this, cx| {
 7576            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7577                s.move_with(|map, selection| {
 7578                    if selection.is_empty() {
 7579                        let cursor = movement::next_subword_end(map, selection.head());
 7580                        selection.set_head(cursor, SelectionGoal::None);
 7581                    }
 7582                });
 7583            });
 7584            this.insert("", cx);
 7585        });
 7586    }
 7587
 7588    pub fn move_to_beginning_of_line(
 7589        &mut self,
 7590        action: &MoveToBeginningOfLine,
 7591        cx: &mut ViewContext<Self>,
 7592    ) {
 7593        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7594            s.move_cursors_with(|map, head, _| {
 7595                (
 7596                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7597                    SelectionGoal::None,
 7598                )
 7599            });
 7600        })
 7601    }
 7602
 7603    pub fn select_to_beginning_of_line(
 7604        &mut self,
 7605        action: &SelectToBeginningOfLine,
 7606        cx: &mut ViewContext<Self>,
 7607    ) {
 7608        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7609            s.move_heads_with(|map, head, _| {
 7610                (
 7611                    movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
 7612                    SelectionGoal::None,
 7613                )
 7614            });
 7615        });
 7616    }
 7617
 7618    pub fn delete_to_beginning_of_line(
 7619        &mut self,
 7620        _: &DeleteToBeginningOfLine,
 7621        cx: &mut ViewContext<Self>,
 7622    ) {
 7623        self.transact(cx, |this, cx| {
 7624            this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7625                s.move_with(|_, selection| {
 7626                    selection.reversed = true;
 7627                });
 7628            });
 7629
 7630            this.select_to_beginning_of_line(
 7631                &SelectToBeginningOfLine {
 7632                    stop_at_soft_wraps: false,
 7633                },
 7634                cx,
 7635            );
 7636            this.backspace(&Backspace, cx);
 7637        });
 7638    }
 7639
 7640    pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
 7641        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7642            s.move_cursors_with(|map, head, _| {
 7643                (
 7644                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7645                    SelectionGoal::None,
 7646                )
 7647            });
 7648        })
 7649    }
 7650
 7651    pub fn select_to_end_of_line(
 7652        &mut self,
 7653        action: &SelectToEndOfLine,
 7654        cx: &mut ViewContext<Self>,
 7655    ) {
 7656        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7657            s.move_heads_with(|map, head, _| {
 7658                (
 7659                    movement::line_end(map, head, action.stop_at_soft_wraps),
 7660                    SelectionGoal::None,
 7661                )
 7662            });
 7663        })
 7664    }
 7665
 7666    pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
 7667        self.transact(cx, |this, cx| {
 7668            this.select_to_end_of_line(
 7669                &SelectToEndOfLine {
 7670                    stop_at_soft_wraps: false,
 7671                },
 7672                cx,
 7673            );
 7674            this.delete(&Delete, cx);
 7675        });
 7676    }
 7677
 7678    pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
 7679        self.transact(cx, |this, cx| {
 7680            this.select_to_end_of_line(
 7681                &SelectToEndOfLine {
 7682                    stop_at_soft_wraps: false,
 7683                },
 7684                cx,
 7685            );
 7686            this.cut(&Cut, cx);
 7687        });
 7688    }
 7689
 7690    pub fn move_to_start_of_paragraph(
 7691        &mut self,
 7692        _: &MoveToStartOfParagraph,
 7693        cx: &mut ViewContext<Self>,
 7694    ) {
 7695        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7696            cx.propagate();
 7697            return;
 7698        }
 7699
 7700        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7701            s.move_with(|map, selection| {
 7702                selection.collapse_to(
 7703                    movement::start_of_paragraph(map, selection.head(), 1),
 7704                    SelectionGoal::None,
 7705                )
 7706            });
 7707        })
 7708    }
 7709
 7710    pub fn move_to_end_of_paragraph(
 7711        &mut self,
 7712        _: &MoveToEndOfParagraph,
 7713        cx: &mut ViewContext<Self>,
 7714    ) {
 7715        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7716            cx.propagate();
 7717            return;
 7718        }
 7719
 7720        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7721            s.move_with(|map, selection| {
 7722                selection.collapse_to(
 7723                    movement::end_of_paragraph(map, selection.head(), 1),
 7724                    SelectionGoal::None,
 7725                )
 7726            });
 7727        })
 7728    }
 7729
 7730    pub fn select_to_start_of_paragraph(
 7731        &mut self,
 7732        _: &SelectToStartOfParagraph,
 7733        cx: &mut ViewContext<Self>,
 7734    ) {
 7735        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7736            cx.propagate();
 7737            return;
 7738        }
 7739
 7740        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7741            s.move_heads_with(|map, head, _| {
 7742                (
 7743                    movement::start_of_paragraph(map, head, 1),
 7744                    SelectionGoal::None,
 7745                )
 7746            });
 7747        })
 7748    }
 7749
 7750    pub fn select_to_end_of_paragraph(
 7751        &mut self,
 7752        _: &SelectToEndOfParagraph,
 7753        cx: &mut ViewContext<Self>,
 7754    ) {
 7755        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7756            cx.propagate();
 7757            return;
 7758        }
 7759
 7760        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7761            s.move_heads_with(|map, head, _| {
 7762                (
 7763                    movement::end_of_paragraph(map, head, 1),
 7764                    SelectionGoal::None,
 7765                )
 7766            });
 7767        })
 7768    }
 7769
 7770    pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
 7771        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7772            cx.propagate();
 7773            return;
 7774        }
 7775
 7776        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7777            s.select_ranges(vec![0..0]);
 7778        });
 7779    }
 7780
 7781    pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
 7782        let mut selection = self.selections.last::<Point>(cx);
 7783        selection.set_head(Point::zero(), SelectionGoal::None);
 7784
 7785        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7786            s.select(vec![selection]);
 7787        });
 7788    }
 7789
 7790    pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
 7791        if matches!(self.mode, EditorMode::SingleLine { .. }) {
 7792            cx.propagate();
 7793            return;
 7794        }
 7795
 7796        let cursor = self.buffer.read(cx).read(cx).len();
 7797        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7798            s.select_ranges(vec![cursor..cursor])
 7799        });
 7800    }
 7801
 7802    pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
 7803        self.nav_history = nav_history;
 7804    }
 7805
 7806    pub fn nav_history(&self) -> Option<&ItemNavHistory> {
 7807        self.nav_history.as_ref()
 7808    }
 7809
 7810    fn push_to_nav_history(
 7811        &mut self,
 7812        cursor_anchor: Anchor,
 7813        new_position: Option<Point>,
 7814        cx: &mut ViewContext<Self>,
 7815    ) {
 7816        if let Some(nav_history) = self.nav_history.as_mut() {
 7817            let buffer = self.buffer.read(cx).read(cx);
 7818            let cursor_position = cursor_anchor.to_point(&buffer);
 7819            let scroll_state = self.scroll_manager.anchor();
 7820            let scroll_top_row = scroll_state.top_row(&buffer);
 7821            drop(buffer);
 7822
 7823            if let Some(new_position) = new_position {
 7824                let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
 7825                if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
 7826                    return;
 7827                }
 7828            }
 7829
 7830            nav_history.push(
 7831                Some(NavigationData {
 7832                    cursor_anchor,
 7833                    cursor_position,
 7834                    scroll_anchor: scroll_state,
 7835                    scroll_top_row,
 7836                }),
 7837                cx,
 7838            );
 7839        }
 7840    }
 7841
 7842    pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
 7843        let buffer = self.buffer.read(cx).snapshot(cx);
 7844        let mut selection = self.selections.first::<usize>(cx);
 7845        selection.set_head(buffer.len(), SelectionGoal::None);
 7846        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7847            s.select(vec![selection]);
 7848        });
 7849    }
 7850
 7851    pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
 7852        let end = self.buffer.read(cx).read(cx).len();
 7853        self.change_selections(None, cx, |s| {
 7854            s.select_ranges(vec![0..end]);
 7855        });
 7856    }
 7857
 7858    pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
 7859        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7860        let mut selections = self.selections.all::<Point>(cx);
 7861        let max_point = display_map.buffer_snapshot.max_point();
 7862        for selection in &mut selections {
 7863            let rows = selection.spanned_rows(true, &display_map);
 7864            selection.start = Point::new(rows.start.0, 0);
 7865            selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
 7866            selection.reversed = false;
 7867        }
 7868        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7869            s.select(selections);
 7870        });
 7871    }
 7872
 7873    pub fn split_selection_into_lines(
 7874        &mut self,
 7875        _: &SplitSelectionIntoLines,
 7876        cx: &mut ViewContext<Self>,
 7877    ) {
 7878        let mut to_unfold = Vec::new();
 7879        let mut new_selection_ranges = Vec::new();
 7880        {
 7881            let selections = self.selections.all::<Point>(cx);
 7882            let buffer = self.buffer.read(cx).read(cx);
 7883            for selection in selections {
 7884                for row in selection.start.row..selection.end.row {
 7885                    let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
 7886                    new_selection_ranges.push(cursor..cursor);
 7887                }
 7888                new_selection_ranges.push(selection.end..selection.end);
 7889                to_unfold.push(selection.start..selection.end);
 7890            }
 7891        }
 7892        self.unfold_ranges(&to_unfold, true, true, cx);
 7893        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 7894            s.select_ranges(new_selection_ranges);
 7895        });
 7896    }
 7897
 7898    pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
 7899        self.add_selection(true, cx);
 7900    }
 7901
 7902    pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
 7903        self.add_selection(false, cx);
 7904    }
 7905
 7906    fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
 7907        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 7908        let mut selections = self.selections.all::<Point>(cx);
 7909        let text_layout_details = self.text_layout_details(cx);
 7910        let mut state = self.add_selections_state.take().unwrap_or_else(|| {
 7911            let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
 7912            let range = oldest_selection.display_range(&display_map).sorted();
 7913
 7914            let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
 7915            let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
 7916            let positions = start_x.min(end_x)..start_x.max(end_x);
 7917
 7918            selections.clear();
 7919            let mut stack = Vec::new();
 7920            for row in range.start.row().0..=range.end.row().0 {
 7921                if let Some(selection) = self.selections.build_columnar_selection(
 7922                    &display_map,
 7923                    DisplayRow(row),
 7924                    &positions,
 7925                    oldest_selection.reversed,
 7926                    &text_layout_details,
 7927                ) {
 7928                    stack.push(selection.id);
 7929                    selections.push(selection);
 7930                }
 7931            }
 7932
 7933            if above {
 7934                stack.reverse();
 7935            }
 7936
 7937            AddSelectionsState { above, stack }
 7938        });
 7939
 7940        let last_added_selection = *state.stack.last().unwrap();
 7941        let mut new_selections = Vec::new();
 7942        if above == state.above {
 7943            let end_row = if above {
 7944                DisplayRow(0)
 7945            } else {
 7946                display_map.max_point().row()
 7947            };
 7948
 7949            'outer: for selection in selections {
 7950                if selection.id == last_added_selection {
 7951                    let range = selection.display_range(&display_map).sorted();
 7952                    debug_assert_eq!(range.start.row(), range.end.row());
 7953                    let mut row = range.start.row();
 7954                    let positions =
 7955                        if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
 7956                            px(start)..px(end)
 7957                        } else {
 7958                            let start_x =
 7959                                display_map.x_for_display_point(range.start, &text_layout_details);
 7960                            let end_x =
 7961                                display_map.x_for_display_point(range.end, &text_layout_details);
 7962                            start_x.min(end_x)..start_x.max(end_x)
 7963                        };
 7964
 7965                    while row != end_row {
 7966                        if above {
 7967                            row.0 -= 1;
 7968                        } else {
 7969                            row.0 += 1;
 7970                        }
 7971
 7972                        if let Some(new_selection) = self.selections.build_columnar_selection(
 7973                            &display_map,
 7974                            row,
 7975                            &positions,
 7976                            selection.reversed,
 7977                            &text_layout_details,
 7978                        ) {
 7979                            state.stack.push(new_selection.id);
 7980                            if above {
 7981                                new_selections.push(new_selection);
 7982                                new_selections.push(selection);
 7983                            } else {
 7984                                new_selections.push(selection);
 7985                                new_selections.push(new_selection);
 7986                            }
 7987
 7988                            continue 'outer;
 7989                        }
 7990                    }
 7991                }
 7992
 7993                new_selections.push(selection);
 7994            }
 7995        } else {
 7996            new_selections = selections;
 7997            new_selections.retain(|s| s.id != last_added_selection);
 7998            state.stack.pop();
 7999        }
 8000
 8001        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8002            s.select(new_selections);
 8003        });
 8004        if state.stack.len() > 1 {
 8005            self.add_selections_state = Some(state);
 8006        }
 8007    }
 8008
 8009    pub fn select_next_match_internal(
 8010        &mut self,
 8011        display_map: &DisplaySnapshot,
 8012        replace_newest: bool,
 8013        autoscroll: Option<Autoscroll>,
 8014        cx: &mut ViewContext<Self>,
 8015    ) -> Result<()> {
 8016        fn select_next_match_ranges(
 8017            this: &mut Editor,
 8018            range: Range<usize>,
 8019            replace_newest: bool,
 8020            auto_scroll: Option<Autoscroll>,
 8021            cx: &mut ViewContext<Editor>,
 8022        ) {
 8023            this.unfold_ranges(&[range.clone()], false, true, cx);
 8024            this.change_selections(auto_scroll, cx, |s| {
 8025                if replace_newest {
 8026                    s.delete(s.newest_anchor().id);
 8027                }
 8028                s.insert_range(range.clone());
 8029            });
 8030        }
 8031
 8032        let buffer = &display_map.buffer_snapshot;
 8033        let mut selections = self.selections.all::<usize>(cx);
 8034        if let Some(mut select_next_state) = self.select_next_state.take() {
 8035            let query = &select_next_state.query;
 8036            if !select_next_state.done {
 8037                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8038                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8039                let mut next_selected_range = None;
 8040
 8041                let bytes_after_last_selection =
 8042                    buffer.bytes_in_range(last_selection.end..buffer.len());
 8043                let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
 8044                let query_matches = query
 8045                    .stream_find_iter(bytes_after_last_selection)
 8046                    .map(|result| (last_selection.end, result))
 8047                    .chain(
 8048                        query
 8049                            .stream_find_iter(bytes_before_first_selection)
 8050                            .map(|result| (0, result)),
 8051                    );
 8052
 8053                for (start_offset, query_match) in query_matches {
 8054                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8055                    let offset_range =
 8056                        start_offset + query_match.start()..start_offset + query_match.end();
 8057                    let display_range = offset_range.start.to_display_point(display_map)
 8058                        ..offset_range.end.to_display_point(display_map);
 8059
 8060                    if !select_next_state.wordwise
 8061                        || (!movement::is_inside_word(display_map, display_range.start)
 8062                            && !movement::is_inside_word(display_map, display_range.end))
 8063                    {
 8064                        // TODO: This is n^2, because we might check all the selections
 8065                        if !selections
 8066                            .iter()
 8067                            .any(|selection| selection.range().overlaps(&offset_range))
 8068                        {
 8069                            next_selected_range = Some(offset_range);
 8070                            break;
 8071                        }
 8072                    }
 8073                }
 8074
 8075                if let Some(next_selected_range) = next_selected_range {
 8076                    select_next_match_ranges(
 8077                        self,
 8078                        next_selected_range,
 8079                        replace_newest,
 8080                        autoscroll,
 8081                        cx,
 8082                    );
 8083                } else {
 8084                    select_next_state.done = true;
 8085                }
 8086            }
 8087
 8088            self.select_next_state = Some(select_next_state);
 8089        } else {
 8090            let mut only_carets = true;
 8091            let mut same_text_selected = true;
 8092            let mut selected_text = None;
 8093
 8094            let mut selections_iter = selections.iter().peekable();
 8095            while let Some(selection) = selections_iter.next() {
 8096                if selection.start != selection.end {
 8097                    only_carets = false;
 8098                }
 8099
 8100                if same_text_selected {
 8101                    if selected_text.is_none() {
 8102                        selected_text =
 8103                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8104                    }
 8105
 8106                    if let Some(next_selection) = selections_iter.peek() {
 8107                        if next_selection.range().len() == selection.range().len() {
 8108                            let next_selected_text = buffer
 8109                                .text_for_range(next_selection.range())
 8110                                .collect::<String>();
 8111                            if Some(next_selected_text) != selected_text {
 8112                                same_text_selected = false;
 8113                                selected_text = None;
 8114                            }
 8115                        } else {
 8116                            same_text_selected = false;
 8117                            selected_text = None;
 8118                        }
 8119                    }
 8120                }
 8121            }
 8122
 8123            if only_carets {
 8124                for selection in &mut selections {
 8125                    let word_range = movement::surrounding_word(
 8126                        display_map,
 8127                        selection.start.to_display_point(display_map),
 8128                    );
 8129                    selection.start = word_range.start.to_offset(display_map, Bias::Left);
 8130                    selection.end = word_range.end.to_offset(display_map, Bias::Left);
 8131                    selection.goal = SelectionGoal::None;
 8132                    selection.reversed = false;
 8133                    select_next_match_ranges(
 8134                        self,
 8135                        selection.start..selection.end,
 8136                        replace_newest,
 8137                        autoscroll,
 8138                        cx,
 8139                    );
 8140                }
 8141
 8142                if selections.len() == 1 {
 8143                    let selection = selections
 8144                        .last()
 8145                        .expect("ensured that there's only one selection");
 8146                    let query = buffer
 8147                        .text_for_range(selection.start..selection.end)
 8148                        .collect::<String>();
 8149                    let is_empty = query.is_empty();
 8150                    let select_state = SelectNextState {
 8151                        query: AhoCorasick::new(&[query])?,
 8152                        wordwise: true,
 8153                        done: is_empty,
 8154                    };
 8155                    self.select_next_state = Some(select_state);
 8156                } else {
 8157                    self.select_next_state = None;
 8158                }
 8159            } else if let Some(selected_text) = selected_text {
 8160                self.select_next_state = Some(SelectNextState {
 8161                    query: AhoCorasick::new(&[selected_text])?,
 8162                    wordwise: false,
 8163                    done: false,
 8164                });
 8165                self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
 8166            }
 8167        }
 8168        Ok(())
 8169    }
 8170
 8171    pub fn select_all_matches(
 8172        &mut self,
 8173        _action: &SelectAllMatches,
 8174        cx: &mut ViewContext<Self>,
 8175    ) -> Result<()> {
 8176        self.push_to_selection_history();
 8177        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8178
 8179        self.select_next_match_internal(&display_map, false, None, cx)?;
 8180        let Some(select_next_state) = self.select_next_state.as_mut() else {
 8181            return Ok(());
 8182        };
 8183        if select_next_state.done {
 8184            return Ok(());
 8185        }
 8186
 8187        let mut new_selections = self.selections.all::<usize>(cx);
 8188
 8189        let buffer = &display_map.buffer_snapshot;
 8190        let query_matches = select_next_state
 8191            .query
 8192            .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
 8193
 8194        for query_match in query_matches {
 8195            let query_match = query_match.unwrap(); // can only fail due to I/O
 8196            let offset_range = query_match.start()..query_match.end();
 8197            let display_range = offset_range.start.to_display_point(&display_map)
 8198                ..offset_range.end.to_display_point(&display_map);
 8199
 8200            if !select_next_state.wordwise
 8201                || (!movement::is_inside_word(&display_map, display_range.start)
 8202                    && !movement::is_inside_word(&display_map, display_range.end))
 8203            {
 8204                self.selections.change_with(cx, |selections| {
 8205                    new_selections.push(Selection {
 8206                        id: selections.new_selection_id(),
 8207                        start: offset_range.start,
 8208                        end: offset_range.end,
 8209                        reversed: false,
 8210                        goal: SelectionGoal::None,
 8211                    });
 8212                });
 8213            }
 8214        }
 8215
 8216        new_selections.sort_by_key(|selection| selection.start);
 8217        let mut ix = 0;
 8218        while ix + 1 < new_selections.len() {
 8219            let current_selection = &new_selections[ix];
 8220            let next_selection = &new_selections[ix + 1];
 8221            if current_selection.range().overlaps(&next_selection.range()) {
 8222                if current_selection.id < next_selection.id {
 8223                    new_selections.remove(ix + 1);
 8224                } else {
 8225                    new_selections.remove(ix);
 8226                }
 8227            } else {
 8228                ix += 1;
 8229            }
 8230        }
 8231
 8232        select_next_state.done = true;
 8233        self.unfold_ranges(
 8234            &new_selections
 8235                .iter()
 8236                .map(|selection| selection.range())
 8237                .collect::<Vec<_>>(),
 8238            false,
 8239            false,
 8240            cx,
 8241        );
 8242        self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
 8243            selections.select(new_selections)
 8244        });
 8245
 8246        Ok(())
 8247    }
 8248
 8249    pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
 8250        self.push_to_selection_history();
 8251        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8252        self.select_next_match_internal(
 8253            &display_map,
 8254            action.replace_newest,
 8255            Some(Autoscroll::newest()),
 8256            cx,
 8257        )?;
 8258        Ok(())
 8259    }
 8260
 8261    pub fn select_previous(
 8262        &mut self,
 8263        action: &SelectPrevious,
 8264        cx: &mut ViewContext<Self>,
 8265    ) -> Result<()> {
 8266        self.push_to_selection_history();
 8267        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8268        let buffer = &display_map.buffer_snapshot;
 8269        let mut selections = self.selections.all::<usize>(cx);
 8270        if let Some(mut select_prev_state) = self.select_prev_state.take() {
 8271            let query = &select_prev_state.query;
 8272            if !select_prev_state.done {
 8273                let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
 8274                let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
 8275                let mut next_selected_range = None;
 8276                // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
 8277                let bytes_before_last_selection =
 8278                    buffer.reversed_bytes_in_range(0..last_selection.start);
 8279                let bytes_after_first_selection =
 8280                    buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
 8281                let query_matches = query
 8282                    .stream_find_iter(bytes_before_last_selection)
 8283                    .map(|result| (last_selection.start, result))
 8284                    .chain(
 8285                        query
 8286                            .stream_find_iter(bytes_after_first_selection)
 8287                            .map(|result| (buffer.len(), result)),
 8288                    );
 8289                for (end_offset, query_match) in query_matches {
 8290                    let query_match = query_match.unwrap(); // can only fail due to I/O
 8291                    let offset_range =
 8292                        end_offset - query_match.end()..end_offset - query_match.start();
 8293                    let display_range = offset_range.start.to_display_point(&display_map)
 8294                        ..offset_range.end.to_display_point(&display_map);
 8295
 8296                    if !select_prev_state.wordwise
 8297                        || (!movement::is_inside_word(&display_map, display_range.start)
 8298                            && !movement::is_inside_word(&display_map, display_range.end))
 8299                    {
 8300                        next_selected_range = Some(offset_range);
 8301                        break;
 8302                    }
 8303                }
 8304
 8305                if let Some(next_selected_range) = next_selected_range {
 8306                    self.unfold_ranges(&[next_selected_range.clone()], false, true, cx);
 8307                    self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8308                        if action.replace_newest {
 8309                            s.delete(s.newest_anchor().id);
 8310                        }
 8311                        s.insert_range(next_selected_range);
 8312                    });
 8313                } else {
 8314                    select_prev_state.done = true;
 8315                }
 8316            }
 8317
 8318            self.select_prev_state = Some(select_prev_state);
 8319        } else {
 8320            let mut only_carets = true;
 8321            let mut same_text_selected = true;
 8322            let mut selected_text = None;
 8323
 8324            let mut selections_iter = selections.iter().peekable();
 8325            while let Some(selection) = selections_iter.next() {
 8326                if selection.start != selection.end {
 8327                    only_carets = false;
 8328                }
 8329
 8330                if same_text_selected {
 8331                    if selected_text.is_none() {
 8332                        selected_text =
 8333                            Some(buffer.text_for_range(selection.range()).collect::<String>());
 8334                    }
 8335
 8336                    if let Some(next_selection) = selections_iter.peek() {
 8337                        if next_selection.range().len() == selection.range().len() {
 8338                            let next_selected_text = buffer
 8339                                .text_for_range(next_selection.range())
 8340                                .collect::<String>();
 8341                            if Some(next_selected_text) != selected_text {
 8342                                same_text_selected = false;
 8343                                selected_text = None;
 8344                            }
 8345                        } else {
 8346                            same_text_selected = false;
 8347                            selected_text = None;
 8348                        }
 8349                    }
 8350                }
 8351            }
 8352
 8353            if only_carets {
 8354                for selection in &mut selections {
 8355                    let word_range = movement::surrounding_word(
 8356                        &display_map,
 8357                        selection.start.to_display_point(&display_map),
 8358                    );
 8359                    selection.start = word_range.start.to_offset(&display_map, Bias::Left);
 8360                    selection.end = word_range.end.to_offset(&display_map, Bias::Left);
 8361                    selection.goal = SelectionGoal::None;
 8362                    selection.reversed = false;
 8363                }
 8364                if selections.len() == 1 {
 8365                    let selection = selections
 8366                        .last()
 8367                        .expect("ensured that there's only one selection");
 8368                    let query = buffer
 8369                        .text_for_range(selection.start..selection.end)
 8370                        .collect::<String>();
 8371                    let is_empty = query.is_empty();
 8372                    let select_state = SelectNextState {
 8373                        query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
 8374                        wordwise: true,
 8375                        done: is_empty,
 8376                    };
 8377                    self.select_prev_state = Some(select_state);
 8378                } else {
 8379                    self.select_prev_state = None;
 8380                }
 8381
 8382                self.unfold_ranges(
 8383                    &selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
 8384                    false,
 8385                    true,
 8386                    cx,
 8387                );
 8388                self.change_selections(Some(Autoscroll::newest()), cx, |s| {
 8389                    s.select(selections);
 8390                });
 8391            } else if let Some(selected_text) = selected_text {
 8392                self.select_prev_state = Some(SelectNextState {
 8393                    query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
 8394                    wordwise: false,
 8395                    done: false,
 8396                });
 8397                self.select_previous(action, cx)?;
 8398            }
 8399        }
 8400        Ok(())
 8401    }
 8402
 8403    pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
 8404        if self.read_only(cx) {
 8405            return;
 8406        }
 8407        let text_layout_details = &self.text_layout_details(cx);
 8408        self.transact(cx, |this, cx| {
 8409            let mut selections = this.selections.all::<MultiBufferPoint>(cx);
 8410            let mut edits = Vec::new();
 8411            let mut selection_edit_ranges = Vec::new();
 8412            let mut last_toggled_row = None;
 8413            let snapshot = this.buffer.read(cx).read(cx);
 8414            let empty_str: Arc<str> = Arc::default();
 8415            let mut suffixes_inserted = Vec::new();
 8416            let ignore_indent = action.ignore_indent;
 8417
 8418            fn comment_prefix_range(
 8419                snapshot: &MultiBufferSnapshot,
 8420                row: MultiBufferRow,
 8421                comment_prefix: &str,
 8422                comment_prefix_whitespace: &str,
 8423                ignore_indent: bool,
 8424            ) -> Range<Point> {
 8425                let indent_size = if ignore_indent {
 8426                    0
 8427                } else {
 8428                    snapshot.indent_size_for_line(row).len
 8429                };
 8430
 8431                let start = Point::new(row.0, indent_size);
 8432
 8433                let mut line_bytes = snapshot
 8434                    .bytes_in_range(start..snapshot.max_point())
 8435                    .flatten()
 8436                    .copied();
 8437
 8438                // If this line currently begins with the line comment prefix, then record
 8439                // the range containing the prefix.
 8440                if line_bytes
 8441                    .by_ref()
 8442                    .take(comment_prefix.len())
 8443                    .eq(comment_prefix.bytes())
 8444                {
 8445                    // Include any whitespace that matches the comment prefix.
 8446                    let matching_whitespace_len = line_bytes
 8447                        .zip(comment_prefix_whitespace.bytes())
 8448                        .take_while(|(a, b)| a == b)
 8449                        .count() as u32;
 8450                    let end = Point::new(
 8451                        start.row,
 8452                        start.column + comment_prefix.len() as u32 + matching_whitespace_len,
 8453                    );
 8454                    start..end
 8455                } else {
 8456                    start..start
 8457                }
 8458            }
 8459
 8460            fn comment_suffix_range(
 8461                snapshot: &MultiBufferSnapshot,
 8462                row: MultiBufferRow,
 8463                comment_suffix: &str,
 8464                comment_suffix_has_leading_space: bool,
 8465            ) -> Range<Point> {
 8466                let end = Point::new(row.0, snapshot.line_len(row));
 8467                let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
 8468
 8469                let mut line_end_bytes = snapshot
 8470                    .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
 8471                    .flatten()
 8472                    .copied();
 8473
 8474                let leading_space_len = if suffix_start_column > 0
 8475                    && line_end_bytes.next() == Some(b' ')
 8476                    && comment_suffix_has_leading_space
 8477                {
 8478                    1
 8479                } else {
 8480                    0
 8481                };
 8482
 8483                // If this line currently begins with the line comment prefix, then record
 8484                // the range containing the prefix.
 8485                if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
 8486                    let start = Point::new(end.row, suffix_start_column - leading_space_len);
 8487                    start..end
 8488                } else {
 8489                    end..end
 8490                }
 8491            }
 8492
 8493            // TODO: Handle selections that cross excerpts
 8494            for selection in &mut selections {
 8495                let start_column = snapshot
 8496                    .indent_size_for_line(MultiBufferRow(selection.start.row))
 8497                    .len;
 8498                let language = if let Some(language) =
 8499                    snapshot.language_scope_at(Point::new(selection.start.row, start_column))
 8500                {
 8501                    language
 8502                } else {
 8503                    continue;
 8504                };
 8505
 8506                selection_edit_ranges.clear();
 8507
 8508                // If multiple selections contain a given row, avoid processing that
 8509                // row more than once.
 8510                let mut start_row = MultiBufferRow(selection.start.row);
 8511                if last_toggled_row == Some(start_row) {
 8512                    start_row = start_row.next_row();
 8513                }
 8514                let end_row =
 8515                    if selection.end.row > selection.start.row && selection.end.column == 0 {
 8516                        MultiBufferRow(selection.end.row - 1)
 8517                    } else {
 8518                        MultiBufferRow(selection.end.row)
 8519                    };
 8520                last_toggled_row = Some(end_row);
 8521
 8522                if start_row > end_row {
 8523                    continue;
 8524                }
 8525
 8526                // If the language has line comments, toggle those.
 8527                let mut full_comment_prefixes = language.line_comment_prefixes().to_vec();
 8528
 8529                // If ignore_indent is set, trim spaces from the right side of all full_comment_prefixes
 8530                if ignore_indent {
 8531                    full_comment_prefixes = full_comment_prefixes
 8532                        .into_iter()
 8533                        .map(|s| Arc::from(s.trim_end()))
 8534                        .collect();
 8535                }
 8536
 8537                if !full_comment_prefixes.is_empty() {
 8538                    let first_prefix = full_comment_prefixes
 8539                        .first()
 8540                        .expect("prefixes is non-empty");
 8541                    let prefix_trimmed_lengths = full_comment_prefixes
 8542                        .iter()
 8543                        .map(|p| p.trim_end_matches(' ').len())
 8544                        .collect::<SmallVec<[usize; 4]>>();
 8545
 8546                    let mut all_selection_lines_are_comments = true;
 8547
 8548                    for row in start_row.0..=end_row.0 {
 8549                        let row = MultiBufferRow(row);
 8550                        if start_row < end_row && snapshot.is_line_blank(row) {
 8551                            continue;
 8552                        }
 8553
 8554                        let prefix_range = full_comment_prefixes
 8555                            .iter()
 8556                            .zip(prefix_trimmed_lengths.iter().copied())
 8557                            .map(|(prefix, trimmed_prefix_len)| {
 8558                                comment_prefix_range(
 8559                                    snapshot.deref(),
 8560                                    row,
 8561                                    &prefix[..trimmed_prefix_len],
 8562                                    &prefix[trimmed_prefix_len..],
 8563                                    ignore_indent,
 8564                                )
 8565                            })
 8566                            .max_by_key(|range| range.end.column - range.start.column)
 8567                            .expect("prefixes is non-empty");
 8568
 8569                        if prefix_range.is_empty() {
 8570                            all_selection_lines_are_comments = false;
 8571                        }
 8572
 8573                        selection_edit_ranges.push(prefix_range);
 8574                    }
 8575
 8576                    if all_selection_lines_are_comments {
 8577                        edits.extend(
 8578                            selection_edit_ranges
 8579                                .iter()
 8580                                .cloned()
 8581                                .map(|range| (range, empty_str.clone())),
 8582                        );
 8583                    } else {
 8584                        let min_column = selection_edit_ranges
 8585                            .iter()
 8586                            .map(|range| range.start.column)
 8587                            .min()
 8588                            .unwrap_or(0);
 8589                        edits.extend(selection_edit_ranges.iter().map(|range| {
 8590                            let position = Point::new(range.start.row, min_column);
 8591                            (position..position, first_prefix.clone())
 8592                        }));
 8593                    }
 8594                } else if let Some((full_comment_prefix, comment_suffix)) =
 8595                    language.block_comment_delimiters()
 8596                {
 8597                    let comment_prefix = full_comment_prefix.trim_end_matches(' ');
 8598                    let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
 8599                    let prefix_range = comment_prefix_range(
 8600                        snapshot.deref(),
 8601                        start_row,
 8602                        comment_prefix,
 8603                        comment_prefix_whitespace,
 8604                        ignore_indent,
 8605                    );
 8606                    let suffix_range = comment_suffix_range(
 8607                        snapshot.deref(),
 8608                        end_row,
 8609                        comment_suffix.trim_start_matches(' '),
 8610                        comment_suffix.starts_with(' '),
 8611                    );
 8612
 8613                    if prefix_range.is_empty() || suffix_range.is_empty() {
 8614                        edits.push((
 8615                            prefix_range.start..prefix_range.start,
 8616                            full_comment_prefix.clone(),
 8617                        ));
 8618                        edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
 8619                        suffixes_inserted.push((end_row, comment_suffix.len()));
 8620                    } else {
 8621                        edits.push((prefix_range, empty_str.clone()));
 8622                        edits.push((suffix_range, empty_str.clone()));
 8623                    }
 8624                } else {
 8625                    continue;
 8626                }
 8627            }
 8628
 8629            drop(snapshot);
 8630            this.buffer.update(cx, |buffer, cx| {
 8631                buffer.edit(edits, None, cx);
 8632            });
 8633
 8634            // Adjust selections so that they end before any comment suffixes that
 8635            // were inserted.
 8636            let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
 8637            let mut selections = this.selections.all::<Point>(cx);
 8638            let snapshot = this.buffer.read(cx).read(cx);
 8639            for selection in &mut selections {
 8640                while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
 8641                    match row.cmp(&MultiBufferRow(selection.end.row)) {
 8642                        Ordering::Less => {
 8643                            suffixes_inserted.next();
 8644                            continue;
 8645                        }
 8646                        Ordering::Greater => break,
 8647                        Ordering::Equal => {
 8648                            if selection.end.column == snapshot.line_len(row) {
 8649                                if selection.is_empty() {
 8650                                    selection.start.column -= suffix_len as u32;
 8651                                }
 8652                                selection.end.column -= suffix_len as u32;
 8653                            }
 8654                            break;
 8655                        }
 8656                    }
 8657                }
 8658            }
 8659
 8660            drop(snapshot);
 8661            this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
 8662
 8663            let selections = this.selections.all::<Point>(cx);
 8664            let selections_on_single_row = selections.windows(2).all(|selections| {
 8665                selections[0].start.row == selections[1].start.row
 8666                    && selections[0].end.row == selections[1].end.row
 8667                    && selections[0].start.row == selections[0].end.row
 8668            });
 8669            let selections_selecting = selections
 8670                .iter()
 8671                .any(|selection| selection.start != selection.end);
 8672            let advance_downwards = action.advance_downwards
 8673                && selections_on_single_row
 8674                && !selections_selecting
 8675                && !matches!(this.mode, EditorMode::SingleLine { .. });
 8676
 8677            if advance_downwards {
 8678                let snapshot = this.buffer.read(cx).snapshot(cx);
 8679
 8680                this.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8681                    s.move_cursors_with(|display_snapshot, display_point, _| {
 8682                        let mut point = display_point.to_point(display_snapshot);
 8683                        point.row += 1;
 8684                        point = snapshot.clip_point(point, Bias::Left);
 8685                        let display_point = point.to_display_point(display_snapshot);
 8686                        let goal = SelectionGoal::HorizontalPosition(
 8687                            display_snapshot
 8688                                .x_for_display_point(display_point, text_layout_details)
 8689                                .into(),
 8690                        );
 8691                        (display_point, goal)
 8692                    })
 8693                });
 8694            }
 8695        });
 8696    }
 8697
 8698    pub fn select_enclosing_symbol(
 8699        &mut self,
 8700        _: &SelectEnclosingSymbol,
 8701        cx: &mut ViewContext<Self>,
 8702    ) {
 8703        let buffer = self.buffer.read(cx).snapshot(cx);
 8704        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8705
 8706        fn update_selection(
 8707            selection: &Selection<usize>,
 8708            buffer_snap: &MultiBufferSnapshot,
 8709        ) -> Option<Selection<usize>> {
 8710            let cursor = selection.head();
 8711            let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
 8712            for symbol in symbols.iter().rev() {
 8713                let start = symbol.range.start.to_offset(buffer_snap);
 8714                let end = symbol.range.end.to_offset(buffer_snap);
 8715                let new_range = start..end;
 8716                if start < selection.start || end > selection.end {
 8717                    return Some(Selection {
 8718                        id: selection.id,
 8719                        start: new_range.start,
 8720                        end: new_range.end,
 8721                        goal: SelectionGoal::None,
 8722                        reversed: selection.reversed,
 8723                    });
 8724                }
 8725            }
 8726            None
 8727        }
 8728
 8729        let mut selected_larger_symbol = false;
 8730        let new_selections = old_selections
 8731            .iter()
 8732            .map(|selection| match update_selection(selection, &buffer) {
 8733                Some(new_selection) => {
 8734                    if new_selection.range() != selection.range() {
 8735                        selected_larger_symbol = true;
 8736                    }
 8737                    new_selection
 8738                }
 8739                None => selection.clone(),
 8740            })
 8741            .collect::<Vec<_>>();
 8742
 8743        if selected_larger_symbol {
 8744            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8745                s.select(new_selections);
 8746            });
 8747        }
 8748    }
 8749
 8750    pub fn select_larger_syntax_node(
 8751        &mut self,
 8752        _: &SelectLargerSyntaxNode,
 8753        cx: &mut ViewContext<Self>,
 8754    ) {
 8755        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
 8756        let buffer = self.buffer.read(cx).snapshot(cx);
 8757        let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
 8758
 8759        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8760        let mut selected_larger_node = false;
 8761        let new_selections = old_selections
 8762            .iter()
 8763            .map(|selection| {
 8764                let old_range = selection.start..selection.end;
 8765                let mut new_range = old_range.clone();
 8766                while let Some(containing_range) =
 8767                    buffer.range_for_syntax_ancestor(new_range.clone())
 8768                {
 8769                    new_range = containing_range;
 8770                    if !display_map.intersects_fold(new_range.start)
 8771                        && !display_map.intersects_fold(new_range.end)
 8772                    {
 8773                        break;
 8774                    }
 8775                }
 8776
 8777                selected_larger_node |= new_range != old_range;
 8778                Selection {
 8779                    id: selection.id,
 8780                    start: new_range.start,
 8781                    end: new_range.end,
 8782                    goal: SelectionGoal::None,
 8783                    reversed: selection.reversed,
 8784                }
 8785            })
 8786            .collect::<Vec<_>>();
 8787
 8788        if selected_larger_node {
 8789            stack.push(old_selections);
 8790            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8791                s.select(new_selections);
 8792            });
 8793        }
 8794        self.select_larger_syntax_node_stack = stack;
 8795    }
 8796
 8797    pub fn select_smaller_syntax_node(
 8798        &mut self,
 8799        _: &SelectSmallerSyntaxNode,
 8800        cx: &mut ViewContext<Self>,
 8801    ) {
 8802        let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
 8803        if let Some(selections) = stack.pop() {
 8804            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8805                s.select(selections.to_vec());
 8806            });
 8807        }
 8808        self.select_larger_syntax_node_stack = stack;
 8809    }
 8810
 8811    fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
 8812        if !EditorSettings::get_global(cx).gutter.runnables {
 8813            self.clear_tasks();
 8814            return Task::ready(());
 8815        }
 8816        let project = self.project.as_ref().map(Model::downgrade);
 8817        cx.spawn(|this, mut cx| async move {
 8818            cx.background_executor().timer(UPDATE_DEBOUNCE).await;
 8819            let Some(project) = project.and_then(|p| p.upgrade()) else {
 8820                return;
 8821            };
 8822            let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
 8823                this.display_map.update(cx, |map, cx| map.snapshot(cx))
 8824            }) else {
 8825                return;
 8826            };
 8827
 8828            let hide_runnables = project
 8829                .update(&mut cx, |project, cx| {
 8830                    // Do not display any test indicators in non-dev server remote projects.
 8831                    project.is_via_collab() && project.ssh_connection_string(cx).is_none()
 8832                })
 8833                .unwrap_or(true);
 8834            if hide_runnables {
 8835                return;
 8836            }
 8837            let new_rows =
 8838                cx.background_executor()
 8839                    .spawn({
 8840                        let snapshot = display_snapshot.clone();
 8841                        async move {
 8842                            Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
 8843                        }
 8844                    })
 8845                    .await;
 8846            let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
 8847
 8848            this.update(&mut cx, |this, _| {
 8849                this.clear_tasks();
 8850                for (key, value) in rows {
 8851                    this.insert_tasks(key, value);
 8852                }
 8853            })
 8854            .ok();
 8855        })
 8856    }
 8857    fn fetch_runnable_ranges(
 8858        snapshot: &DisplaySnapshot,
 8859        range: Range<Anchor>,
 8860    ) -> Vec<language::RunnableRange> {
 8861        snapshot.buffer_snapshot.runnable_ranges(range).collect()
 8862    }
 8863
 8864    fn runnable_rows(
 8865        project: Model<Project>,
 8866        snapshot: DisplaySnapshot,
 8867        runnable_ranges: Vec<RunnableRange>,
 8868        mut cx: AsyncWindowContext,
 8869    ) -> Vec<((BufferId, u32), RunnableTasks)> {
 8870        runnable_ranges
 8871            .into_iter()
 8872            .filter_map(|mut runnable| {
 8873                let tasks = cx
 8874                    .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
 8875                    .ok()?;
 8876                if tasks.is_empty() {
 8877                    return None;
 8878                }
 8879
 8880                let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
 8881
 8882                let row = snapshot
 8883                    .buffer_snapshot
 8884                    .buffer_line_for_row(MultiBufferRow(point.row))?
 8885                    .1
 8886                    .start
 8887                    .row;
 8888
 8889                let context_range =
 8890                    BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
 8891                Some((
 8892                    (runnable.buffer_id, row),
 8893                    RunnableTasks {
 8894                        templates: tasks,
 8895                        offset: MultiBufferOffset(runnable.run_range.start),
 8896                        context_range,
 8897                        column: point.column,
 8898                        extra_variables: runnable.extra_captures,
 8899                    },
 8900                ))
 8901            })
 8902            .collect()
 8903    }
 8904
 8905    fn templates_with_tags(
 8906        project: &Model<Project>,
 8907        runnable: &mut Runnable,
 8908        cx: &WindowContext<'_>,
 8909    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 8910        let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
 8911            let (worktree_id, file) = project
 8912                .buffer_for_id(runnable.buffer, cx)
 8913                .and_then(|buffer| buffer.read(cx).file())
 8914                .map(|file| (file.worktree_id(cx), file.clone()))
 8915                .unzip();
 8916
 8917            (
 8918                project.task_store().read(cx).task_inventory().cloned(),
 8919                worktree_id,
 8920                file,
 8921            )
 8922        });
 8923
 8924        let tags = mem::take(&mut runnable.tags);
 8925        let mut tags: Vec<_> = tags
 8926            .into_iter()
 8927            .flat_map(|tag| {
 8928                let tag = tag.0.clone();
 8929                inventory
 8930                    .as_ref()
 8931                    .into_iter()
 8932                    .flat_map(|inventory| {
 8933                        inventory.read(cx).list_tasks(
 8934                            file.clone(),
 8935                            Some(runnable.language.clone()),
 8936                            worktree_id,
 8937                            cx,
 8938                        )
 8939                    })
 8940                    .filter(move |(_, template)| {
 8941                        template.tags.iter().any(|source_tag| source_tag == &tag)
 8942                    })
 8943            })
 8944            .sorted_by_key(|(kind, _)| kind.to_owned())
 8945            .collect();
 8946        if let Some((leading_tag_source, _)) = tags.first() {
 8947            // Strongest source wins; if we have worktree tag binding, prefer that to
 8948            // global and language bindings;
 8949            // if we have a global binding, prefer that to language binding.
 8950            let first_mismatch = tags
 8951                .iter()
 8952                .position(|(tag_source, _)| tag_source != leading_tag_source);
 8953            if let Some(index) = first_mismatch {
 8954                tags.truncate(index);
 8955            }
 8956        }
 8957
 8958        tags
 8959    }
 8960
 8961    pub fn move_to_enclosing_bracket(
 8962        &mut self,
 8963        _: &MoveToEnclosingBracket,
 8964        cx: &mut ViewContext<Self>,
 8965    ) {
 8966        self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 8967            s.move_offsets_with(|snapshot, selection| {
 8968                let Some(enclosing_bracket_ranges) =
 8969                    snapshot.enclosing_bracket_ranges(selection.start..selection.end)
 8970                else {
 8971                    return;
 8972                };
 8973
 8974                let mut best_length = usize::MAX;
 8975                let mut best_inside = false;
 8976                let mut best_in_bracket_range = false;
 8977                let mut best_destination = None;
 8978                for (open, close) in enclosing_bracket_ranges {
 8979                    let close = close.to_inclusive();
 8980                    let length = close.end() - open.start;
 8981                    let inside = selection.start >= open.end && selection.end <= *close.start();
 8982                    let in_bracket_range = open.to_inclusive().contains(&selection.head())
 8983                        || close.contains(&selection.head());
 8984
 8985                    // If best is next to a bracket and current isn't, skip
 8986                    if !in_bracket_range && best_in_bracket_range {
 8987                        continue;
 8988                    }
 8989
 8990                    // Prefer smaller lengths unless best is inside and current isn't
 8991                    if length > best_length && (best_inside || !inside) {
 8992                        continue;
 8993                    }
 8994
 8995                    best_length = length;
 8996                    best_inside = inside;
 8997                    best_in_bracket_range = in_bracket_range;
 8998                    best_destination = Some(
 8999                        if close.contains(&selection.start) && close.contains(&selection.end) {
 9000                            if inside {
 9001                                open.end
 9002                            } else {
 9003                                open.start
 9004                            }
 9005                        } else if inside {
 9006                            *close.start()
 9007                        } else {
 9008                            *close.end()
 9009                        },
 9010                    );
 9011                }
 9012
 9013                if let Some(destination) = best_destination {
 9014                    selection.collapse_to(destination, SelectionGoal::None);
 9015                }
 9016            })
 9017        });
 9018    }
 9019
 9020    pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
 9021        self.end_selection(cx);
 9022        self.selection_history.mode = SelectionHistoryMode::Undoing;
 9023        if let Some(entry) = self.selection_history.undo_stack.pop_back() {
 9024            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9025            self.select_next_state = entry.select_next_state;
 9026            self.select_prev_state = entry.select_prev_state;
 9027            self.add_selections_state = entry.add_selections_state;
 9028            self.request_autoscroll(Autoscroll::newest(), cx);
 9029        }
 9030        self.selection_history.mode = SelectionHistoryMode::Normal;
 9031    }
 9032
 9033    pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
 9034        self.end_selection(cx);
 9035        self.selection_history.mode = SelectionHistoryMode::Redoing;
 9036        if let Some(entry) = self.selection_history.redo_stack.pop_back() {
 9037            self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
 9038            self.select_next_state = entry.select_next_state;
 9039            self.select_prev_state = entry.select_prev_state;
 9040            self.add_selections_state = entry.add_selections_state;
 9041            self.request_autoscroll(Autoscroll::newest(), cx);
 9042        }
 9043        self.selection_history.mode = SelectionHistoryMode::Normal;
 9044    }
 9045
 9046    pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
 9047        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
 9048    }
 9049
 9050    pub fn expand_excerpts_down(
 9051        &mut self,
 9052        action: &ExpandExcerptsDown,
 9053        cx: &mut ViewContext<Self>,
 9054    ) {
 9055        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
 9056    }
 9057
 9058    pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
 9059        self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
 9060    }
 9061
 9062    pub fn expand_excerpts_for_direction(
 9063        &mut self,
 9064        lines: u32,
 9065        direction: ExpandExcerptDirection,
 9066        cx: &mut ViewContext<Self>,
 9067    ) {
 9068        let selections = self.selections.disjoint_anchors();
 9069
 9070        let lines = if lines == 0 {
 9071            EditorSettings::get_global(cx).expand_excerpt_lines
 9072        } else {
 9073            lines
 9074        };
 9075
 9076        self.buffer.update(cx, |buffer, cx| {
 9077            buffer.expand_excerpts(
 9078                selections
 9079                    .iter()
 9080                    .map(|selection| selection.head().excerpt_id)
 9081                    .dedup(),
 9082                lines,
 9083                direction,
 9084                cx,
 9085            )
 9086        })
 9087    }
 9088
 9089    pub fn expand_excerpt(
 9090        &mut self,
 9091        excerpt: ExcerptId,
 9092        direction: ExpandExcerptDirection,
 9093        cx: &mut ViewContext<Self>,
 9094    ) {
 9095        let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
 9096        self.buffer.update(cx, |buffer, cx| {
 9097            buffer.expand_excerpts([excerpt], lines, direction, cx)
 9098        })
 9099    }
 9100
 9101    fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
 9102        self.go_to_diagnostic_impl(Direction::Next, cx)
 9103    }
 9104
 9105    fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
 9106        self.go_to_diagnostic_impl(Direction::Prev, cx)
 9107    }
 9108
 9109    pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
 9110        let buffer = self.buffer.read(cx).snapshot(cx);
 9111        let selection = self.selections.newest::<usize>(cx);
 9112
 9113        // If there is an active Diagnostic Popover jump to its diagnostic instead.
 9114        if direction == Direction::Next {
 9115            if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
 9116                let (group_id, jump_to) = popover.activation_info();
 9117                if self.activate_diagnostics(group_id, cx) {
 9118                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9119                        let mut new_selection = s.newest_anchor().clone();
 9120                        new_selection.collapse_to(jump_to, SelectionGoal::None);
 9121                        s.select_anchors(vec![new_selection.clone()]);
 9122                    });
 9123                }
 9124                return;
 9125            }
 9126        }
 9127
 9128        let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
 9129            active_diagnostics
 9130                .primary_range
 9131                .to_offset(&buffer)
 9132                .to_inclusive()
 9133        });
 9134        let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
 9135            if active_primary_range.contains(&selection.head()) {
 9136                *active_primary_range.start()
 9137            } else {
 9138                selection.head()
 9139            }
 9140        } else {
 9141            selection.head()
 9142        };
 9143        let snapshot = self.snapshot(cx);
 9144        loop {
 9145            let diagnostics = if direction == Direction::Prev {
 9146                buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
 9147            } else {
 9148                buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
 9149            }
 9150            .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
 9151            let group = diagnostics
 9152                // relies on diagnostics_in_range to return diagnostics with the same starting range to
 9153                // be sorted in a stable way
 9154                // skip until we are at current active diagnostic, if it exists
 9155                .skip_while(|entry| {
 9156                    (match direction {
 9157                        Direction::Prev => entry.range.start >= search_start,
 9158                        Direction::Next => entry.range.start <= search_start,
 9159                    }) && self
 9160                        .active_diagnostics
 9161                        .as_ref()
 9162                        .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
 9163                })
 9164                .find_map(|entry| {
 9165                    if entry.diagnostic.is_primary
 9166                        && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
 9167                        && !entry.range.is_empty()
 9168                        // if we match with the active diagnostic, skip it
 9169                        && Some(entry.diagnostic.group_id)
 9170                            != self.active_diagnostics.as_ref().map(|d| d.group_id)
 9171                    {
 9172                        Some((entry.range, entry.diagnostic.group_id))
 9173                    } else {
 9174                        None
 9175                    }
 9176                });
 9177
 9178            if let Some((primary_range, group_id)) = group {
 9179                if self.activate_diagnostics(group_id, cx) {
 9180                    self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9181                        s.select(vec![Selection {
 9182                            id: selection.id,
 9183                            start: primary_range.start,
 9184                            end: primary_range.start,
 9185                            reversed: false,
 9186                            goal: SelectionGoal::None,
 9187                        }]);
 9188                    });
 9189                }
 9190                break;
 9191            } else {
 9192                // Cycle around to the start of the buffer, potentially moving back to the start of
 9193                // the currently active diagnostic.
 9194                active_primary_range.take();
 9195                if direction == Direction::Prev {
 9196                    if search_start == buffer.len() {
 9197                        break;
 9198                    } else {
 9199                        search_start = buffer.len();
 9200                    }
 9201                } else if search_start == 0 {
 9202                    break;
 9203                } else {
 9204                    search_start = 0;
 9205                }
 9206            }
 9207        }
 9208    }
 9209
 9210    fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
 9211        let snapshot = self.snapshot(cx);
 9212        let selection = self.selections.newest::<Point>(cx);
 9213        self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
 9214    }
 9215
 9216    fn go_to_hunk_after_position(
 9217        &mut self,
 9218        snapshot: &EditorSnapshot,
 9219        position: Point,
 9220        cx: &mut ViewContext<'_, Editor>,
 9221    ) -> Option<MultiBufferDiffHunk> {
 9222        for (ix, position) in [position, Point::zero()].into_iter().enumerate() {
 9223            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9224                snapshot,
 9225                position,
 9226                ix > 0,
 9227                snapshot.diff_map.diff_hunks_in_range(
 9228                    position + Point::new(1, 0)..snapshot.buffer_snapshot.max_point(),
 9229                    &snapshot.buffer_snapshot,
 9230                ),
 9231                cx,
 9232            ) {
 9233                return Some(hunk);
 9234            }
 9235        }
 9236        None
 9237    }
 9238
 9239    fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
 9240        let snapshot = self.snapshot(cx);
 9241        let selection = self.selections.newest::<Point>(cx);
 9242        self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
 9243    }
 9244
 9245    fn go_to_hunk_before_position(
 9246        &mut self,
 9247        snapshot: &EditorSnapshot,
 9248        position: Point,
 9249        cx: &mut ViewContext<'_, Editor>,
 9250    ) -> Option<MultiBufferDiffHunk> {
 9251        for (ix, position) in [position, snapshot.buffer_snapshot.max_point()]
 9252            .into_iter()
 9253            .enumerate()
 9254        {
 9255            if let Some(hunk) = self.go_to_next_hunk_in_direction(
 9256                snapshot,
 9257                position,
 9258                ix > 0,
 9259                snapshot
 9260                    .diff_map
 9261                    .diff_hunks_in_range_rev(Point::zero()..position, &snapshot.buffer_snapshot),
 9262                cx,
 9263            ) {
 9264                return Some(hunk);
 9265            }
 9266        }
 9267        None
 9268    }
 9269
 9270    fn go_to_next_hunk_in_direction(
 9271        &mut self,
 9272        snapshot: &DisplaySnapshot,
 9273        initial_point: Point,
 9274        is_wrapped: bool,
 9275        hunks: impl Iterator<Item = MultiBufferDiffHunk>,
 9276        cx: &mut ViewContext<Editor>,
 9277    ) -> Option<MultiBufferDiffHunk> {
 9278        let display_point = initial_point.to_display_point(snapshot);
 9279        let mut hunks = hunks
 9280            .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
 9281            .filter(|(display_hunk, _)| {
 9282                is_wrapped || !display_hunk.contains_display_row(display_point.row())
 9283            })
 9284            .dedup();
 9285
 9286        if let Some((display_hunk, hunk)) = hunks.next() {
 9287            self.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9288                let row = display_hunk.start_display_row();
 9289                let point = DisplayPoint::new(row, 0);
 9290                s.select_display_ranges([point..point]);
 9291            });
 9292
 9293            Some(hunk)
 9294        } else {
 9295            None
 9296        }
 9297    }
 9298
 9299    pub fn go_to_definition(
 9300        &mut self,
 9301        _: &GoToDefinition,
 9302        cx: &mut ViewContext<Self>,
 9303    ) -> Task<Result<Navigated>> {
 9304        let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
 9305        cx.spawn(|editor, mut cx| async move {
 9306            if definition.await? == Navigated::Yes {
 9307                return Ok(Navigated::Yes);
 9308            }
 9309            match editor.update(&mut cx, |editor, cx| {
 9310                editor.find_all_references(&FindAllReferences, cx)
 9311            })? {
 9312                Some(references) => references.await,
 9313                None => Ok(Navigated::No),
 9314            }
 9315        })
 9316    }
 9317
 9318    pub fn go_to_declaration(
 9319        &mut self,
 9320        _: &GoToDeclaration,
 9321        cx: &mut ViewContext<Self>,
 9322    ) -> Task<Result<Navigated>> {
 9323        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
 9324    }
 9325
 9326    pub fn go_to_declaration_split(
 9327        &mut self,
 9328        _: &GoToDeclaration,
 9329        cx: &mut ViewContext<Self>,
 9330    ) -> Task<Result<Navigated>> {
 9331        self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
 9332    }
 9333
 9334    pub fn go_to_implementation(
 9335        &mut self,
 9336        _: &GoToImplementation,
 9337        cx: &mut ViewContext<Self>,
 9338    ) -> Task<Result<Navigated>> {
 9339        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
 9340    }
 9341
 9342    pub fn go_to_implementation_split(
 9343        &mut self,
 9344        _: &GoToImplementationSplit,
 9345        cx: &mut ViewContext<Self>,
 9346    ) -> Task<Result<Navigated>> {
 9347        self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
 9348    }
 9349
 9350    pub fn go_to_type_definition(
 9351        &mut self,
 9352        _: &GoToTypeDefinition,
 9353        cx: &mut ViewContext<Self>,
 9354    ) -> Task<Result<Navigated>> {
 9355        self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
 9356    }
 9357
 9358    pub fn go_to_definition_split(
 9359        &mut self,
 9360        _: &GoToDefinitionSplit,
 9361        cx: &mut ViewContext<Self>,
 9362    ) -> Task<Result<Navigated>> {
 9363        self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
 9364    }
 9365
 9366    pub fn go_to_type_definition_split(
 9367        &mut self,
 9368        _: &GoToTypeDefinitionSplit,
 9369        cx: &mut ViewContext<Self>,
 9370    ) -> Task<Result<Navigated>> {
 9371        self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
 9372    }
 9373
 9374    fn go_to_definition_of_kind(
 9375        &mut self,
 9376        kind: GotoDefinitionKind,
 9377        split: bool,
 9378        cx: &mut ViewContext<Self>,
 9379    ) -> Task<Result<Navigated>> {
 9380        let Some(provider) = self.semantics_provider.clone() else {
 9381            return Task::ready(Ok(Navigated::No));
 9382        };
 9383        let head = self.selections.newest::<usize>(cx).head();
 9384        let buffer = self.buffer.read(cx);
 9385        let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
 9386            text_anchor
 9387        } else {
 9388            return Task::ready(Ok(Navigated::No));
 9389        };
 9390
 9391        let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
 9392            return Task::ready(Ok(Navigated::No));
 9393        };
 9394
 9395        cx.spawn(|editor, mut cx| async move {
 9396            let definitions = definitions.await?;
 9397            let navigated = editor
 9398                .update(&mut cx, |editor, cx| {
 9399                    editor.navigate_to_hover_links(
 9400                        Some(kind),
 9401                        definitions
 9402                            .into_iter()
 9403                            .filter(|location| {
 9404                                hover_links::exclude_link_to_position(&buffer, &head, location, cx)
 9405                            })
 9406                            .map(HoverLink::Text)
 9407                            .collect::<Vec<_>>(),
 9408                        split,
 9409                        cx,
 9410                    )
 9411                })?
 9412                .await?;
 9413            anyhow::Ok(navigated)
 9414        })
 9415    }
 9416
 9417    pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
 9418        let selection = self.selections.newest_anchor();
 9419        let head = selection.head();
 9420        let tail = selection.tail();
 9421
 9422        let Some((buffer, start_position)) =
 9423            self.buffer.read(cx).text_anchor_for_position(head, cx)
 9424        else {
 9425            return;
 9426        };
 9427
 9428        let end_position = if head != tail {
 9429            let Some((_, pos)) = self.buffer.read(cx).text_anchor_for_position(tail, cx) else {
 9430                return;
 9431            };
 9432            Some(pos)
 9433        } else {
 9434            None
 9435        };
 9436
 9437        let url_finder = cx.spawn(|editor, mut cx| async move {
 9438            let url = if let Some(end_pos) = end_position {
 9439                find_url_from_range(&buffer, start_position..end_pos, cx.clone())
 9440            } else {
 9441                find_url(&buffer, start_position, cx.clone()).map(|(_, url)| url)
 9442            };
 9443
 9444            if let Some(url) = url {
 9445                editor.update(&mut cx, |_, cx| {
 9446                    cx.open_url(&url);
 9447                })
 9448            } else {
 9449                Ok(())
 9450            }
 9451        });
 9452
 9453        url_finder.detach();
 9454    }
 9455
 9456    pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
 9457        let Some(workspace) = self.workspace() else {
 9458            return;
 9459        };
 9460
 9461        let position = self.selections.newest_anchor().head();
 9462
 9463        let Some((buffer, buffer_position)) =
 9464            self.buffer.read(cx).text_anchor_for_position(position, cx)
 9465        else {
 9466            return;
 9467        };
 9468
 9469        let project = self.project.clone();
 9470
 9471        cx.spawn(|_, mut cx| async move {
 9472            let result = find_file(&buffer, project, buffer_position, &mut cx).await;
 9473
 9474            if let Some((_, path)) = result {
 9475                workspace
 9476                    .update(&mut cx, |workspace, cx| {
 9477                        workspace.open_resolved_path(path, cx)
 9478                    })?
 9479                    .await?;
 9480            }
 9481            anyhow::Ok(())
 9482        })
 9483        .detach();
 9484    }
 9485
 9486    pub(crate) fn navigate_to_hover_links(
 9487        &mut self,
 9488        kind: Option<GotoDefinitionKind>,
 9489        mut definitions: Vec<HoverLink>,
 9490        split: bool,
 9491        cx: &mut ViewContext<Editor>,
 9492    ) -> Task<Result<Navigated>> {
 9493        // If there is one definition, just open it directly
 9494        if definitions.len() == 1 {
 9495            let definition = definitions.pop().unwrap();
 9496
 9497            enum TargetTaskResult {
 9498                Location(Option<Location>),
 9499                AlreadyNavigated,
 9500            }
 9501
 9502            let target_task = match definition {
 9503                HoverLink::Text(link) => {
 9504                    Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
 9505                }
 9506                HoverLink::InlayHint(lsp_location, server_id) => {
 9507                    let computation = self.compute_target_location(lsp_location, server_id, cx);
 9508                    cx.background_executor().spawn(async move {
 9509                        let location = computation.await?;
 9510                        Ok(TargetTaskResult::Location(location))
 9511                    })
 9512                }
 9513                HoverLink::Url(url) => {
 9514                    cx.open_url(&url);
 9515                    Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
 9516                }
 9517                HoverLink::File(path) => {
 9518                    if let Some(workspace) = self.workspace() {
 9519                        cx.spawn(|_, mut cx| async move {
 9520                            workspace
 9521                                .update(&mut cx, |workspace, cx| {
 9522                                    workspace.open_resolved_path(path, cx)
 9523                                })?
 9524                                .await
 9525                                .map(|_| TargetTaskResult::AlreadyNavigated)
 9526                        })
 9527                    } else {
 9528                        Task::ready(Ok(TargetTaskResult::Location(None)))
 9529                    }
 9530                }
 9531            };
 9532            cx.spawn(|editor, mut cx| async move {
 9533                let target = match target_task.await.context("target resolution task")? {
 9534                    TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
 9535                    TargetTaskResult::Location(None) => return Ok(Navigated::No),
 9536                    TargetTaskResult::Location(Some(target)) => target,
 9537                };
 9538
 9539                editor.update(&mut cx, |editor, cx| {
 9540                    let Some(workspace) = editor.workspace() else {
 9541                        return Navigated::No;
 9542                    };
 9543                    let pane = workspace.read(cx).active_pane().clone();
 9544
 9545                    let range = target.range.to_offset(target.buffer.read(cx));
 9546                    let range = editor.range_for_match(&range);
 9547
 9548                    if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
 9549                        let buffer = target.buffer.read(cx);
 9550                        let range = check_multiline_range(buffer, range);
 9551                        editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9552                            s.select_ranges([range]);
 9553                        });
 9554                    } else {
 9555                        cx.window_context().defer(move |cx| {
 9556                            let target_editor: View<Self> =
 9557                                workspace.update(cx, |workspace, cx| {
 9558                                    let pane = if split {
 9559                                        workspace.adjacent_pane(cx)
 9560                                    } else {
 9561                                        workspace.active_pane().clone()
 9562                                    };
 9563
 9564                                    workspace.open_project_item(
 9565                                        pane,
 9566                                        target.buffer.clone(),
 9567                                        true,
 9568                                        true,
 9569                                        cx,
 9570                                    )
 9571                                });
 9572                            target_editor.update(cx, |target_editor, cx| {
 9573                                // When selecting a definition in a different buffer, disable the nav history
 9574                                // to avoid creating a history entry at the previous cursor location.
 9575                                pane.update(cx, |pane, _| pane.disable_history());
 9576                                let buffer = target.buffer.read(cx);
 9577                                let range = check_multiline_range(buffer, range);
 9578                                target_editor.change_selections(
 9579                                    Some(Autoscroll::focused()),
 9580                                    cx,
 9581                                    |s| {
 9582                                        s.select_ranges([range]);
 9583                                    },
 9584                                );
 9585                                pane.update(cx, |pane, _| pane.enable_history());
 9586                            });
 9587                        });
 9588                    }
 9589                    Navigated::Yes
 9590                })
 9591            })
 9592        } else if !definitions.is_empty() {
 9593            cx.spawn(|editor, mut cx| async move {
 9594                let (title, location_tasks, workspace) = editor
 9595                    .update(&mut cx, |editor, cx| {
 9596                        let tab_kind = match kind {
 9597                            Some(GotoDefinitionKind::Implementation) => "Implementations",
 9598                            _ => "Definitions",
 9599                        };
 9600                        let title = definitions
 9601                            .iter()
 9602                            .find_map(|definition| match definition {
 9603                                HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
 9604                                    let buffer = origin.buffer.read(cx);
 9605                                    format!(
 9606                                        "{} for {}",
 9607                                        tab_kind,
 9608                                        buffer
 9609                                            .text_for_range(origin.range.clone())
 9610                                            .collect::<String>()
 9611                                    )
 9612                                }),
 9613                                HoverLink::InlayHint(_, _) => None,
 9614                                HoverLink::Url(_) => None,
 9615                                HoverLink::File(_) => None,
 9616                            })
 9617                            .unwrap_or(tab_kind.to_string());
 9618                        let location_tasks = definitions
 9619                            .into_iter()
 9620                            .map(|definition| match definition {
 9621                                HoverLink::Text(link) => Task::ready(Ok(Some(link.target))),
 9622                                HoverLink::InlayHint(lsp_location, server_id) => {
 9623                                    editor.compute_target_location(lsp_location, server_id, cx)
 9624                                }
 9625                                HoverLink::Url(_) => Task::ready(Ok(None)),
 9626                                HoverLink::File(_) => Task::ready(Ok(None)),
 9627                            })
 9628                            .collect::<Vec<_>>();
 9629                        (title, location_tasks, editor.workspace().clone())
 9630                    })
 9631                    .context("location tasks preparation")?;
 9632
 9633                let locations = future::join_all(location_tasks)
 9634                    .await
 9635                    .into_iter()
 9636                    .filter_map(|location| location.transpose())
 9637                    .collect::<Result<_>>()
 9638                    .context("location tasks")?;
 9639
 9640                let Some(workspace) = workspace else {
 9641                    return Ok(Navigated::No);
 9642                };
 9643                let opened = workspace
 9644                    .update(&mut cx, |workspace, cx| {
 9645                        Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
 9646                    })
 9647                    .ok();
 9648
 9649                anyhow::Ok(Navigated::from_bool(opened.is_some()))
 9650            })
 9651        } else {
 9652            Task::ready(Ok(Navigated::No))
 9653        }
 9654    }
 9655
 9656    fn compute_target_location(
 9657        &self,
 9658        lsp_location: lsp::Location,
 9659        server_id: LanguageServerId,
 9660        cx: &mut ViewContext<Self>,
 9661    ) -> Task<anyhow::Result<Option<Location>>> {
 9662        let Some(project) = self.project.clone() else {
 9663            return Task::ready(Ok(None));
 9664        };
 9665
 9666        cx.spawn(move |editor, mut cx| async move {
 9667            let location_task = editor.update(&mut cx, |_, cx| {
 9668                project.update(cx, |project, cx| {
 9669                    let language_server_name = project
 9670                        .language_server_statuses(cx)
 9671                        .find(|(id, _)| server_id == *id)
 9672                        .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
 9673                    language_server_name.map(|language_server_name| {
 9674                        project.open_local_buffer_via_lsp(
 9675                            lsp_location.uri.clone(),
 9676                            server_id,
 9677                            language_server_name,
 9678                            cx,
 9679                        )
 9680                    })
 9681                })
 9682            })?;
 9683            let location = match location_task {
 9684                Some(task) => Some({
 9685                    let target_buffer_handle = task.await.context("open local buffer")?;
 9686                    let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
 9687                        let target_start = target_buffer
 9688                            .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
 9689                        let target_end = target_buffer
 9690                            .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
 9691                        target_buffer.anchor_after(target_start)
 9692                            ..target_buffer.anchor_before(target_end)
 9693                    })?;
 9694                    Location {
 9695                        buffer: target_buffer_handle,
 9696                        range,
 9697                    }
 9698                }),
 9699                None => None,
 9700            };
 9701            Ok(location)
 9702        })
 9703    }
 9704
 9705    pub fn find_all_references(
 9706        &mut self,
 9707        _: &FindAllReferences,
 9708        cx: &mut ViewContext<Self>,
 9709    ) -> Option<Task<Result<Navigated>>> {
 9710        let selection = self.selections.newest::<usize>(cx);
 9711        let multi_buffer = self.buffer.read(cx);
 9712        let head = selection.head();
 9713
 9714        let multi_buffer_snapshot = multi_buffer.snapshot(cx);
 9715        let head_anchor = multi_buffer_snapshot.anchor_at(
 9716            head,
 9717            if head < selection.tail() {
 9718                Bias::Right
 9719            } else {
 9720                Bias::Left
 9721            },
 9722        );
 9723
 9724        match self
 9725            .find_all_references_task_sources
 9726            .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
 9727        {
 9728            Ok(_) => {
 9729                log::info!(
 9730                    "Ignoring repeated FindAllReferences invocation with the position of already running task"
 9731                );
 9732                return None;
 9733            }
 9734            Err(i) => {
 9735                self.find_all_references_task_sources.insert(i, head_anchor);
 9736            }
 9737        }
 9738
 9739        let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
 9740        let workspace = self.workspace()?;
 9741        let project = workspace.read(cx).project().clone();
 9742        let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
 9743        Some(cx.spawn(|editor, mut cx| async move {
 9744            let _cleanup = defer({
 9745                let mut cx = cx.clone();
 9746                move || {
 9747                    let _ = editor.update(&mut cx, |editor, _| {
 9748                        if let Ok(i) =
 9749                            editor
 9750                                .find_all_references_task_sources
 9751                                .binary_search_by(|anchor| {
 9752                                    anchor.cmp(&head_anchor, &multi_buffer_snapshot)
 9753                                })
 9754                        {
 9755                            editor.find_all_references_task_sources.remove(i);
 9756                        }
 9757                    });
 9758                }
 9759            });
 9760
 9761            let locations = references.await?;
 9762            if locations.is_empty() {
 9763                return anyhow::Ok(Navigated::No);
 9764            }
 9765
 9766            workspace.update(&mut cx, |workspace, cx| {
 9767                let title = locations
 9768                    .first()
 9769                    .as_ref()
 9770                    .map(|location| {
 9771                        let buffer = location.buffer.read(cx);
 9772                        format!(
 9773                            "References to `{}`",
 9774                            buffer
 9775                                .text_for_range(location.range.clone())
 9776                                .collect::<String>()
 9777                        )
 9778                    })
 9779                    .unwrap();
 9780                Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
 9781                Navigated::Yes
 9782            })
 9783        }))
 9784    }
 9785
 9786    /// Opens a multibuffer with the given project locations in it
 9787    pub fn open_locations_in_multibuffer(
 9788        workspace: &mut Workspace,
 9789        mut locations: Vec<Location>,
 9790        title: String,
 9791        split: bool,
 9792        cx: &mut ViewContext<Workspace>,
 9793    ) {
 9794        // If there are multiple definitions, open them in a multibuffer
 9795        locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
 9796        let mut locations = locations.into_iter().peekable();
 9797        let mut ranges_to_highlight = Vec::new();
 9798        let capability = workspace.project().read(cx).capability();
 9799
 9800        let excerpt_buffer = cx.new_model(|cx| {
 9801            let mut multibuffer = MultiBuffer::new(capability);
 9802            while let Some(location) = locations.next() {
 9803                let buffer = location.buffer.read(cx);
 9804                let mut ranges_for_buffer = Vec::new();
 9805                let range = location.range.to_offset(buffer);
 9806                ranges_for_buffer.push(range.clone());
 9807
 9808                while let Some(next_location) = locations.peek() {
 9809                    if next_location.buffer == location.buffer {
 9810                        ranges_for_buffer.push(next_location.range.to_offset(buffer));
 9811                        locations.next();
 9812                    } else {
 9813                        break;
 9814                    }
 9815                }
 9816
 9817                ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
 9818                ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
 9819                    location.buffer.clone(),
 9820                    ranges_for_buffer,
 9821                    DEFAULT_MULTIBUFFER_CONTEXT,
 9822                    cx,
 9823                ))
 9824            }
 9825
 9826            multibuffer.with_title(title)
 9827        });
 9828
 9829        let editor = cx.new_view(|cx| {
 9830            Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
 9831        });
 9832        editor.update(cx, |editor, cx| {
 9833            if let Some(first_range) = ranges_to_highlight.first() {
 9834                editor.change_selections(None, cx, |selections| {
 9835                    selections.clear_disjoint();
 9836                    selections.select_anchor_ranges(std::iter::once(first_range.clone()));
 9837                });
 9838            }
 9839            editor.highlight_background::<Self>(
 9840                &ranges_to_highlight,
 9841                |theme| theme.editor_highlighted_line_background,
 9842                cx,
 9843            );
 9844            editor.register_buffers_with_language_servers(cx);
 9845        });
 9846
 9847        let item = Box::new(editor);
 9848        let item_id = item.item_id();
 9849
 9850        if split {
 9851            workspace.split_item(SplitDirection::Right, item.clone(), cx);
 9852        } else {
 9853            let destination_index = workspace.active_pane().update(cx, |pane, cx| {
 9854                if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
 9855                    pane.close_current_preview_item(cx)
 9856                } else {
 9857                    None
 9858                }
 9859            });
 9860            workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
 9861        }
 9862        workspace.active_pane().update(cx, |pane, cx| {
 9863            pane.set_preview_item_id(Some(item_id), cx);
 9864        });
 9865    }
 9866
 9867    pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
 9868        use language::ToOffset as _;
 9869
 9870        let provider = self.semantics_provider.clone()?;
 9871        let selection = self.selections.newest_anchor().clone();
 9872        let (cursor_buffer, cursor_buffer_position) = self
 9873            .buffer
 9874            .read(cx)
 9875            .text_anchor_for_position(selection.head(), cx)?;
 9876        let (tail_buffer, cursor_buffer_position_end) = self
 9877            .buffer
 9878            .read(cx)
 9879            .text_anchor_for_position(selection.tail(), cx)?;
 9880        if tail_buffer != cursor_buffer {
 9881            return None;
 9882        }
 9883
 9884        let snapshot = cursor_buffer.read(cx).snapshot();
 9885        let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
 9886        let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
 9887        let prepare_rename = provider
 9888            .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
 9889            .unwrap_or_else(|| Task::ready(Ok(None)));
 9890        drop(snapshot);
 9891
 9892        Some(cx.spawn(|this, mut cx| async move {
 9893            let rename_range = if let Some(range) = prepare_rename.await? {
 9894                Some(range)
 9895            } else {
 9896                this.update(&mut cx, |this, cx| {
 9897                    let buffer = this.buffer.read(cx).snapshot(cx);
 9898                    let mut buffer_highlights = this
 9899                        .document_highlights_for_position(selection.head(), &buffer)
 9900                        .filter(|highlight| {
 9901                            highlight.start.excerpt_id == selection.head().excerpt_id
 9902                                && highlight.end.excerpt_id == selection.head().excerpt_id
 9903                        });
 9904                    buffer_highlights
 9905                        .next()
 9906                        .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
 9907                })?
 9908            };
 9909            if let Some(rename_range) = rename_range {
 9910                this.update(&mut cx, |this, cx| {
 9911                    let snapshot = cursor_buffer.read(cx).snapshot();
 9912                    let rename_buffer_range = rename_range.to_offset(&snapshot);
 9913                    let cursor_offset_in_rename_range =
 9914                        cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
 9915                    let cursor_offset_in_rename_range_end =
 9916                        cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
 9917
 9918                    this.take_rename(false, cx);
 9919                    let buffer = this.buffer.read(cx).read(cx);
 9920                    let cursor_offset = selection.head().to_offset(&buffer);
 9921                    let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
 9922                    let rename_end = rename_start + rename_buffer_range.len();
 9923                    let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
 9924                    let mut old_highlight_id = None;
 9925                    let old_name: Arc<str> = buffer
 9926                        .chunks(rename_start..rename_end, true)
 9927                        .map(|chunk| {
 9928                            if old_highlight_id.is_none() {
 9929                                old_highlight_id = chunk.syntax_highlight_id;
 9930                            }
 9931                            chunk.text
 9932                        })
 9933                        .collect::<String>()
 9934                        .into();
 9935
 9936                    drop(buffer);
 9937
 9938                    // Position the selection in the rename editor so that it matches the current selection.
 9939                    this.show_local_selections = false;
 9940                    let rename_editor = cx.new_view(|cx| {
 9941                        let mut editor = Editor::single_line(cx);
 9942                        editor.buffer.update(cx, |buffer, cx| {
 9943                            buffer.edit([(0..0, old_name.clone())], None, cx)
 9944                        });
 9945                        let rename_selection_range = match cursor_offset_in_rename_range
 9946                            .cmp(&cursor_offset_in_rename_range_end)
 9947                        {
 9948                            Ordering::Equal => {
 9949                                editor.select_all(&SelectAll, cx);
 9950                                return editor;
 9951                            }
 9952                            Ordering::Less => {
 9953                                cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
 9954                            }
 9955                            Ordering::Greater => {
 9956                                cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
 9957                            }
 9958                        };
 9959                        if rename_selection_range.end > old_name.len() {
 9960                            editor.select_all(&SelectAll, cx);
 9961                        } else {
 9962                            editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
 9963                                s.select_ranges([rename_selection_range]);
 9964                            });
 9965                        }
 9966                        editor
 9967                    });
 9968                    cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
 9969                        if e == &EditorEvent::Focused {
 9970                            cx.emit(EditorEvent::FocusedIn)
 9971                        }
 9972                    })
 9973                    .detach();
 9974
 9975                    let write_highlights =
 9976                        this.clear_background_highlights::<DocumentHighlightWrite>(cx);
 9977                    let read_highlights =
 9978                        this.clear_background_highlights::<DocumentHighlightRead>(cx);
 9979                    let ranges = write_highlights
 9980                        .iter()
 9981                        .flat_map(|(_, ranges)| ranges.iter())
 9982                        .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
 9983                        .cloned()
 9984                        .collect();
 9985
 9986                    this.highlight_text::<Rename>(
 9987                        ranges,
 9988                        HighlightStyle {
 9989                            fade_out: Some(0.6),
 9990                            ..Default::default()
 9991                        },
 9992                        cx,
 9993                    );
 9994                    let rename_focus_handle = rename_editor.focus_handle(cx);
 9995                    cx.focus(&rename_focus_handle);
 9996                    let block_id = this.insert_blocks(
 9997                        [BlockProperties {
 9998                            style: BlockStyle::Flex,
 9999                            placement: BlockPlacement::Below(range.start),
10000                            height: 1,
10001                            render: Arc::new({
10002                                let rename_editor = rename_editor.clone();
10003                                move |cx: &mut BlockContext| {
10004                                    let mut text_style = cx.editor_style.text.clone();
10005                                    if let Some(highlight_style) = old_highlight_id
10006                                        .and_then(|h| h.style(&cx.editor_style.syntax))
10007                                    {
10008                                        text_style = text_style.highlight(highlight_style);
10009                                    }
10010                                    div()
10011                                        .block_mouse_down()
10012                                        .pl(cx.anchor_x)
10013                                        .child(EditorElement::new(
10014                                            &rename_editor,
10015                                            EditorStyle {
10016                                                background: cx.theme().system().transparent,
10017                                                local_player: cx.editor_style.local_player,
10018                                                text: text_style,
10019                                                scrollbar_width: cx.editor_style.scrollbar_width,
10020                                                syntax: cx.editor_style.syntax.clone(),
10021                                                status: cx.editor_style.status.clone(),
10022                                                inlay_hints_style: HighlightStyle {
10023                                                    font_weight: Some(FontWeight::BOLD),
10024                                                    ..make_inlay_hints_style(cx)
10025                                                },
10026                                                inline_completion_styles: make_suggestion_styles(
10027                                                    cx,
10028                                                ),
10029                                                ..EditorStyle::default()
10030                                            },
10031                                        ))
10032                                        .into_any_element()
10033                                }
10034                            }),
10035                            priority: 0,
10036                        }],
10037                        Some(Autoscroll::fit()),
10038                        cx,
10039                    )[0];
10040                    this.pending_rename = Some(RenameState {
10041                        range,
10042                        old_name,
10043                        editor: rename_editor,
10044                        block_id,
10045                    });
10046                })?;
10047            }
10048
10049            Ok(())
10050        }))
10051    }
10052
10053    pub fn confirm_rename(
10054        &mut self,
10055        _: &ConfirmRename,
10056        cx: &mut ViewContext<Self>,
10057    ) -> Option<Task<Result<()>>> {
10058        let rename = self.take_rename(false, cx)?;
10059        let workspace = self.workspace()?.downgrade();
10060        let (buffer, start) = self
10061            .buffer
10062            .read(cx)
10063            .text_anchor_for_position(rename.range.start, cx)?;
10064        let (end_buffer, _) = self
10065            .buffer
10066            .read(cx)
10067            .text_anchor_for_position(rename.range.end, cx)?;
10068        if buffer != end_buffer {
10069            return None;
10070        }
10071
10072        let old_name = rename.old_name;
10073        let new_name = rename.editor.read(cx).text(cx);
10074
10075        let rename = self.semantics_provider.as_ref()?.perform_rename(
10076            &buffer,
10077            start,
10078            new_name.clone(),
10079            cx,
10080        )?;
10081
10082        Some(cx.spawn(|editor, mut cx| async move {
10083            let project_transaction = rename.await?;
10084            Self::open_project_transaction(
10085                &editor,
10086                workspace,
10087                project_transaction,
10088                format!("Rename: {}{}", old_name, new_name),
10089                cx.clone(),
10090            )
10091            .await?;
10092
10093            editor.update(&mut cx, |editor, cx| {
10094                editor.refresh_document_highlights(cx);
10095            })?;
10096            Ok(())
10097        }))
10098    }
10099
10100    fn take_rename(
10101        &mut self,
10102        moving_cursor: bool,
10103        cx: &mut ViewContext<Self>,
10104    ) -> Option<RenameState> {
10105        let rename = self.pending_rename.take()?;
10106        if rename.editor.focus_handle(cx).is_focused(cx) {
10107            cx.focus(&self.focus_handle);
10108        }
10109
10110        self.remove_blocks(
10111            [rename.block_id].into_iter().collect(),
10112            Some(Autoscroll::fit()),
10113            cx,
10114        );
10115        self.clear_highlights::<Rename>(cx);
10116        self.show_local_selections = true;
10117
10118        if moving_cursor {
10119            let cursor_in_rename_editor = rename.editor.update(cx, |editor, cx| {
10120                editor.selections.newest::<usize>(cx).head()
10121            });
10122
10123            // Update the selection to match the position of the selection inside
10124            // the rename editor.
10125            let snapshot = self.buffer.read(cx).read(cx);
10126            let rename_range = rename.range.to_offset(&snapshot);
10127            let cursor_in_editor = snapshot
10128                .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10129                .min(rename_range.end);
10130            drop(snapshot);
10131
10132            self.change_selections(None, cx, |s| {
10133                s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10134            });
10135        } else {
10136            self.refresh_document_highlights(cx);
10137        }
10138
10139        Some(rename)
10140    }
10141
10142    pub fn pending_rename(&self) -> Option<&RenameState> {
10143        self.pending_rename.as_ref()
10144    }
10145
10146    fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10147        let project = match &self.project {
10148            Some(project) => project.clone(),
10149            None => return None,
10150        };
10151
10152        Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10153    }
10154
10155    fn format_selections(
10156        &mut self,
10157        _: &FormatSelections,
10158        cx: &mut ViewContext<Self>,
10159    ) -> Option<Task<Result<()>>> {
10160        let project = match &self.project {
10161            Some(project) => project.clone(),
10162            None => return None,
10163        };
10164
10165        let selections = self
10166            .selections
10167            .all_adjusted(cx)
10168            .into_iter()
10169            .filter(|s| !s.is_empty())
10170            .collect_vec();
10171
10172        Some(self.perform_format(
10173            project,
10174            FormatTrigger::Manual,
10175            FormatTarget::Ranges(selections),
10176            cx,
10177        ))
10178    }
10179
10180    fn perform_format(
10181        &mut self,
10182        project: Model<Project>,
10183        trigger: FormatTrigger,
10184        target: FormatTarget,
10185        cx: &mut ViewContext<Self>,
10186    ) -> Task<Result<()>> {
10187        let buffer = self.buffer().clone();
10188        let mut buffers = buffer.read(cx).all_buffers();
10189        if trigger == FormatTrigger::Save {
10190            buffers.retain(|buffer| buffer.read(cx).is_dirty());
10191        }
10192
10193        let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10194        let format = project.update(cx, |project, cx| {
10195            project.format(buffers, true, trigger, target, cx)
10196        });
10197
10198        cx.spawn(|_, mut cx| async move {
10199            let transaction = futures::select_biased! {
10200                () = timeout => {
10201                    log::warn!("timed out waiting for formatting");
10202                    None
10203                }
10204                transaction = format.log_err().fuse() => transaction,
10205            };
10206
10207            buffer
10208                .update(&mut cx, |buffer, cx| {
10209                    if let Some(transaction) = transaction {
10210                        if !buffer.is_singleton() {
10211                            buffer.push_transaction(&transaction.0, cx);
10212                        }
10213                    }
10214
10215                    cx.notify();
10216                })
10217                .ok();
10218
10219            Ok(())
10220        })
10221    }
10222
10223    fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10224        if let Some(project) = self.project.clone() {
10225            self.buffer.update(cx, |multi_buffer, cx| {
10226                project.update(cx, |project, cx| {
10227                    project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10228                });
10229            })
10230        }
10231    }
10232
10233    fn cancel_language_server_work(
10234        &mut self,
10235        _: &actions::CancelLanguageServerWork,
10236        cx: &mut ViewContext<Self>,
10237    ) {
10238        if let Some(project) = self.project.clone() {
10239            self.buffer.update(cx, |multi_buffer, cx| {
10240                project.update(cx, |project, cx| {
10241                    project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10242                });
10243            })
10244        }
10245    }
10246
10247    fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10248        cx.show_character_palette();
10249    }
10250
10251    fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10252        if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10253            let buffer = self.buffer.read(cx).snapshot(cx);
10254            let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10255            let is_valid = buffer
10256                .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10257                .any(|entry| {
10258                    entry.diagnostic.is_primary
10259                        && !entry.range.is_empty()
10260                        && entry.range.start == primary_range_start
10261                        && entry.diagnostic.message == active_diagnostics.primary_message
10262                });
10263
10264            if is_valid != active_diagnostics.is_valid {
10265                active_diagnostics.is_valid = is_valid;
10266                let mut new_styles = HashMap::default();
10267                for (block_id, diagnostic) in &active_diagnostics.blocks {
10268                    new_styles.insert(
10269                        *block_id,
10270                        diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10271                    );
10272                }
10273                self.display_map.update(cx, |display_map, _cx| {
10274                    display_map.replace_blocks(new_styles)
10275                });
10276            }
10277        }
10278    }
10279
10280    fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10281        self.dismiss_diagnostics(cx);
10282        let snapshot = self.snapshot(cx);
10283        self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10284            let buffer = self.buffer.read(cx).snapshot(cx);
10285
10286            let mut primary_range = None;
10287            let mut primary_message = None;
10288            let mut group_end = Point::zero();
10289            let diagnostic_group = buffer
10290                .diagnostic_group::<MultiBufferPoint>(group_id)
10291                .filter_map(|entry| {
10292                    if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10293                        && (entry.range.start.row == entry.range.end.row
10294                            || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10295                    {
10296                        return None;
10297                    }
10298                    if entry.range.end > group_end {
10299                        group_end = entry.range.end;
10300                    }
10301                    if entry.diagnostic.is_primary {
10302                        primary_range = Some(entry.range.clone());
10303                        primary_message = Some(entry.diagnostic.message.clone());
10304                    }
10305                    Some(entry)
10306                })
10307                .collect::<Vec<_>>();
10308            let primary_range = primary_range?;
10309            let primary_message = primary_message?;
10310            let primary_range =
10311                buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10312
10313            let blocks = display_map
10314                .insert_blocks(
10315                    diagnostic_group.iter().map(|entry| {
10316                        let diagnostic = entry.diagnostic.clone();
10317                        let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10318                        BlockProperties {
10319                            style: BlockStyle::Fixed,
10320                            placement: BlockPlacement::Below(
10321                                buffer.anchor_after(entry.range.start),
10322                            ),
10323                            height: message_height,
10324                            render: diagnostic_block_renderer(diagnostic, None, true, true),
10325                            priority: 0,
10326                        }
10327                    }),
10328                    cx,
10329                )
10330                .into_iter()
10331                .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10332                .collect();
10333
10334            Some(ActiveDiagnosticGroup {
10335                primary_range,
10336                primary_message,
10337                group_id,
10338                blocks,
10339                is_valid: true,
10340            })
10341        });
10342        self.active_diagnostics.is_some()
10343    }
10344
10345    fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10346        if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10347            self.display_map.update(cx, |display_map, cx| {
10348                display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10349            });
10350            cx.notify();
10351        }
10352    }
10353
10354    pub fn set_selections_from_remote(
10355        &mut self,
10356        selections: Vec<Selection<Anchor>>,
10357        pending_selection: Option<Selection<Anchor>>,
10358        cx: &mut ViewContext<Self>,
10359    ) {
10360        let old_cursor_position = self.selections.newest_anchor().head();
10361        self.selections.change_with(cx, |s| {
10362            s.select_anchors(selections);
10363            if let Some(pending_selection) = pending_selection {
10364                s.set_pending(pending_selection, SelectMode::Character);
10365            } else {
10366                s.clear_pending();
10367            }
10368        });
10369        self.selections_did_change(false, &old_cursor_position, true, cx);
10370    }
10371
10372    fn push_to_selection_history(&mut self) {
10373        self.selection_history.push(SelectionHistoryEntry {
10374            selections: self.selections.disjoint_anchors(),
10375            select_next_state: self.select_next_state.clone(),
10376            select_prev_state: self.select_prev_state.clone(),
10377            add_selections_state: self.add_selections_state.clone(),
10378        });
10379    }
10380
10381    pub fn transact(
10382        &mut self,
10383        cx: &mut ViewContext<Self>,
10384        update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10385    ) -> Option<TransactionId> {
10386        self.start_transaction_at(Instant::now(), cx);
10387        update(self, cx);
10388        self.end_transaction_at(Instant::now(), cx)
10389    }
10390
10391    fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10392        self.end_selection(cx);
10393        if let Some(tx_id) = self
10394            .buffer
10395            .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10396        {
10397            self.selection_history
10398                .insert_transaction(tx_id, self.selections.disjoint_anchors());
10399            cx.emit(EditorEvent::TransactionBegun {
10400                transaction_id: tx_id,
10401            })
10402        }
10403    }
10404
10405    fn end_transaction_at(
10406        &mut self,
10407        now: Instant,
10408        cx: &mut ViewContext<Self>,
10409    ) -> Option<TransactionId> {
10410        if let Some(transaction_id) = self
10411            .buffer
10412            .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10413        {
10414            if let Some((_, end_selections)) =
10415                self.selection_history.transaction_mut(transaction_id)
10416            {
10417                *end_selections = Some(self.selections.disjoint_anchors());
10418            } else {
10419                log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10420            }
10421
10422            cx.emit(EditorEvent::Edited { transaction_id });
10423            Some(transaction_id)
10424        } else {
10425            None
10426        }
10427    }
10428
10429    pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10430        if self.is_singleton(cx) {
10431            let selection = self.selections.newest::<Point>(cx);
10432
10433            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10434            let range = if selection.is_empty() {
10435                let point = selection.head().to_display_point(&display_map);
10436                let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10437                let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10438                    .to_point(&display_map);
10439                start..end
10440            } else {
10441                selection.range()
10442            };
10443            if display_map.folds_in_range(range).next().is_some() {
10444                self.unfold_lines(&Default::default(), cx)
10445            } else {
10446                self.fold(&Default::default(), cx)
10447            }
10448        } else {
10449            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10450            let mut toggled_buffers = HashSet::default();
10451            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10452                self.selections
10453                    .disjoint_anchors()
10454                    .into_iter()
10455                    .map(|selection| selection.range()),
10456            ) {
10457                let buffer_id = buffer_snapshot.remote_id();
10458                if toggled_buffers.insert(buffer_id) {
10459                    if self.buffer_folded(buffer_id, cx) {
10460                        self.unfold_buffer(buffer_id, cx);
10461                    } else {
10462                        self.fold_buffer(buffer_id, cx);
10463                    }
10464                }
10465            }
10466        }
10467    }
10468
10469    pub fn toggle_fold_recursive(
10470        &mut self,
10471        _: &actions::ToggleFoldRecursive,
10472        cx: &mut ViewContext<Self>,
10473    ) {
10474        let selection = self.selections.newest::<Point>(cx);
10475
10476        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10477        let range = if selection.is_empty() {
10478            let point = selection.head().to_display_point(&display_map);
10479            let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10480            let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10481                .to_point(&display_map);
10482            start..end
10483        } else {
10484            selection.range()
10485        };
10486        if display_map.folds_in_range(range).next().is_some() {
10487            self.unfold_recursive(&Default::default(), cx)
10488        } else {
10489            self.fold_recursive(&Default::default(), cx)
10490        }
10491    }
10492
10493    pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10494        if self.is_singleton(cx) {
10495            let mut to_fold = Vec::new();
10496            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10497            let selections = self.selections.all_adjusted(cx);
10498
10499            for selection in selections {
10500                let range = selection.range().sorted();
10501                let buffer_start_row = range.start.row;
10502
10503                if range.start.row != range.end.row {
10504                    let mut found = false;
10505                    let mut row = range.start.row;
10506                    while row <= range.end.row {
10507                        if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row))
10508                        {
10509                            found = true;
10510                            row = crease.range().end.row + 1;
10511                            to_fold.push(crease);
10512                        } else {
10513                            row += 1
10514                        }
10515                    }
10516                    if found {
10517                        continue;
10518                    }
10519                }
10520
10521                for row in (0..=range.start.row).rev() {
10522                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10523                        if crease.range().end.row >= buffer_start_row {
10524                            to_fold.push(crease);
10525                            if row <= range.start.row {
10526                                break;
10527                            }
10528                        }
10529                    }
10530                }
10531            }
10532
10533            self.fold_creases(to_fold, true, cx);
10534        } else {
10535            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10536            let mut folded_buffers = HashSet::default();
10537            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10538                self.selections
10539                    .disjoint_anchors()
10540                    .into_iter()
10541                    .map(|selection| selection.range()),
10542            ) {
10543                let buffer_id = buffer_snapshot.remote_id();
10544                if folded_buffers.insert(buffer_id) {
10545                    self.fold_buffer(buffer_id, cx);
10546                }
10547            }
10548        }
10549    }
10550
10551    fn fold_at_level(&mut self, fold_at: &FoldAtLevel, cx: &mut ViewContext<Self>) {
10552        if !self.buffer.read(cx).is_singleton() {
10553            return;
10554        }
10555
10556        let fold_at_level = fold_at.level;
10557        let snapshot = self.buffer.read(cx).snapshot(cx);
10558        let mut to_fold = Vec::new();
10559        let mut stack = vec![(0, snapshot.max_row().0, 1)];
10560
10561        while let Some((mut start_row, end_row, current_level)) = stack.pop() {
10562            while start_row < end_row {
10563                match self
10564                    .snapshot(cx)
10565                    .crease_for_buffer_row(MultiBufferRow(start_row))
10566                {
10567                    Some(crease) => {
10568                        let nested_start_row = crease.range().start.row + 1;
10569                        let nested_end_row = crease.range().end.row;
10570
10571                        if current_level < fold_at_level {
10572                            stack.push((nested_start_row, nested_end_row, current_level + 1));
10573                        } else if current_level == fold_at_level {
10574                            to_fold.push(crease);
10575                        }
10576
10577                        start_row = nested_end_row + 1;
10578                    }
10579                    None => start_row += 1,
10580                }
10581            }
10582        }
10583
10584        self.fold_creases(to_fold, true, cx);
10585    }
10586
10587    pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10588        if self.buffer.read(cx).is_singleton() {
10589            let mut fold_ranges = Vec::new();
10590            let snapshot = self.buffer.read(cx).snapshot(cx);
10591
10592            for row in 0..snapshot.max_row().0 {
10593                if let Some(foldable_range) =
10594                    self.snapshot(cx).crease_for_buffer_row(MultiBufferRow(row))
10595                {
10596                    fold_ranges.push(foldable_range);
10597                }
10598            }
10599
10600            self.fold_creases(fold_ranges, true, cx);
10601        } else {
10602            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10603                editor
10604                    .update(&mut cx, |editor, cx| {
10605                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10606                            editor.fold_buffer(buffer_id, cx);
10607                        }
10608                    })
10609                    .ok();
10610            });
10611        }
10612    }
10613
10614    pub fn fold_function_bodies(
10615        &mut self,
10616        _: &actions::FoldFunctionBodies,
10617        cx: &mut ViewContext<Self>,
10618    ) {
10619        let snapshot = self.buffer.read(cx).snapshot(cx);
10620        let Some((_, _, buffer)) = snapshot.as_singleton() else {
10621            return;
10622        };
10623        let creases = buffer
10624            .function_body_fold_ranges(0..buffer.len())
10625            .map(|range| Crease::simple(range, self.display_map.read(cx).fold_placeholder.clone()))
10626            .collect();
10627
10628        self.fold_creases(creases, true, cx);
10629    }
10630
10631    pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10632        let mut to_fold = Vec::new();
10633        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10634        let selections = self.selections.all_adjusted(cx);
10635
10636        for selection in selections {
10637            let range = selection.range().sorted();
10638            let buffer_start_row = range.start.row;
10639
10640            if range.start.row != range.end.row {
10641                let mut found = false;
10642                for row in range.start.row..=range.end.row {
10643                    if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10644                        found = true;
10645                        to_fold.push(crease);
10646                    }
10647                }
10648                if found {
10649                    continue;
10650                }
10651            }
10652
10653            for row in (0..=range.start.row).rev() {
10654                if let Some(crease) = display_map.crease_for_buffer_row(MultiBufferRow(row)) {
10655                    if crease.range().end.row >= buffer_start_row {
10656                        to_fold.push(crease);
10657                    } else {
10658                        break;
10659                    }
10660                }
10661            }
10662        }
10663
10664        self.fold_creases(to_fold, true, cx);
10665    }
10666
10667    pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10668        let buffer_row = fold_at.buffer_row;
10669        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10670
10671        if let Some(crease) = display_map.crease_for_buffer_row(buffer_row) {
10672            let autoscroll = self
10673                .selections
10674                .all::<Point>(cx)
10675                .iter()
10676                .any(|selection| crease.range().overlaps(&selection.range()));
10677
10678            self.fold_creases(vec![crease], autoscroll, cx);
10679        }
10680    }
10681
10682    pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10683        if self.is_singleton(cx) {
10684            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10685            let buffer = &display_map.buffer_snapshot;
10686            let selections = self.selections.all::<Point>(cx);
10687            let ranges = selections
10688                .iter()
10689                .map(|s| {
10690                    let range = s.display_range(&display_map).sorted();
10691                    let mut start = range.start.to_point(&display_map);
10692                    let mut end = range.end.to_point(&display_map);
10693                    start.column = 0;
10694                    end.column = buffer.line_len(MultiBufferRow(end.row));
10695                    start..end
10696                })
10697                .collect::<Vec<_>>();
10698
10699            self.unfold_ranges(&ranges, true, true, cx);
10700        } else {
10701            let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
10702            let mut unfolded_buffers = HashSet::default();
10703            for (_, buffer_snapshot, _) in multi_buffer_snapshot.excerpts_in_ranges(
10704                self.selections
10705                    .disjoint_anchors()
10706                    .into_iter()
10707                    .map(|selection| selection.range()),
10708            ) {
10709                let buffer_id = buffer_snapshot.remote_id();
10710                if unfolded_buffers.insert(buffer_id) {
10711                    self.unfold_buffer(buffer_id, cx);
10712                }
10713            }
10714        }
10715    }
10716
10717    pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10718        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10719        let selections = self.selections.all::<Point>(cx);
10720        let ranges = selections
10721            .iter()
10722            .map(|s| {
10723                let mut range = s.display_range(&display_map).sorted();
10724                *range.start.column_mut() = 0;
10725                *range.end.column_mut() = display_map.line_len(range.end.row());
10726                let start = range.start.to_point(&display_map);
10727                let end = range.end.to_point(&display_map);
10728                start..end
10729            })
10730            .collect::<Vec<_>>();
10731
10732        self.unfold_ranges(&ranges, true, true, cx);
10733    }
10734
10735    pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10736        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10737
10738        let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10739            ..Point::new(
10740                unfold_at.buffer_row.0,
10741                display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10742            );
10743
10744        let autoscroll = self
10745            .selections
10746            .all::<Point>(cx)
10747            .iter()
10748            .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10749
10750        self.unfold_ranges(&[intersection_range], true, autoscroll, cx)
10751    }
10752
10753    pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10754        if self.buffer.read(cx).is_singleton() {
10755            let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10756            self.unfold_ranges(&[0..display_map.buffer_snapshot.len()], true, true, cx);
10757        } else {
10758            self.toggle_fold_multiple_buffers = cx.spawn(|editor, mut cx| async move {
10759                editor
10760                    .update(&mut cx, |editor, cx| {
10761                        for buffer_id in editor.buffer.read(cx).excerpt_buffer_ids() {
10762                            editor.unfold_buffer(buffer_id, cx);
10763                        }
10764                    })
10765                    .ok();
10766            });
10767        }
10768    }
10769
10770    pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10771        let selections = self.selections.all::<Point>(cx);
10772        let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10773        let line_mode = self.selections.line_mode;
10774        let ranges = selections
10775            .into_iter()
10776            .map(|s| {
10777                if line_mode {
10778                    let start = Point::new(s.start.row, 0);
10779                    let end = Point::new(
10780                        s.end.row,
10781                        display_map
10782                            .buffer_snapshot
10783                            .line_len(MultiBufferRow(s.end.row)),
10784                    );
10785                    Crease::simple(start..end, display_map.fold_placeholder.clone())
10786                } else {
10787                    Crease::simple(s.start..s.end, display_map.fold_placeholder.clone())
10788                }
10789            })
10790            .collect::<Vec<_>>();
10791        self.fold_creases(ranges, true, cx);
10792    }
10793
10794    pub fn fold_creases<T: ToOffset + Clone>(
10795        &mut self,
10796        creases: Vec<Crease<T>>,
10797        auto_scroll: bool,
10798        cx: &mut ViewContext<Self>,
10799    ) {
10800        if creases.is_empty() {
10801            return;
10802        }
10803
10804        let mut buffers_affected = HashSet::default();
10805        let multi_buffer = self.buffer().read(cx);
10806        for crease in &creases {
10807            if let Some((_, buffer, _)) =
10808                multi_buffer.excerpt_containing(crease.range().start.clone(), cx)
10809            {
10810                buffers_affected.insert(buffer.read(cx).remote_id());
10811            };
10812        }
10813
10814        self.display_map.update(cx, |map, cx| map.fold(creases, cx));
10815
10816        if auto_scroll {
10817            self.request_autoscroll(Autoscroll::fit(), cx);
10818        }
10819
10820        for buffer_id in buffers_affected {
10821            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10822        }
10823
10824        cx.notify();
10825
10826        if let Some(active_diagnostics) = self.active_diagnostics.take() {
10827            // Clear diagnostics block when folding a range that contains it.
10828            let snapshot = self.snapshot(cx);
10829            if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10830                drop(snapshot);
10831                self.active_diagnostics = Some(active_diagnostics);
10832                self.dismiss_diagnostics(cx);
10833            } else {
10834                self.active_diagnostics = Some(active_diagnostics);
10835            }
10836        }
10837
10838        self.scrollbar_marker_state.dirty = true;
10839    }
10840
10841    /// Removes any folds whose ranges intersect any of the given ranges.
10842    pub fn unfold_ranges<T: ToOffset + Clone>(
10843        &mut self,
10844        ranges: &[Range<T>],
10845        inclusive: bool,
10846        auto_scroll: bool,
10847        cx: &mut ViewContext<Self>,
10848    ) {
10849        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10850            map.unfold_intersecting(ranges.iter().cloned(), inclusive, cx)
10851        });
10852    }
10853
10854    pub fn fold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10855        if self.buffer().read(cx).is_singleton() || self.buffer_folded(buffer_id, cx) {
10856            return;
10857        }
10858        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10859            return;
10860        };
10861        let folded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10862        self.display_map
10863            .update(cx, |display_map, cx| display_map.fold_buffer(buffer_id, cx));
10864        cx.emit(EditorEvent::BufferFoldToggled {
10865            ids: folded_excerpts.iter().map(|&(id, _)| id).collect(),
10866            folded: true,
10867        });
10868        cx.notify();
10869    }
10870
10871    pub fn unfold_buffer(&mut self, buffer_id: BufferId, cx: &mut ViewContext<Self>) {
10872        if self.buffer().read(cx).is_singleton() || !self.buffer_folded(buffer_id, cx) {
10873            return;
10874        }
10875        let Some(buffer) = self.buffer().read(cx).buffer(buffer_id) else {
10876            return;
10877        };
10878        let unfolded_excerpts = self.buffer().read(cx).excerpts_for_buffer(&buffer, cx);
10879        self.display_map.update(cx, |display_map, cx| {
10880            display_map.unfold_buffer(buffer_id, cx);
10881        });
10882        cx.emit(EditorEvent::BufferFoldToggled {
10883            ids: unfolded_excerpts.iter().map(|&(id, _)| id).collect(),
10884            folded: false,
10885        });
10886        cx.notify();
10887    }
10888
10889    pub fn buffer_folded(&self, buffer: BufferId, cx: &AppContext) -> bool {
10890        self.display_map.read(cx).buffer_folded(buffer)
10891    }
10892
10893    /// Removes any folds with the given ranges.
10894    pub fn remove_folds_with_type<T: ToOffset + Clone>(
10895        &mut self,
10896        ranges: &[Range<T>],
10897        type_id: TypeId,
10898        auto_scroll: bool,
10899        cx: &mut ViewContext<Self>,
10900    ) {
10901        self.remove_folds_with(ranges, auto_scroll, cx, |map, cx| {
10902            map.remove_folds_with_type(ranges.iter().cloned(), type_id, cx)
10903        });
10904    }
10905
10906    fn remove_folds_with<T: ToOffset + Clone>(
10907        &mut self,
10908        ranges: &[Range<T>],
10909        auto_scroll: bool,
10910        cx: &mut ViewContext<Self>,
10911        update: impl FnOnce(&mut DisplayMap, &mut ModelContext<DisplayMap>),
10912    ) {
10913        if ranges.is_empty() {
10914            return;
10915        }
10916
10917        let mut buffers_affected = HashSet::default();
10918        let multi_buffer = self.buffer().read(cx);
10919        for range in ranges {
10920            if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10921                buffers_affected.insert(buffer.read(cx).remote_id());
10922            };
10923        }
10924
10925        self.display_map.update(cx, update);
10926
10927        if auto_scroll {
10928            self.request_autoscroll(Autoscroll::fit(), cx);
10929        }
10930
10931        for buffer_id in buffers_affected {
10932            Self::sync_expanded_diff_hunks(&mut self.diff_map, buffer_id, cx);
10933        }
10934
10935        cx.notify();
10936        self.scrollbar_marker_state.dirty = true;
10937        self.active_indent_guides_state.dirty = true;
10938    }
10939
10940    pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10941        self.display_map.read(cx).fold_placeholder.clone()
10942    }
10943
10944    pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10945        if hovered != self.gutter_hovered {
10946            self.gutter_hovered = hovered;
10947            cx.notify();
10948        }
10949    }
10950
10951    pub fn insert_blocks(
10952        &mut self,
10953        blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10954        autoscroll: Option<Autoscroll>,
10955        cx: &mut ViewContext<Self>,
10956    ) -> Vec<CustomBlockId> {
10957        let blocks = self
10958            .display_map
10959            .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10960        if let Some(autoscroll) = autoscroll {
10961            self.request_autoscroll(autoscroll, cx);
10962        }
10963        cx.notify();
10964        blocks
10965    }
10966
10967    pub fn resize_blocks(
10968        &mut self,
10969        heights: HashMap<CustomBlockId, u32>,
10970        autoscroll: Option<Autoscroll>,
10971        cx: &mut ViewContext<Self>,
10972    ) {
10973        self.display_map
10974            .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10975        if let Some(autoscroll) = autoscroll {
10976            self.request_autoscroll(autoscroll, cx);
10977        }
10978        cx.notify();
10979    }
10980
10981    pub fn replace_blocks(
10982        &mut self,
10983        renderers: HashMap<CustomBlockId, RenderBlock>,
10984        autoscroll: Option<Autoscroll>,
10985        cx: &mut ViewContext<Self>,
10986    ) {
10987        self.display_map
10988            .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10989        if let Some(autoscroll) = autoscroll {
10990            self.request_autoscroll(autoscroll, cx);
10991        }
10992        cx.notify();
10993    }
10994
10995    pub fn remove_blocks(
10996        &mut self,
10997        block_ids: HashSet<CustomBlockId>,
10998        autoscroll: Option<Autoscroll>,
10999        cx: &mut ViewContext<Self>,
11000    ) {
11001        self.display_map.update(cx, |display_map, cx| {
11002            display_map.remove_blocks(block_ids, cx)
11003        });
11004        if let Some(autoscroll) = autoscroll {
11005            self.request_autoscroll(autoscroll, cx);
11006        }
11007        cx.notify();
11008    }
11009
11010    pub fn row_for_block(
11011        &self,
11012        block_id: CustomBlockId,
11013        cx: &mut ViewContext<Self>,
11014    ) -> Option<DisplayRow> {
11015        self.display_map
11016            .update(cx, |map, cx| map.row_for_block(block_id, cx))
11017    }
11018
11019    pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11020        self.focused_block = Some(focused_block);
11021    }
11022
11023    pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11024        self.focused_block.take()
11025    }
11026
11027    pub fn insert_creases(
11028        &mut self,
11029        creases: impl IntoIterator<Item = Crease<Anchor>>,
11030        cx: &mut ViewContext<Self>,
11031    ) -> Vec<CreaseId> {
11032        self.display_map
11033            .update(cx, |map, cx| map.insert_creases(creases, cx))
11034    }
11035
11036    pub fn remove_creases(
11037        &mut self,
11038        ids: impl IntoIterator<Item = CreaseId>,
11039        cx: &mut ViewContext<Self>,
11040    ) {
11041        self.display_map
11042            .update(cx, |map, cx| map.remove_creases(ids, cx));
11043    }
11044
11045    pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11046        self.display_map
11047            .update(cx, |map, cx| map.snapshot(cx))
11048            .longest_row()
11049    }
11050
11051    pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11052        self.display_map
11053            .update(cx, |map, cx| map.snapshot(cx))
11054            .max_point()
11055    }
11056
11057    pub fn text(&self, cx: &AppContext) -> String {
11058        self.buffer.read(cx).read(cx).text()
11059    }
11060
11061    pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11062        let text = self.text(cx);
11063        let text = text.trim();
11064
11065        if text.is_empty() {
11066            return None;
11067        }
11068
11069        Some(text.to_string())
11070    }
11071
11072    pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11073        self.transact(cx, |this, cx| {
11074            this.buffer
11075                .read(cx)
11076                .as_singleton()
11077                .expect("you can only call set_text on editors for singleton buffers")
11078                .update(cx, |buffer, cx| buffer.set_text(text, cx));
11079        });
11080    }
11081
11082    pub fn display_text(&self, cx: &mut AppContext) -> String {
11083        self.display_map
11084            .update(cx, |map, cx| map.snapshot(cx))
11085            .text()
11086    }
11087
11088    pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11089        let mut wrap_guides = smallvec::smallvec![];
11090
11091        if self.show_wrap_guides == Some(false) {
11092            return wrap_guides;
11093        }
11094
11095        let settings = self.buffer.read(cx).settings_at(0, cx);
11096        if settings.show_wrap_guides {
11097            if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11098                wrap_guides.push((soft_wrap as usize, true));
11099            } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11100                wrap_guides.push((soft_wrap as usize, true));
11101            }
11102            wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11103        }
11104
11105        wrap_guides
11106    }
11107
11108    pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11109        let settings = self.buffer.read(cx).settings_at(0, cx);
11110        let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11111        match mode {
11112            language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11113                SoftWrap::None
11114            }
11115            language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11116            language_settings::SoftWrap::PreferredLineLength => {
11117                SoftWrap::Column(settings.preferred_line_length)
11118            }
11119            language_settings::SoftWrap::Bounded => {
11120                SoftWrap::Bounded(settings.preferred_line_length)
11121            }
11122        }
11123    }
11124
11125    pub fn set_soft_wrap_mode(
11126        &mut self,
11127        mode: language_settings::SoftWrap,
11128        cx: &mut ViewContext<Self>,
11129    ) {
11130        self.soft_wrap_mode_override = Some(mode);
11131        cx.notify();
11132    }
11133
11134    pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11135        self.text_style_refinement = Some(style);
11136    }
11137
11138    /// called by the Element so we know what style we were most recently rendered with.
11139    pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11140        let rem_size = cx.rem_size();
11141        self.display_map.update(cx, |map, cx| {
11142            map.set_font(
11143                style.text.font(),
11144                style.text.font_size.to_pixels(rem_size),
11145                cx,
11146            )
11147        });
11148        self.style = Some(style);
11149    }
11150
11151    pub fn style(&self) -> Option<&EditorStyle> {
11152        self.style.as_ref()
11153    }
11154
11155    // Called by the element. This method is not designed to be called outside of the editor
11156    // element's layout code because it does not notify when rewrapping is computed synchronously.
11157    pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11158        self.display_map
11159            .update(cx, |map, cx| map.set_wrap_width(width, cx))
11160    }
11161
11162    pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11163        if self.soft_wrap_mode_override.is_some() {
11164            self.soft_wrap_mode_override.take();
11165        } else {
11166            let soft_wrap = match self.soft_wrap_mode(cx) {
11167                SoftWrap::GitDiff => return,
11168                SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11169                SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11170                    language_settings::SoftWrap::None
11171                }
11172            };
11173            self.soft_wrap_mode_override = Some(soft_wrap);
11174        }
11175        cx.notify();
11176    }
11177
11178    pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11179        let Some(workspace) = self.workspace() else {
11180            return;
11181        };
11182        let fs = workspace.read(cx).app_state().fs.clone();
11183        let current_show = TabBarSettings::get_global(cx).show;
11184        update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11185            setting.show = Some(!current_show);
11186        });
11187    }
11188
11189    pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11190        let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11191            self.buffer
11192                .read(cx)
11193                .settings_at(0, cx)
11194                .indent_guides
11195                .enabled
11196        });
11197        self.show_indent_guides = Some(!currently_enabled);
11198        cx.notify();
11199    }
11200
11201    fn should_show_indent_guides(&self) -> Option<bool> {
11202        self.show_indent_guides
11203    }
11204
11205    pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11206        let mut editor_settings = EditorSettings::get_global(cx).clone();
11207        editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11208        EditorSettings::override_global(editor_settings, cx);
11209    }
11210
11211    pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11212        self.use_relative_line_numbers
11213            .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11214    }
11215
11216    pub fn toggle_relative_line_numbers(
11217        &mut self,
11218        _: &ToggleRelativeLineNumbers,
11219        cx: &mut ViewContext<Self>,
11220    ) {
11221        let is_relative = self.should_use_relative_line_numbers(cx);
11222        self.set_relative_line_number(Some(!is_relative), cx)
11223    }
11224
11225    pub fn set_relative_line_number(
11226        &mut self,
11227        is_relative: Option<bool>,
11228        cx: &mut ViewContext<Self>,
11229    ) {
11230        self.use_relative_line_numbers = is_relative;
11231        cx.notify();
11232    }
11233
11234    pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11235        self.show_gutter = show_gutter;
11236        cx.notify();
11237    }
11238
11239    pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11240        self.show_line_numbers = Some(show_line_numbers);
11241        cx.notify();
11242    }
11243
11244    pub fn set_show_git_diff_gutter(
11245        &mut self,
11246        show_git_diff_gutter: bool,
11247        cx: &mut ViewContext<Self>,
11248    ) {
11249        self.show_git_diff_gutter = Some(show_git_diff_gutter);
11250        cx.notify();
11251    }
11252
11253    pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11254        self.show_code_actions = Some(show_code_actions);
11255        cx.notify();
11256    }
11257
11258    pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11259        self.show_runnables = Some(show_runnables);
11260        cx.notify();
11261    }
11262
11263    pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11264        if self.display_map.read(cx).masked != masked {
11265            self.display_map.update(cx, |map, _| map.masked = masked);
11266        }
11267        cx.notify()
11268    }
11269
11270    pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11271        self.show_wrap_guides = Some(show_wrap_guides);
11272        cx.notify();
11273    }
11274
11275    pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11276        self.show_indent_guides = Some(show_indent_guides);
11277        cx.notify();
11278    }
11279
11280    pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11281        if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11282            if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11283                if let Some(dir) = file.abs_path(cx).parent() {
11284                    return Some(dir.to_owned());
11285                }
11286            }
11287
11288            if let Some(project_path) = buffer.read(cx).project_path(cx) {
11289                return Some(project_path.path.to_path_buf());
11290            }
11291        }
11292
11293        None
11294    }
11295
11296    fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11297        self.active_excerpt(cx)?
11298            .1
11299            .read(cx)
11300            .file()
11301            .and_then(|f| f.as_local())
11302    }
11303
11304    pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11305        if let Some(target) = self.target_file(cx) {
11306            cx.reveal_path(&target.abs_path(cx));
11307        }
11308    }
11309
11310    pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11311        if let Some(file) = self.target_file(cx) {
11312            if let Some(path) = file.abs_path(cx).to_str() {
11313                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11314            }
11315        }
11316    }
11317
11318    pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11319        if let Some(file) = self.target_file(cx) {
11320            if let Some(path) = file.path().to_str() {
11321                cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11322            }
11323        }
11324    }
11325
11326    pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11327        self.show_git_blame_gutter = !self.show_git_blame_gutter;
11328
11329        if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11330            self.start_git_blame(true, cx);
11331        }
11332
11333        cx.notify();
11334    }
11335
11336    pub fn toggle_git_blame_inline(
11337        &mut self,
11338        _: &ToggleGitBlameInline,
11339        cx: &mut ViewContext<Self>,
11340    ) {
11341        self.toggle_git_blame_inline_internal(true, cx);
11342        cx.notify();
11343    }
11344
11345    pub fn git_blame_inline_enabled(&self) -> bool {
11346        self.git_blame_inline_enabled
11347    }
11348
11349    pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11350        self.show_selection_menu = self
11351            .show_selection_menu
11352            .map(|show_selections_menu| !show_selections_menu)
11353            .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11354
11355        cx.notify();
11356    }
11357
11358    pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11359        self.show_selection_menu
11360            .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11361    }
11362
11363    fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11364        if let Some(project) = self.project.as_ref() {
11365            let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11366                return;
11367            };
11368
11369            if buffer.read(cx).file().is_none() {
11370                return;
11371            }
11372
11373            let focused = self.focus_handle(cx).contains_focused(cx);
11374
11375            let project = project.clone();
11376            let blame =
11377                cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11378            self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11379            self.blame = Some(blame);
11380        }
11381    }
11382
11383    fn toggle_git_blame_inline_internal(
11384        &mut self,
11385        user_triggered: bool,
11386        cx: &mut ViewContext<Self>,
11387    ) {
11388        if self.git_blame_inline_enabled {
11389            self.git_blame_inline_enabled = false;
11390            self.show_git_blame_inline = false;
11391            self.show_git_blame_inline_delay_task.take();
11392        } else {
11393            self.git_blame_inline_enabled = true;
11394            self.start_git_blame_inline(user_triggered, cx);
11395        }
11396
11397        cx.notify();
11398    }
11399
11400    fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11401        self.start_git_blame(user_triggered, cx);
11402
11403        if ProjectSettings::get_global(cx)
11404            .git
11405            .inline_blame_delay()
11406            .is_some()
11407        {
11408            self.start_inline_blame_timer(cx);
11409        } else {
11410            self.show_git_blame_inline = true
11411        }
11412    }
11413
11414    pub fn blame(&self) -> Option<&Model<GitBlame>> {
11415        self.blame.as_ref()
11416    }
11417
11418    pub fn show_git_blame_gutter(&self) -> bool {
11419        self.show_git_blame_gutter
11420    }
11421
11422    pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11423        self.show_git_blame_gutter && self.has_blame_entries(cx)
11424    }
11425
11426    pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11427        self.show_git_blame_inline
11428            && self.focus_handle.is_focused(cx)
11429            && !self.newest_selection_head_on_empty_line(cx)
11430            && self.has_blame_entries(cx)
11431    }
11432
11433    fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11434        self.blame()
11435            .map_or(false, |blame| blame.read(cx).has_generated_entries())
11436    }
11437
11438    fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11439        let cursor_anchor = self.selections.newest_anchor().head();
11440
11441        let snapshot = self.buffer.read(cx).snapshot(cx);
11442        let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11443
11444        snapshot.line_len(buffer_row) == 0
11445    }
11446
11447    fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11448        let buffer_and_selection = maybe!({
11449            let selection = self.selections.newest::<Point>(cx);
11450            let selection_range = selection.range();
11451
11452            let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11453                (buffer, selection_range.start.row..selection_range.end.row)
11454            } else {
11455                let buffer_ranges = self
11456                    .buffer()
11457                    .read(cx)
11458                    .range_to_buffer_ranges(selection_range, cx);
11459
11460                let (buffer, range, _) = if selection.reversed {
11461                    buffer_ranges.first()
11462                } else {
11463                    buffer_ranges.last()
11464                }?;
11465
11466                let snapshot = buffer.read(cx).snapshot();
11467                let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11468                    ..text::ToPoint::to_point(&range.end, &snapshot).row;
11469                (buffer.clone(), selection)
11470            };
11471
11472            Some((buffer, selection))
11473        });
11474
11475        let Some((buffer, selection)) = buffer_and_selection else {
11476            return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11477        };
11478
11479        let Some(project) = self.project.as_ref() else {
11480            return Task::ready(Err(anyhow!("editor does not have project")));
11481        };
11482
11483        project.update(cx, |project, cx| {
11484            project.get_permalink_to_line(&buffer, selection, cx)
11485        })
11486    }
11487
11488    pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11489        let permalink_task = self.get_permalink_to_line(cx);
11490        let workspace = self.workspace();
11491
11492        cx.spawn(|_, mut cx| async move {
11493            match permalink_task.await {
11494                Ok(permalink) => {
11495                    cx.update(|cx| {
11496                        cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11497                    })
11498                    .ok();
11499                }
11500                Err(err) => {
11501                    let message = format!("Failed to copy permalink: {err}");
11502
11503                    Err::<(), anyhow::Error>(err).log_err();
11504
11505                    if let Some(workspace) = workspace {
11506                        workspace
11507                            .update(&mut cx, |workspace, cx| {
11508                                struct CopyPermalinkToLine;
11509
11510                                workspace.show_toast(
11511                                    Toast::new(
11512                                        NotificationId::unique::<CopyPermalinkToLine>(),
11513                                        message,
11514                                    ),
11515                                    cx,
11516                                )
11517                            })
11518                            .ok();
11519                    }
11520                }
11521            }
11522        })
11523        .detach();
11524    }
11525
11526    pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11527        let selection = self.selections.newest::<Point>(cx).start.row + 1;
11528        if let Some(file) = self.target_file(cx) {
11529            if let Some(path) = file.path().to_str() {
11530                cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11531            }
11532        }
11533    }
11534
11535    pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11536        let permalink_task = self.get_permalink_to_line(cx);
11537        let workspace = self.workspace();
11538
11539        cx.spawn(|_, mut cx| async move {
11540            match permalink_task.await {
11541                Ok(permalink) => {
11542                    cx.update(|cx| {
11543                        cx.open_url(permalink.as_ref());
11544                    })
11545                    .ok();
11546                }
11547                Err(err) => {
11548                    let message = format!("Failed to open permalink: {err}");
11549
11550                    Err::<(), anyhow::Error>(err).log_err();
11551
11552                    if let Some(workspace) = workspace {
11553                        workspace
11554                            .update(&mut cx, |workspace, cx| {
11555                                struct OpenPermalinkToLine;
11556
11557                                workspace.show_toast(
11558                                    Toast::new(
11559                                        NotificationId::unique::<OpenPermalinkToLine>(),
11560                                        message,
11561                                    ),
11562                                    cx,
11563                                )
11564                            })
11565                            .ok();
11566                    }
11567                }
11568            }
11569        })
11570        .detach();
11571    }
11572
11573    pub fn insert_uuid_v4(&mut self, _: &InsertUuidV4, cx: &mut ViewContext<Self>) {
11574        self.insert_uuid(UuidVersion::V4, cx);
11575    }
11576
11577    pub fn insert_uuid_v7(&mut self, _: &InsertUuidV7, cx: &mut ViewContext<Self>) {
11578        self.insert_uuid(UuidVersion::V7, cx);
11579    }
11580
11581    fn insert_uuid(&mut self, version: UuidVersion, cx: &mut ViewContext<Self>) {
11582        self.transact(cx, |this, cx| {
11583            let edits = this
11584                .selections
11585                .all::<Point>(cx)
11586                .into_iter()
11587                .map(|selection| {
11588                    let uuid = match version {
11589                        UuidVersion::V4 => uuid::Uuid::new_v4(),
11590                        UuidVersion::V7 => uuid::Uuid::now_v7(),
11591                    };
11592
11593                    (selection.range(), uuid.to_string())
11594                });
11595            this.edit(edits, cx);
11596            this.refresh_inline_completion(true, false, cx);
11597        });
11598    }
11599
11600    /// Adds a row highlight for the given range. If a row has multiple highlights, the
11601    /// last highlight added will be used.
11602    ///
11603    /// If the range ends at the beginning of a line, then that line will not be highlighted.
11604    pub fn highlight_rows<T: 'static>(
11605        &mut self,
11606        range: Range<Anchor>,
11607        color: Hsla,
11608        should_autoscroll: bool,
11609        cx: &mut ViewContext<Self>,
11610    ) {
11611        let snapshot = self.buffer().read(cx).snapshot(cx);
11612        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11613        let ix = row_highlights.binary_search_by(|highlight| {
11614            Ordering::Equal
11615                .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11616                .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11617        });
11618
11619        if let Err(mut ix) = ix {
11620            let index = post_inc(&mut self.highlight_order);
11621
11622            // If this range intersects with the preceding highlight, then merge it with
11623            // the preceding highlight. Otherwise insert a new highlight.
11624            let mut merged = false;
11625            if ix > 0 {
11626                let prev_highlight = &mut row_highlights[ix - 1];
11627                if prev_highlight
11628                    .range
11629                    .end
11630                    .cmp(&range.start, &snapshot)
11631                    .is_ge()
11632                {
11633                    ix -= 1;
11634                    if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11635                        prev_highlight.range.end = range.end;
11636                    }
11637                    merged = true;
11638                    prev_highlight.index = index;
11639                    prev_highlight.color = color;
11640                    prev_highlight.should_autoscroll = should_autoscroll;
11641                }
11642            }
11643
11644            if !merged {
11645                row_highlights.insert(
11646                    ix,
11647                    RowHighlight {
11648                        range: range.clone(),
11649                        index,
11650                        color,
11651                        should_autoscroll,
11652                    },
11653                );
11654            }
11655
11656            // If any of the following highlights intersect with this one, merge them.
11657            while let Some(next_highlight) = row_highlights.get(ix + 1) {
11658                let highlight = &row_highlights[ix];
11659                if next_highlight
11660                    .range
11661                    .start
11662                    .cmp(&highlight.range.end, &snapshot)
11663                    .is_le()
11664                {
11665                    if next_highlight
11666                        .range
11667                        .end
11668                        .cmp(&highlight.range.end, &snapshot)
11669                        .is_gt()
11670                    {
11671                        row_highlights[ix].range.end = next_highlight.range.end;
11672                    }
11673                    row_highlights.remove(ix + 1);
11674                } else {
11675                    break;
11676                }
11677            }
11678        }
11679    }
11680
11681    /// Remove any highlighted row ranges of the given type that intersect the
11682    /// given ranges.
11683    pub fn remove_highlighted_rows<T: 'static>(
11684        &mut self,
11685        ranges_to_remove: Vec<Range<Anchor>>,
11686        cx: &mut ViewContext<Self>,
11687    ) {
11688        let snapshot = self.buffer().read(cx).snapshot(cx);
11689        let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11690        let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11691        row_highlights.retain(|highlight| {
11692            while let Some(range_to_remove) = ranges_to_remove.peek() {
11693                match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11694                    Ordering::Less | Ordering::Equal => {
11695                        ranges_to_remove.next();
11696                    }
11697                    Ordering::Greater => {
11698                        match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11699                            Ordering::Less | Ordering::Equal => {
11700                                return false;
11701                            }
11702                            Ordering::Greater => break,
11703                        }
11704                    }
11705                }
11706            }
11707
11708            true
11709        })
11710    }
11711
11712    /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11713    pub fn clear_row_highlights<T: 'static>(&mut self) {
11714        self.highlighted_rows.remove(&TypeId::of::<T>());
11715    }
11716
11717    /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11718    pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11719        self.highlighted_rows
11720            .get(&TypeId::of::<T>())
11721            .map_or(&[] as &[_], |vec| vec.as_slice())
11722            .iter()
11723            .map(|highlight| (highlight.range.clone(), highlight.color))
11724    }
11725
11726    /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11727    /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11728    /// Allows to ignore certain kinds of highlights.
11729    pub fn highlighted_display_rows(
11730        &mut self,
11731        cx: &mut WindowContext,
11732    ) -> BTreeMap<DisplayRow, Hsla> {
11733        let snapshot = self.snapshot(cx);
11734        let mut used_highlight_orders = HashMap::default();
11735        self.highlighted_rows
11736            .iter()
11737            .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11738            .fold(
11739                BTreeMap::<DisplayRow, Hsla>::new(),
11740                |mut unique_rows, highlight| {
11741                    let start = highlight.range.start.to_display_point(&snapshot);
11742                    let end = highlight.range.end.to_display_point(&snapshot);
11743                    let start_row = start.row().0;
11744                    let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11745                        && end.column() == 0
11746                    {
11747                        end.row().0.saturating_sub(1)
11748                    } else {
11749                        end.row().0
11750                    };
11751                    for row in start_row..=end_row {
11752                        let used_index =
11753                            used_highlight_orders.entry(row).or_insert(highlight.index);
11754                        if highlight.index >= *used_index {
11755                            *used_index = highlight.index;
11756                            unique_rows.insert(DisplayRow(row), highlight.color);
11757                        }
11758                    }
11759                    unique_rows
11760                },
11761            )
11762    }
11763
11764    pub fn highlighted_display_row_for_autoscroll(
11765        &self,
11766        snapshot: &DisplaySnapshot,
11767    ) -> Option<DisplayRow> {
11768        self.highlighted_rows
11769            .values()
11770            .flat_map(|highlighted_rows| highlighted_rows.iter())
11771            .filter_map(|highlight| {
11772                if highlight.should_autoscroll {
11773                    Some(highlight.range.start.to_display_point(snapshot).row())
11774                } else {
11775                    None
11776                }
11777            })
11778            .min()
11779    }
11780
11781    pub fn set_search_within_ranges(
11782        &mut self,
11783        ranges: &[Range<Anchor>],
11784        cx: &mut ViewContext<Self>,
11785    ) {
11786        self.highlight_background::<SearchWithinRange>(
11787            ranges,
11788            |colors| colors.editor_document_highlight_read_background,
11789            cx,
11790        )
11791    }
11792
11793    pub fn set_breadcrumb_header(&mut self, new_header: String) {
11794        self.breadcrumb_header = Some(new_header);
11795    }
11796
11797    pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11798        self.clear_background_highlights::<SearchWithinRange>(cx);
11799    }
11800
11801    pub fn highlight_background<T: 'static>(
11802        &mut self,
11803        ranges: &[Range<Anchor>],
11804        color_fetcher: fn(&ThemeColors) -> Hsla,
11805        cx: &mut ViewContext<Self>,
11806    ) {
11807        self.background_highlights
11808            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11809        self.scrollbar_marker_state.dirty = true;
11810        cx.notify();
11811    }
11812
11813    pub fn clear_background_highlights<T: 'static>(
11814        &mut self,
11815        cx: &mut ViewContext<Self>,
11816    ) -> Option<BackgroundHighlight> {
11817        let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11818        if !text_highlights.1.is_empty() {
11819            self.scrollbar_marker_state.dirty = true;
11820            cx.notify();
11821        }
11822        Some(text_highlights)
11823    }
11824
11825    pub fn highlight_gutter<T: 'static>(
11826        &mut self,
11827        ranges: &[Range<Anchor>],
11828        color_fetcher: fn(&AppContext) -> Hsla,
11829        cx: &mut ViewContext<Self>,
11830    ) {
11831        self.gutter_highlights
11832            .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11833        cx.notify();
11834    }
11835
11836    pub fn clear_gutter_highlights<T: 'static>(
11837        &mut self,
11838        cx: &mut ViewContext<Self>,
11839    ) -> Option<GutterHighlight> {
11840        cx.notify();
11841        self.gutter_highlights.remove(&TypeId::of::<T>())
11842    }
11843
11844    #[cfg(feature = "test-support")]
11845    pub fn all_text_background_highlights(
11846        &mut self,
11847        cx: &mut ViewContext<Self>,
11848    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11849        let snapshot = self.snapshot(cx);
11850        let buffer = &snapshot.buffer_snapshot;
11851        let start = buffer.anchor_before(0);
11852        let end = buffer.anchor_after(buffer.len());
11853        let theme = cx.theme().colors();
11854        self.background_highlights_in_range(start..end, &snapshot, theme)
11855    }
11856
11857    #[cfg(feature = "test-support")]
11858    pub fn search_background_highlights(
11859        &mut self,
11860        cx: &mut ViewContext<Self>,
11861    ) -> Vec<Range<Point>> {
11862        let snapshot = self.buffer().read(cx).snapshot(cx);
11863
11864        let highlights = self
11865            .background_highlights
11866            .get(&TypeId::of::<items::BufferSearchHighlights>());
11867
11868        if let Some((_color, ranges)) = highlights {
11869            ranges
11870                .iter()
11871                .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11872                .collect_vec()
11873        } else {
11874            vec![]
11875        }
11876    }
11877
11878    fn document_highlights_for_position<'a>(
11879        &'a self,
11880        position: Anchor,
11881        buffer: &'a MultiBufferSnapshot,
11882    ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11883        let read_highlights = self
11884            .background_highlights
11885            .get(&TypeId::of::<DocumentHighlightRead>())
11886            .map(|h| &h.1);
11887        let write_highlights = self
11888            .background_highlights
11889            .get(&TypeId::of::<DocumentHighlightWrite>())
11890            .map(|h| &h.1);
11891        let left_position = position.bias_left(buffer);
11892        let right_position = position.bias_right(buffer);
11893        read_highlights
11894            .into_iter()
11895            .chain(write_highlights)
11896            .flat_map(move |ranges| {
11897                let start_ix = match ranges.binary_search_by(|probe| {
11898                    let cmp = probe.end.cmp(&left_position, buffer);
11899                    if cmp.is_ge() {
11900                        Ordering::Greater
11901                    } else {
11902                        Ordering::Less
11903                    }
11904                }) {
11905                    Ok(i) | Err(i) => i,
11906                };
11907
11908                ranges[start_ix..]
11909                    .iter()
11910                    .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11911            })
11912    }
11913
11914    pub fn has_background_highlights<T: 'static>(&self) -> bool {
11915        self.background_highlights
11916            .get(&TypeId::of::<T>())
11917            .map_or(false, |(_, highlights)| !highlights.is_empty())
11918    }
11919
11920    pub fn background_highlights_in_range(
11921        &self,
11922        search_range: Range<Anchor>,
11923        display_snapshot: &DisplaySnapshot,
11924        theme: &ThemeColors,
11925    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11926        let mut results = Vec::new();
11927        for (color_fetcher, ranges) in self.background_highlights.values() {
11928            let color = color_fetcher(theme);
11929            let start_ix = match ranges.binary_search_by(|probe| {
11930                let cmp = probe
11931                    .end
11932                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11933                if cmp.is_gt() {
11934                    Ordering::Greater
11935                } else {
11936                    Ordering::Less
11937                }
11938            }) {
11939                Ok(i) | Err(i) => i,
11940            };
11941            for range in &ranges[start_ix..] {
11942                if range
11943                    .start
11944                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11945                    .is_ge()
11946                {
11947                    break;
11948                }
11949
11950                let start = range.start.to_display_point(display_snapshot);
11951                let end = range.end.to_display_point(display_snapshot);
11952                results.push((start..end, color))
11953            }
11954        }
11955        results
11956    }
11957
11958    pub fn background_highlight_row_ranges<T: 'static>(
11959        &self,
11960        search_range: Range<Anchor>,
11961        display_snapshot: &DisplaySnapshot,
11962        count: usize,
11963    ) -> Vec<RangeInclusive<DisplayPoint>> {
11964        let mut results = Vec::new();
11965        let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11966            return vec![];
11967        };
11968
11969        let start_ix = match ranges.binary_search_by(|probe| {
11970            let cmp = probe
11971                .end
11972                .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11973            if cmp.is_gt() {
11974                Ordering::Greater
11975            } else {
11976                Ordering::Less
11977            }
11978        }) {
11979            Ok(i) | Err(i) => i,
11980        };
11981        let mut push_region = |start: Option<Point>, end: Option<Point>| {
11982            if let (Some(start_display), Some(end_display)) = (start, end) {
11983                results.push(
11984                    start_display.to_display_point(display_snapshot)
11985                        ..=end_display.to_display_point(display_snapshot),
11986                );
11987            }
11988        };
11989        let mut start_row: Option<Point> = None;
11990        let mut end_row: Option<Point> = None;
11991        if ranges.len() > count {
11992            return Vec::new();
11993        }
11994        for range in &ranges[start_ix..] {
11995            if range
11996                .start
11997                .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11998                .is_ge()
11999            {
12000                break;
12001            }
12002            let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12003            if let Some(current_row) = &end_row {
12004                if end.row == current_row.row {
12005                    continue;
12006                }
12007            }
12008            let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12009            if start_row.is_none() {
12010                assert_eq!(end_row, None);
12011                start_row = Some(start);
12012                end_row = Some(end);
12013                continue;
12014            }
12015            if let Some(current_end) = end_row.as_mut() {
12016                if start.row > current_end.row + 1 {
12017                    push_region(start_row, end_row);
12018                    start_row = Some(start);
12019                    end_row = Some(end);
12020                } else {
12021                    // Merge two hunks.
12022                    *current_end = end;
12023                }
12024            } else {
12025                unreachable!();
12026            }
12027        }
12028        // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12029        push_region(start_row, end_row);
12030        results
12031    }
12032
12033    pub fn gutter_highlights_in_range(
12034        &self,
12035        search_range: Range<Anchor>,
12036        display_snapshot: &DisplaySnapshot,
12037        cx: &AppContext,
12038    ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12039        let mut results = Vec::new();
12040        for (color_fetcher, ranges) in self.gutter_highlights.values() {
12041            let color = color_fetcher(cx);
12042            let start_ix = match ranges.binary_search_by(|probe| {
12043                let cmp = probe
12044                    .end
12045                    .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12046                if cmp.is_gt() {
12047                    Ordering::Greater
12048                } else {
12049                    Ordering::Less
12050                }
12051            }) {
12052                Ok(i) | Err(i) => i,
12053            };
12054            for range in &ranges[start_ix..] {
12055                if range
12056                    .start
12057                    .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12058                    .is_ge()
12059                {
12060                    break;
12061                }
12062
12063                let start = range.start.to_display_point(display_snapshot);
12064                let end = range.end.to_display_point(display_snapshot);
12065                results.push((start..end, color))
12066            }
12067        }
12068        results
12069    }
12070
12071    /// Get the text ranges corresponding to the redaction query
12072    pub fn redacted_ranges(
12073        &self,
12074        search_range: Range<Anchor>,
12075        display_snapshot: &DisplaySnapshot,
12076        cx: &WindowContext,
12077    ) -> Vec<Range<DisplayPoint>> {
12078        display_snapshot
12079            .buffer_snapshot
12080            .redacted_ranges(search_range, |file| {
12081                if let Some(file) = file {
12082                    file.is_private()
12083                        && EditorSettings::get(
12084                            Some(SettingsLocation {
12085                                worktree_id: file.worktree_id(cx),
12086                                path: file.path().as_ref(),
12087                            }),
12088                            cx,
12089                        )
12090                        .redact_private_values
12091                } else {
12092                    false
12093                }
12094            })
12095            .map(|range| {
12096                range.start.to_display_point(display_snapshot)
12097                    ..range.end.to_display_point(display_snapshot)
12098            })
12099            .collect()
12100    }
12101
12102    pub fn highlight_text<T: 'static>(
12103        &mut self,
12104        ranges: Vec<Range<Anchor>>,
12105        style: HighlightStyle,
12106        cx: &mut ViewContext<Self>,
12107    ) {
12108        self.display_map.update(cx, |map, _| {
12109            map.highlight_text(TypeId::of::<T>(), ranges, style)
12110        });
12111        cx.notify();
12112    }
12113
12114    pub(crate) fn highlight_inlays<T: 'static>(
12115        &mut self,
12116        highlights: Vec<InlayHighlight>,
12117        style: HighlightStyle,
12118        cx: &mut ViewContext<Self>,
12119    ) {
12120        self.display_map.update(cx, |map, _| {
12121            map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12122        });
12123        cx.notify();
12124    }
12125
12126    pub fn text_highlights<'a, T: 'static>(
12127        &'a self,
12128        cx: &'a AppContext,
12129    ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12130        self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12131    }
12132
12133    pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12134        let cleared = self
12135            .display_map
12136            .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12137        if cleared {
12138            cx.notify();
12139        }
12140    }
12141
12142    pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12143        (self.read_only(cx) || self.blink_manager.read(cx).visible())
12144            && self.focus_handle.is_focused(cx)
12145    }
12146
12147    pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12148        self.show_cursor_when_unfocused = is_enabled;
12149        cx.notify();
12150    }
12151
12152    pub fn lsp_store(&self, cx: &AppContext) -> Option<Model<LspStore>> {
12153        self.project
12154            .as_ref()
12155            .map(|project| project.read(cx).lsp_store())
12156    }
12157
12158    fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12159        cx.notify();
12160    }
12161
12162    fn on_buffer_event(
12163        &mut self,
12164        multibuffer: Model<MultiBuffer>,
12165        event: &multi_buffer::Event,
12166        cx: &mut ViewContext<Self>,
12167    ) {
12168        match event {
12169            multi_buffer::Event::Edited {
12170                singleton_buffer_edited,
12171                edited_buffer: buffer_edited,
12172            } => {
12173                self.scrollbar_marker_state.dirty = true;
12174                self.active_indent_guides_state.dirty = true;
12175                self.refresh_active_diagnostics(cx);
12176                self.refresh_code_actions(cx);
12177                if self.has_active_inline_completion() {
12178                    self.update_visible_inline_completion(cx);
12179                }
12180                if let Some(buffer) = buffer_edited {
12181                    let buffer_id = buffer.read(cx).remote_id();
12182                    if !self.registered_buffers.contains_key(&buffer_id) {
12183                        if let Some(lsp_store) = self.lsp_store(cx) {
12184                            lsp_store.update(cx, |lsp_store, cx| {
12185                                self.registered_buffers.insert(
12186                                    buffer_id,
12187                                    lsp_store.register_buffer_with_language_servers(&buffer, cx),
12188                                );
12189                            })
12190                        }
12191                    }
12192                }
12193                cx.emit(EditorEvent::BufferEdited);
12194                cx.emit(SearchEvent::MatchesInvalidated);
12195                if *singleton_buffer_edited {
12196                    if let Some(project) = &self.project {
12197                        let project = project.read(cx);
12198                        #[allow(clippy::mutable_key_type)]
12199                        let languages_affected = multibuffer
12200                            .read(cx)
12201                            .all_buffers()
12202                            .into_iter()
12203                            .filter_map(|buffer| {
12204                                let buffer = buffer.read(cx);
12205                                let language = buffer.language()?;
12206                                if project.is_local()
12207                                    && project
12208                                        .language_servers_for_local_buffer(buffer, cx)
12209                                        .count()
12210                                        == 0
12211                                {
12212                                    None
12213                                } else {
12214                                    Some(language)
12215                                }
12216                            })
12217                            .cloned()
12218                            .collect::<HashSet<_>>();
12219                        if !languages_affected.is_empty() {
12220                            self.refresh_inlay_hints(
12221                                InlayHintRefreshReason::BufferEdited(languages_affected),
12222                                cx,
12223                            );
12224                        }
12225                    }
12226                }
12227
12228                let Some(project) = &self.project else { return };
12229                let (telemetry, is_via_ssh) = {
12230                    let project = project.read(cx);
12231                    let telemetry = project.client().telemetry().clone();
12232                    let is_via_ssh = project.is_via_ssh();
12233                    (telemetry, is_via_ssh)
12234                };
12235                refresh_linked_ranges(self, cx);
12236                telemetry.log_edit_event("editor", is_via_ssh);
12237            }
12238            multi_buffer::Event::ExcerptsAdded {
12239                buffer,
12240                predecessor,
12241                excerpts,
12242            } => {
12243                self.tasks_update_task = Some(self.refresh_runnables(cx));
12244                let buffer_id = buffer.read(cx).remote_id();
12245                if !self.diff_map.diff_bases.contains_key(&buffer_id) {
12246                    if let Some(project) = &self.project {
12247                        get_unstaged_changes_for_buffers(project, [buffer.clone()], cx);
12248                    }
12249                }
12250                cx.emit(EditorEvent::ExcerptsAdded {
12251                    buffer: buffer.clone(),
12252                    predecessor: *predecessor,
12253                    excerpts: excerpts.clone(),
12254                });
12255                self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12256            }
12257            multi_buffer::Event::ExcerptsRemoved { ids } => {
12258                self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12259                let buffer = self.buffer.read(cx);
12260                self.registered_buffers
12261                    .retain(|buffer_id, _| buffer.buffer(*buffer_id).is_some());
12262                cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12263            }
12264            multi_buffer::Event::ExcerptsEdited { ids } => {
12265                cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12266            }
12267            multi_buffer::Event::ExcerptsExpanded { ids } => {
12268                cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12269            }
12270            multi_buffer::Event::Reparsed(buffer_id) => {
12271                self.tasks_update_task = Some(self.refresh_runnables(cx));
12272
12273                cx.emit(EditorEvent::Reparsed(*buffer_id));
12274            }
12275            multi_buffer::Event::LanguageChanged(buffer_id) => {
12276                linked_editing_ranges::refresh_linked_ranges(self, cx);
12277                cx.emit(EditorEvent::Reparsed(*buffer_id));
12278                cx.notify();
12279            }
12280            multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12281            multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12282            multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12283                cx.emit(EditorEvent::TitleChanged)
12284            }
12285            // multi_buffer::Event::DiffBaseChanged => {
12286            //     self.scrollbar_marker_state.dirty = true;
12287            //     cx.emit(EditorEvent::DiffBaseChanged);
12288            //     cx.notify();
12289            // }
12290            multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12291            multi_buffer::Event::DiagnosticsUpdated => {
12292                self.refresh_active_diagnostics(cx);
12293                self.scrollbar_marker_state.dirty = true;
12294                cx.notify();
12295            }
12296            _ => {}
12297        };
12298    }
12299
12300    fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12301        cx.notify();
12302    }
12303
12304    fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12305        self.tasks_update_task = Some(self.refresh_runnables(cx));
12306        self.refresh_inline_completion(true, false, cx);
12307        self.refresh_inlay_hints(
12308            InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12309                self.selections.newest_anchor().head(),
12310                &self.buffer.read(cx).snapshot(cx),
12311                cx,
12312            )),
12313            cx,
12314        );
12315
12316        let old_cursor_shape = self.cursor_shape;
12317
12318        {
12319            let editor_settings = EditorSettings::get_global(cx);
12320            self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12321            self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12322            self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12323        }
12324
12325        if old_cursor_shape != self.cursor_shape {
12326            cx.emit(EditorEvent::CursorShapeChanged);
12327        }
12328
12329        let project_settings = ProjectSettings::get_global(cx);
12330        self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12331
12332        if self.mode == EditorMode::Full {
12333            let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12334            if self.git_blame_inline_enabled != inline_blame_enabled {
12335                self.toggle_git_blame_inline_internal(false, cx);
12336            }
12337        }
12338
12339        cx.notify();
12340    }
12341
12342    pub fn set_searchable(&mut self, searchable: bool) {
12343        self.searchable = searchable;
12344    }
12345
12346    pub fn searchable(&self) -> bool {
12347        self.searchable
12348    }
12349
12350    fn open_proposed_changes_editor(
12351        &mut self,
12352        _: &OpenProposedChangesEditor,
12353        cx: &mut ViewContext<Self>,
12354    ) {
12355        let Some(workspace) = self.workspace() else {
12356            cx.propagate();
12357            return;
12358        };
12359
12360        let selections = self.selections.all::<usize>(cx);
12361        let buffer = self.buffer.read(cx);
12362        let mut new_selections_by_buffer = HashMap::default();
12363        for selection in selections {
12364            for (buffer, range, _) in
12365                buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12366            {
12367                let mut range = range.to_point(buffer.read(cx));
12368                range.start.column = 0;
12369                range.end.column = buffer.read(cx).line_len(range.end.row);
12370                new_selections_by_buffer
12371                    .entry(buffer)
12372                    .or_insert(Vec::new())
12373                    .push(range)
12374            }
12375        }
12376
12377        let proposed_changes_buffers = new_selections_by_buffer
12378            .into_iter()
12379            .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12380            .collect::<Vec<_>>();
12381        let proposed_changes_editor = cx.new_view(|cx| {
12382            ProposedChangesEditor::new(
12383                "Proposed changes",
12384                proposed_changes_buffers,
12385                self.project.clone(),
12386                cx,
12387            )
12388        });
12389
12390        cx.window_context().defer(move |cx| {
12391            workspace.update(cx, |workspace, cx| {
12392                workspace.active_pane().update(cx, |pane, cx| {
12393                    pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12394                });
12395            });
12396        });
12397    }
12398
12399    pub fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12400        self.open_excerpts_common(None, true, cx)
12401    }
12402
12403    pub fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12404        self.open_excerpts_common(None, false, cx)
12405    }
12406
12407    fn open_excerpts_common(
12408        &mut self,
12409        jump_data: Option<JumpData>,
12410        split: bool,
12411        cx: &mut ViewContext<Self>,
12412    ) {
12413        let Some(workspace) = self.workspace() else {
12414            cx.propagate();
12415            return;
12416        };
12417
12418        if self.buffer.read(cx).is_singleton() {
12419            cx.propagate();
12420            return;
12421        }
12422
12423        let mut new_selections_by_buffer = HashMap::default();
12424        match &jump_data {
12425            Some(jump_data) => {
12426                let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
12427                if let Some(buffer) = multi_buffer_snapshot
12428                    .buffer_id_for_excerpt(jump_data.excerpt_id)
12429                    .and_then(|buffer_id| self.buffer.read(cx).buffer(buffer_id))
12430                {
12431                    let buffer_snapshot = buffer.read(cx).snapshot();
12432                    let jump_to_point = if buffer_snapshot.can_resolve(&jump_data.anchor) {
12433                        language::ToPoint::to_point(&jump_data.anchor, &buffer_snapshot)
12434                    } else {
12435                        buffer_snapshot.clip_point(jump_data.position, Bias::Left)
12436                    };
12437                    let jump_to_offset = buffer_snapshot.point_to_offset(jump_to_point);
12438                    new_selections_by_buffer.insert(
12439                        buffer,
12440                        (
12441                            vec![jump_to_offset..jump_to_offset],
12442                            Some(jump_data.line_offset_from_top),
12443                        ),
12444                    );
12445                }
12446            }
12447            None => {
12448                let selections = self.selections.all::<usize>(cx);
12449                let buffer = self.buffer.read(cx);
12450                for selection in selections {
12451                    for (mut buffer_handle, mut range, _) in
12452                        buffer.range_to_buffer_ranges(selection.range(), cx)
12453                    {
12454                        // When editing branch buffers, jump to the corresponding location
12455                        // in their base buffer.
12456                        let buffer = buffer_handle.read(cx);
12457                        if let Some(base_buffer) = buffer.base_buffer() {
12458                            range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12459                            buffer_handle = base_buffer;
12460                        }
12461
12462                        if selection.reversed {
12463                            mem::swap(&mut range.start, &mut range.end);
12464                        }
12465                        new_selections_by_buffer
12466                            .entry(buffer_handle)
12467                            .or_insert((Vec::new(), None))
12468                            .0
12469                            .push(range)
12470                    }
12471                }
12472            }
12473        }
12474
12475        if new_selections_by_buffer.is_empty() {
12476            return;
12477        }
12478
12479        // We defer the pane interaction because we ourselves are a workspace item
12480        // and activating a new item causes the pane to call a method on us reentrantly,
12481        // which panics if we're on the stack.
12482        cx.window_context().defer(move |cx| {
12483            workspace.update(cx, |workspace, cx| {
12484                let pane = if split {
12485                    workspace.adjacent_pane(cx)
12486                } else {
12487                    workspace.active_pane().clone()
12488                };
12489
12490                for (buffer, (ranges, scroll_offset)) in new_selections_by_buffer {
12491                    let editor = buffer
12492                        .read(cx)
12493                        .file()
12494                        .is_none()
12495                        .then(|| {
12496                            // Handle file-less buffers separately: those are not really the project items, so won't have a paroject path or entity id,
12497                            // so `workspace.open_project_item` will never find them, always opening a new editor.
12498                            // Instead, we try to activate the existing editor in the pane first.
12499                            let (editor, pane_item_index) =
12500                                pane.read(cx).items().enumerate().find_map(|(i, item)| {
12501                                    let editor = item.downcast::<Editor>()?;
12502                                    let singleton_buffer =
12503                                        editor.read(cx).buffer().read(cx).as_singleton()?;
12504                                    if singleton_buffer == buffer {
12505                                        Some((editor, i))
12506                                    } else {
12507                                        None
12508                                    }
12509                                })?;
12510                            pane.update(cx, |pane, cx| {
12511                                pane.activate_item(pane_item_index, true, true, cx)
12512                            });
12513                            Some(editor)
12514                        })
12515                        .flatten()
12516                        .unwrap_or_else(|| {
12517                            workspace.open_project_item::<Self>(
12518                                pane.clone(),
12519                                buffer,
12520                                true,
12521                                true,
12522                                cx,
12523                            )
12524                        });
12525
12526                    editor.update(cx, |editor, cx| {
12527                        let autoscroll = match scroll_offset {
12528                            Some(scroll_offset) => Autoscroll::top_relative(scroll_offset as usize),
12529                            None => Autoscroll::newest(),
12530                        };
12531                        let nav_history = editor.nav_history.take();
12532                        editor.change_selections(Some(autoscroll), cx, |s| {
12533                            s.select_ranges(ranges);
12534                        });
12535                        editor.nav_history = nav_history;
12536                    });
12537                }
12538            })
12539        });
12540    }
12541
12542    fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12543        let snapshot = self.buffer.read(cx).read(cx);
12544        let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12545        Some(
12546            ranges
12547                .iter()
12548                .map(move |range| {
12549                    range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12550                })
12551                .collect(),
12552        )
12553    }
12554
12555    fn selection_replacement_ranges(
12556        &self,
12557        range: Range<OffsetUtf16>,
12558        cx: &mut AppContext,
12559    ) -> Vec<Range<OffsetUtf16>> {
12560        let selections = self.selections.all::<OffsetUtf16>(cx);
12561        let newest_selection = selections
12562            .iter()
12563            .max_by_key(|selection| selection.id)
12564            .unwrap();
12565        let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12566        let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12567        let snapshot = self.buffer.read(cx).read(cx);
12568        selections
12569            .into_iter()
12570            .map(|mut selection| {
12571                selection.start.0 =
12572                    (selection.start.0 as isize).saturating_add(start_delta) as usize;
12573                selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12574                snapshot.clip_offset_utf16(selection.start, Bias::Left)
12575                    ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12576            })
12577            .collect()
12578    }
12579
12580    fn report_editor_event(
12581        &self,
12582        event_type: &'static str,
12583        file_extension: Option<String>,
12584        cx: &AppContext,
12585    ) {
12586        if cfg!(any(test, feature = "test-support")) {
12587            return;
12588        }
12589
12590        let Some(project) = &self.project else { return };
12591
12592        // If None, we are in a file without an extension
12593        let file = self
12594            .buffer
12595            .read(cx)
12596            .as_singleton()
12597            .and_then(|b| b.read(cx).file());
12598        let file_extension = file_extension.or(file
12599            .as_ref()
12600            .and_then(|file| Path::new(file.file_name(cx)).extension())
12601            .and_then(|e| e.to_str())
12602            .map(|a| a.to_string()));
12603
12604        let vim_mode = cx
12605            .global::<SettingsStore>()
12606            .raw_user_settings()
12607            .get("vim_mode")
12608            == Some(&serde_json::Value::Bool(true));
12609
12610        let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12611            == language::language_settings::InlineCompletionProvider::Copilot;
12612        let copilot_enabled_for_language = self
12613            .buffer
12614            .read(cx)
12615            .settings_at(0, cx)
12616            .show_inline_completions;
12617
12618        let project = project.read(cx);
12619        telemetry::event!(
12620            event_type,
12621            file_extension,
12622            vim_mode,
12623            copilot_enabled,
12624            copilot_enabled_for_language,
12625            is_via_ssh = project.is_via_ssh(),
12626        );
12627    }
12628
12629    /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12630    /// with each line being an array of {text, highlight} objects.
12631    fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12632        let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12633            return;
12634        };
12635
12636        #[derive(Serialize)]
12637        struct Chunk<'a> {
12638            text: String,
12639            highlight: Option<&'a str>,
12640        }
12641
12642        let snapshot = buffer.read(cx).snapshot();
12643        let range = self
12644            .selected_text_range(false, cx)
12645            .and_then(|selection| {
12646                if selection.range.is_empty() {
12647                    None
12648                } else {
12649                    Some(selection.range)
12650                }
12651            })
12652            .unwrap_or_else(|| 0..snapshot.len());
12653
12654        let chunks = snapshot.chunks(range, true);
12655        let mut lines = Vec::new();
12656        let mut line: VecDeque<Chunk> = VecDeque::new();
12657
12658        let Some(style) = self.style.as_ref() else {
12659            return;
12660        };
12661
12662        for chunk in chunks {
12663            let highlight = chunk
12664                .syntax_highlight_id
12665                .and_then(|id| id.name(&style.syntax));
12666            let mut chunk_lines = chunk.text.split('\n').peekable();
12667            while let Some(text) = chunk_lines.next() {
12668                let mut merged_with_last_token = false;
12669                if let Some(last_token) = line.back_mut() {
12670                    if last_token.highlight == highlight {
12671                        last_token.text.push_str(text);
12672                        merged_with_last_token = true;
12673                    }
12674                }
12675
12676                if !merged_with_last_token {
12677                    line.push_back(Chunk {
12678                        text: text.into(),
12679                        highlight,
12680                    });
12681                }
12682
12683                if chunk_lines.peek().is_some() {
12684                    if line.len() > 1 && line.front().unwrap().text.is_empty() {
12685                        line.pop_front();
12686                    }
12687                    if line.len() > 1 && line.back().unwrap().text.is_empty() {
12688                        line.pop_back();
12689                    }
12690
12691                    lines.push(mem::take(&mut line));
12692                }
12693            }
12694        }
12695
12696        let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12697            return;
12698        };
12699        cx.write_to_clipboard(ClipboardItem::new_string(lines));
12700    }
12701
12702    pub fn open_context_menu(&mut self, _: &OpenContextMenu, cx: &mut ViewContext<Self>) {
12703        self.request_autoscroll(Autoscroll::newest(), cx);
12704        let position = self.selections.newest_display(cx).start;
12705        mouse_context_menu::deploy_context_menu(self, None, position, cx);
12706    }
12707
12708    pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12709        &self.inlay_hint_cache
12710    }
12711
12712    pub fn replay_insert_event(
12713        &mut self,
12714        text: &str,
12715        relative_utf16_range: Option<Range<isize>>,
12716        cx: &mut ViewContext<Self>,
12717    ) {
12718        if !self.input_enabled {
12719            cx.emit(EditorEvent::InputIgnored { text: text.into() });
12720            return;
12721        }
12722        if let Some(relative_utf16_range) = relative_utf16_range {
12723            let selections = self.selections.all::<OffsetUtf16>(cx);
12724            self.change_selections(None, cx, |s| {
12725                let new_ranges = selections.into_iter().map(|range| {
12726                    let start = OffsetUtf16(
12727                        range
12728                            .head()
12729                            .0
12730                            .saturating_add_signed(relative_utf16_range.start),
12731                    );
12732                    let end = OffsetUtf16(
12733                        range
12734                            .head()
12735                            .0
12736                            .saturating_add_signed(relative_utf16_range.end),
12737                    );
12738                    start..end
12739                });
12740                s.select_ranges(new_ranges);
12741            });
12742        }
12743
12744        self.handle_input(text, cx);
12745    }
12746
12747    pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12748        let Some(provider) = self.semantics_provider.as_ref() else {
12749            return false;
12750        };
12751
12752        let mut supports = false;
12753        self.buffer().read(cx).for_each_buffer(|buffer| {
12754            supports |= provider.supports_inlay_hints(buffer, cx);
12755        });
12756        supports
12757    }
12758
12759    pub fn focus(&self, cx: &mut WindowContext) {
12760        cx.focus(&self.focus_handle)
12761    }
12762
12763    pub fn is_focused(&self, cx: &WindowContext) -> bool {
12764        self.focus_handle.is_focused(cx)
12765    }
12766
12767    fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12768        cx.emit(EditorEvent::Focused);
12769
12770        if let Some(descendant) = self
12771            .last_focused_descendant
12772            .take()
12773            .and_then(|descendant| descendant.upgrade())
12774        {
12775            cx.focus(&descendant);
12776        } else {
12777            if let Some(blame) = self.blame.as_ref() {
12778                blame.update(cx, GitBlame::focus)
12779            }
12780
12781            self.blink_manager.update(cx, BlinkManager::enable);
12782            self.show_cursor_names(cx);
12783            self.buffer.update(cx, |buffer, cx| {
12784                buffer.finalize_last_transaction(cx);
12785                if self.leader_peer_id.is_none() {
12786                    buffer.set_active_selections(
12787                        &self.selections.disjoint_anchors(),
12788                        self.selections.line_mode,
12789                        self.cursor_shape,
12790                        cx,
12791                    );
12792                }
12793            });
12794        }
12795    }
12796
12797    fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12798        cx.emit(EditorEvent::FocusedIn)
12799    }
12800
12801    fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12802        if event.blurred != self.focus_handle {
12803            self.last_focused_descendant = Some(event.blurred);
12804        }
12805    }
12806
12807    pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12808        self.blink_manager.update(cx, BlinkManager::disable);
12809        self.buffer
12810            .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12811
12812        if let Some(blame) = self.blame.as_ref() {
12813            blame.update(cx, GitBlame::blur)
12814        }
12815        if !self.hover_state.focused(cx) {
12816            hide_hover(self, cx);
12817        }
12818
12819        self.hide_context_menu(cx);
12820        cx.emit(EditorEvent::Blurred);
12821        cx.notify();
12822    }
12823
12824    pub fn register_action<A: Action>(
12825        &mut self,
12826        listener: impl Fn(&A, &mut WindowContext) + 'static,
12827    ) -> Subscription {
12828        let id = self.next_editor_action_id.post_inc();
12829        let listener = Arc::new(listener);
12830        self.editor_actions.borrow_mut().insert(
12831            id,
12832            Box::new(move |cx| {
12833                let cx = cx.window_context();
12834                let listener = listener.clone();
12835                cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12836                    let action = action.downcast_ref().unwrap();
12837                    if phase == DispatchPhase::Bubble {
12838                        listener(action, cx)
12839                    }
12840                })
12841            }),
12842        );
12843
12844        let editor_actions = self.editor_actions.clone();
12845        Subscription::new(move || {
12846            editor_actions.borrow_mut().remove(&id);
12847        })
12848    }
12849
12850    pub fn file_header_size(&self) -> u32 {
12851        FILE_HEADER_HEIGHT
12852    }
12853
12854    pub fn revert(
12855        &mut self,
12856        revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12857        cx: &mut ViewContext<Self>,
12858    ) {
12859        self.buffer().update(cx, |multi_buffer, cx| {
12860            for (buffer_id, changes) in revert_changes {
12861                if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12862                    buffer.update(cx, |buffer, cx| {
12863                        buffer.edit(
12864                            changes.into_iter().map(|(range, text)| {
12865                                (range, text.to_string().map(Arc::<str>::from))
12866                            }),
12867                            None,
12868                            cx,
12869                        );
12870                    });
12871                }
12872            }
12873        });
12874        self.change_selections(None, cx, |selections| selections.refresh());
12875    }
12876
12877    pub fn to_pixel_point(
12878        &mut self,
12879        source: multi_buffer::Anchor,
12880        editor_snapshot: &EditorSnapshot,
12881        cx: &mut ViewContext<Self>,
12882    ) -> Option<gpui::Point<Pixels>> {
12883        let source_point = source.to_display_point(editor_snapshot);
12884        self.display_to_pixel_point(source_point, editor_snapshot, cx)
12885    }
12886
12887    pub fn display_to_pixel_point(
12888        &self,
12889        source: DisplayPoint,
12890        editor_snapshot: &EditorSnapshot,
12891        cx: &WindowContext,
12892    ) -> Option<gpui::Point<Pixels>> {
12893        let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12894        let text_layout_details = self.text_layout_details(cx);
12895        let scroll_top = text_layout_details
12896            .scroll_anchor
12897            .scroll_position(editor_snapshot)
12898            .y;
12899
12900        if source.row().as_f32() < scroll_top.floor() {
12901            return None;
12902        }
12903        let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12904        let source_y = line_height * (source.row().as_f32() - scroll_top);
12905        Some(gpui::Point::new(source_x, source_y))
12906    }
12907
12908    pub fn has_active_completions_menu(&self) -> bool {
12909        self.context_menu.borrow().as_ref().map_or(false, |menu| {
12910            menu.visible() && matches!(menu, CodeContextMenu::Completions(_))
12911        })
12912    }
12913
12914    pub fn register_addon<T: Addon>(&mut self, instance: T) {
12915        self.addons
12916            .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12917    }
12918
12919    pub fn unregister_addon<T: Addon>(&mut self) {
12920        self.addons.remove(&std::any::TypeId::of::<T>());
12921    }
12922
12923    pub fn addon<T: Addon>(&self) -> Option<&T> {
12924        let type_id = std::any::TypeId::of::<T>();
12925        self.addons
12926            .get(&type_id)
12927            .and_then(|item| item.to_any().downcast_ref::<T>())
12928    }
12929
12930    fn character_size(&self, cx: &mut ViewContext<Self>) -> gpui::Point<Pixels> {
12931        let text_layout_details = self.text_layout_details(cx);
12932        let style = &text_layout_details.editor_style;
12933        let font_id = cx.text_system().resolve_font(&style.text.font());
12934        let font_size = style.text.font_size.to_pixels(cx.rem_size());
12935        let line_height = style.text.line_height_in_pixels(cx.rem_size());
12936
12937        let em_width = cx
12938            .text_system()
12939            .typographic_bounds(font_id, font_size, 'm')
12940            .unwrap()
12941            .size
12942            .width;
12943
12944        gpui::Point::new(em_width, line_height)
12945    }
12946}
12947
12948fn get_unstaged_changes_for_buffers(
12949    project: &Model<Project>,
12950    buffers: impl IntoIterator<Item = Model<Buffer>>,
12951    cx: &mut ViewContext<Editor>,
12952) {
12953    let mut tasks = Vec::new();
12954    project.update(cx, |project, cx| {
12955        for buffer in buffers {
12956            tasks.push(project.open_unstaged_changes(buffer.clone(), cx))
12957        }
12958    });
12959    cx.spawn(|this, mut cx| async move {
12960        let change_sets = futures::future::join_all(tasks).await;
12961        this.update(&mut cx, |this, cx| {
12962            for change_set in change_sets {
12963                if let Some(change_set) = change_set.log_err() {
12964                    this.diff_map.add_change_set(change_set, cx);
12965                }
12966            }
12967        })
12968        .ok();
12969    })
12970    .detach();
12971}
12972
12973fn char_len_with_expanded_tabs(offset: usize, text: &str, tab_size: NonZeroU32) -> usize {
12974    let tab_size = tab_size.get() as usize;
12975    let mut width = offset;
12976
12977    for ch in text.chars() {
12978        width += if ch == '\t' {
12979            tab_size - (width % tab_size)
12980        } else {
12981            1
12982        };
12983    }
12984
12985    width - offset
12986}
12987
12988#[cfg(test)]
12989mod tests {
12990    use super::*;
12991
12992    #[test]
12993    fn test_string_size_with_expanded_tabs() {
12994        let nz = |val| NonZeroU32::new(val).unwrap();
12995        assert_eq!(char_len_with_expanded_tabs(0, "", nz(4)), 0);
12996        assert_eq!(char_len_with_expanded_tabs(0, "hello", nz(4)), 5);
12997        assert_eq!(char_len_with_expanded_tabs(0, "\thello", nz(4)), 9);
12998        assert_eq!(char_len_with_expanded_tabs(0, "abc\tab", nz(4)), 6);
12999        assert_eq!(char_len_with_expanded_tabs(0, "hello\t", nz(4)), 8);
13000        assert_eq!(char_len_with_expanded_tabs(0, "\t\t", nz(8)), 16);
13001        assert_eq!(char_len_with_expanded_tabs(0, "x\t", nz(8)), 8);
13002        assert_eq!(char_len_with_expanded_tabs(7, "x\t", nz(8)), 9);
13003    }
13004}
13005
13006/// Tokenizes a string into runs of text that should stick together, or that is whitespace.
13007struct WordBreakingTokenizer<'a> {
13008    input: &'a str,
13009}
13010
13011impl<'a> WordBreakingTokenizer<'a> {
13012    fn new(input: &'a str) -> Self {
13013        Self { input }
13014    }
13015}
13016
13017fn is_char_ideographic(ch: char) -> bool {
13018    use unicode_script::Script::*;
13019    use unicode_script::UnicodeScript;
13020    matches!(ch.script(), Han | Tangut | Yi)
13021}
13022
13023fn is_grapheme_ideographic(text: &str) -> bool {
13024    text.chars().any(is_char_ideographic)
13025}
13026
13027fn is_grapheme_whitespace(text: &str) -> bool {
13028    text.chars().any(|x| x.is_whitespace())
13029}
13030
13031fn should_stay_with_preceding_ideograph(text: &str) -> bool {
13032    text.chars().next().map_or(false, |ch| {
13033        matches!(ch, '。' | '、' | ',' | '?' | '!' | ':' | ';' | '…')
13034    })
13035}
13036
13037#[derive(PartialEq, Eq, Debug, Clone, Copy)]
13038struct WordBreakToken<'a> {
13039    token: &'a str,
13040    grapheme_len: usize,
13041    is_whitespace: bool,
13042}
13043
13044impl<'a> Iterator for WordBreakingTokenizer<'a> {
13045    /// Yields a span, the count of graphemes in the token, and whether it was
13046    /// whitespace. Note that it also breaks at word boundaries.
13047    type Item = WordBreakToken<'a>;
13048
13049    fn next(&mut self) -> Option<Self::Item> {
13050        use unicode_segmentation::UnicodeSegmentation;
13051        if self.input.is_empty() {
13052            return None;
13053        }
13054
13055        let mut iter = self.input.graphemes(true).peekable();
13056        let mut offset = 0;
13057        let mut graphemes = 0;
13058        if let Some(first_grapheme) = iter.next() {
13059            let is_whitespace = is_grapheme_whitespace(first_grapheme);
13060            offset += first_grapheme.len();
13061            graphemes += 1;
13062            if is_grapheme_ideographic(first_grapheme) && !is_whitespace {
13063                if let Some(grapheme) = iter.peek().copied() {
13064                    if should_stay_with_preceding_ideograph(grapheme) {
13065                        offset += grapheme.len();
13066                        graphemes += 1;
13067                    }
13068                }
13069            } else {
13070                let mut words = self.input[offset..].split_word_bound_indices().peekable();
13071                let mut next_word_bound = words.peek().copied();
13072                if next_word_bound.map_or(false, |(i, _)| i == 0) {
13073                    next_word_bound = words.next();
13074                }
13075                while let Some(grapheme) = iter.peek().copied() {
13076                    if next_word_bound.map_or(false, |(i, _)| i == offset) {
13077                        break;
13078                    };
13079                    if is_grapheme_whitespace(grapheme) != is_whitespace {
13080                        break;
13081                    };
13082                    offset += grapheme.len();
13083                    graphemes += 1;
13084                    iter.next();
13085                }
13086            }
13087            let token = &self.input[..offset];
13088            self.input = &self.input[offset..];
13089            if is_whitespace {
13090                Some(WordBreakToken {
13091                    token: " ",
13092                    grapheme_len: 1,
13093                    is_whitespace: true,
13094                })
13095            } else {
13096                Some(WordBreakToken {
13097                    token,
13098                    grapheme_len: graphemes,
13099                    is_whitespace: false,
13100                })
13101            }
13102        } else {
13103            None
13104        }
13105    }
13106}
13107
13108#[test]
13109fn test_word_breaking_tokenizer() {
13110    let tests: &[(&str, &[(&str, usize, bool)])] = &[
13111        ("", &[]),
13112        ("  ", &[(" ", 1, true)]),
13113        ("Ʒ", &[("Ʒ", 1, false)]),
13114        ("Ǽ", &[("Ǽ", 1, false)]),
13115        ("", &[("", 1, false)]),
13116        ("⋑⋑", &[("⋑⋑", 2, false)]),
13117        (
13118            "原理,进而",
13119            &[
13120                ("", 1, false),
13121                ("理,", 2, false),
13122                ("", 1, false),
13123                ("", 1, false),
13124            ],
13125        ),
13126        (
13127            "hello world",
13128            &[("hello", 5, false), (" ", 1, true), ("world", 5, false)],
13129        ),
13130        (
13131            "hello, world",
13132            &[("hello,", 6, false), (" ", 1, true), ("world", 5, false)],
13133        ),
13134        (
13135            "  hello world",
13136            &[
13137                (" ", 1, true),
13138                ("hello", 5, false),
13139                (" ", 1, true),
13140                ("world", 5, false),
13141            ],
13142        ),
13143        (
13144            "这是什么 \n 钢笔",
13145            &[
13146                ("", 1, false),
13147                ("", 1, false),
13148                ("", 1, false),
13149                ("", 1, false),
13150                (" ", 1, true),
13151                ("", 1, false),
13152                ("", 1, false),
13153            ],
13154        ),
13155        (" mutton", &[(" ", 1, true), ("mutton", 6, false)]),
13156    ];
13157
13158    for (input, result) in tests {
13159        assert_eq!(
13160            WordBreakingTokenizer::new(input).collect::<Vec<_>>(),
13161            result
13162                .iter()
13163                .copied()
13164                .map(|(token, grapheme_len, is_whitespace)| WordBreakToken {
13165                    token,
13166                    grapheme_len,
13167                    is_whitespace,
13168                })
13169                .collect::<Vec<_>>()
13170        );
13171    }
13172}
13173
13174fn wrap_with_prefix(
13175    line_prefix: String,
13176    unwrapped_text: String,
13177    wrap_column: usize,
13178    tab_size: NonZeroU32,
13179) -> String {
13180    let line_prefix_len = char_len_with_expanded_tabs(0, &line_prefix, tab_size);
13181    let mut wrapped_text = String::new();
13182    let mut current_line = line_prefix.clone();
13183
13184    let tokenizer = WordBreakingTokenizer::new(&unwrapped_text);
13185    let mut current_line_len = line_prefix_len;
13186    for WordBreakToken {
13187        token,
13188        grapheme_len,
13189        is_whitespace,
13190    } in tokenizer
13191    {
13192        if current_line_len + grapheme_len > wrap_column && current_line_len != line_prefix_len {
13193            wrapped_text.push_str(current_line.trim_end());
13194            wrapped_text.push('\n');
13195            current_line.truncate(line_prefix.len());
13196            current_line_len = line_prefix_len;
13197            if !is_whitespace {
13198                current_line.push_str(token);
13199                current_line_len += grapheme_len;
13200            }
13201        } else if !is_whitespace {
13202            current_line.push_str(token);
13203            current_line_len += grapheme_len;
13204        } else if current_line_len != line_prefix_len {
13205            current_line.push(' ');
13206            current_line_len += 1;
13207        }
13208    }
13209
13210    if !current_line.is_empty() {
13211        wrapped_text.push_str(&current_line);
13212    }
13213    wrapped_text
13214}
13215
13216#[test]
13217fn test_wrap_with_prefix() {
13218    assert_eq!(
13219        wrap_with_prefix(
13220            "# ".to_string(),
13221            "abcdefg".to_string(),
13222            4,
13223            NonZeroU32::new(4).unwrap()
13224        ),
13225        "# abcdefg"
13226    );
13227    assert_eq!(
13228        wrap_with_prefix(
13229            "".to_string(),
13230            "\thello world".to_string(),
13231            8,
13232            NonZeroU32::new(4).unwrap()
13233        ),
13234        "hello\nworld"
13235    );
13236    assert_eq!(
13237        wrap_with_prefix(
13238            "// ".to_string(),
13239            "xx \nyy zz aa bb cc".to_string(),
13240            12,
13241            NonZeroU32::new(4).unwrap()
13242        ),
13243        "// xx yy zz\n// aa bb cc"
13244    );
13245    assert_eq!(
13246        wrap_with_prefix(
13247            String::new(),
13248            "这是什么 \n 钢笔".to_string(),
13249            3,
13250            NonZeroU32::new(4).unwrap()
13251        ),
13252        "这是什\n么 钢\n"
13253    );
13254}
13255
13256fn hunks_for_selections(
13257    snapshot: &EditorSnapshot,
13258    selections: &[Selection<Point>],
13259) -> Vec<MultiBufferDiffHunk> {
13260    hunks_for_ranges(
13261        selections.iter().map(|selection| selection.range()),
13262        snapshot,
13263    )
13264}
13265
13266pub fn hunks_for_ranges(
13267    ranges: impl Iterator<Item = Range<Point>>,
13268    snapshot: &EditorSnapshot,
13269) -> Vec<MultiBufferDiffHunk> {
13270    let mut hunks = Vec::new();
13271    let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
13272        HashMap::default();
13273    for query_range in ranges {
13274        let query_rows =
13275            MultiBufferRow(query_range.start.row)..MultiBufferRow(query_range.end.row + 1);
13276        for hunk in snapshot.diff_map.diff_hunks_in_range(
13277            Point::new(query_rows.start.0, 0)..Point::new(query_rows.end.0, 0),
13278            &snapshot.buffer_snapshot,
13279        ) {
13280            // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
13281            // when the caret is just above or just below the deleted hunk.
13282            let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
13283            let related_to_selection = if allow_adjacent {
13284                hunk.row_range.overlaps(&query_rows)
13285                    || hunk.row_range.start == query_rows.end
13286                    || hunk.row_range.end == query_rows.start
13287            } else {
13288                hunk.row_range.overlaps(&query_rows)
13289            };
13290            if related_to_selection {
13291                if !processed_buffer_rows
13292                    .entry(hunk.buffer_id)
13293                    .or_default()
13294                    .insert(hunk.buffer_range.start..hunk.buffer_range.end)
13295                {
13296                    continue;
13297                }
13298                hunks.push(hunk);
13299            }
13300        }
13301    }
13302
13303    hunks
13304}
13305
13306pub trait CollaborationHub {
13307    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
13308    fn user_participant_indices<'a>(
13309        &self,
13310        cx: &'a AppContext,
13311    ) -> &'a HashMap<u64, ParticipantIndex>;
13312    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
13313}
13314
13315impl CollaborationHub for Model<Project> {
13316    fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
13317        self.read(cx).collaborators()
13318    }
13319
13320    fn user_participant_indices<'a>(
13321        &self,
13322        cx: &'a AppContext,
13323    ) -> &'a HashMap<u64, ParticipantIndex> {
13324        self.read(cx).user_store().read(cx).participant_indices()
13325    }
13326
13327    fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
13328        let this = self.read(cx);
13329        let user_ids = this.collaborators().values().map(|c| c.user_id);
13330        this.user_store().read_with(cx, |user_store, cx| {
13331            user_store.participant_names(user_ids, cx)
13332        })
13333    }
13334}
13335
13336pub trait SemanticsProvider {
13337    fn hover(
13338        &self,
13339        buffer: &Model<Buffer>,
13340        position: text::Anchor,
13341        cx: &mut AppContext,
13342    ) -> Option<Task<Vec<project::Hover>>>;
13343
13344    fn inlay_hints(
13345        &self,
13346        buffer_handle: Model<Buffer>,
13347        range: Range<text::Anchor>,
13348        cx: &mut AppContext,
13349    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
13350
13351    fn resolve_inlay_hint(
13352        &self,
13353        hint: InlayHint,
13354        buffer_handle: Model<Buffer>,
13355        server_id: LanguageServerId,
13356        cx: &mut AppContext,
13357    ) -> Option<Task<anyhow::Result<InlayHint>>>;
13358
13359    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13360
13361    fn document_highlights(
13362        &self,
13363        buffer: &Model<Buffer>,
13364        position: text::Anchor,
13365        cx: &mut AppContext,
13366    ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13367
13368    fn definitions(
13369        &self,
13370        buffer: &Model<Buffer>,
13371        position: text::Anchor,
13372        kind: GotoDefinitionKind,
13373        cx: &mut AppContext,
13374    ) -> Option<Task<Result<Vec<LocationLink>>>>;
13375
13376    fn range_for_rename(
13377        &self,
13378        buffer: &Model<Buffer>,
13379        position: text::Anchor,
13380        cx: &mut AppContext,
13381    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13382
13383    fn perform_rename(
13384        &self,
13385        buffer: &Model<Buffer>,
13386        position: text::Anchor,
13387        new_name: String,
13388        cx: &mut AppContext,
13389    ) -> Option<Task<Result<ProjectTransaction>>>;
13390}
13391
13392pub trait CompletionProvider {
13393    fn completions(
13394        &self,
13395        buffer: &Model<Buffer>,
13396        buffer_position: text::Anchor,
13397        trigger: CompletionContext,
13398        cx: &mut ViewContext<Editor>,
13399    ) -> Task<Result<Vec<Completion>>>;
13400
13401    fn resolve_completions(
13402        &self,
13403        buffer: Model<Buffer>,
13404        completion_indices: Vec<usize>,
13405        completions: Rc<RefCell<Box<[Completion]>>>,
13406        cx: &mut ViewContext<Editor>,
13407    ) -> Task<Result<bool>>;
13408
13409    fn apply_additional_edits_for_completion(
13410        &self,
13411        buffer: Model<Buffer>,
13412        completion: Completion,
13413        push_to_history: bool,
13414        cx: &mut ViewContext<Editor>,
13415    ) -> Task<Result<Option<language::Transaction>>>;
13416
13417    fn is_completion_trigger(
13418        &self,
13419        buffer: &Model<Buffer>,
13420        position: language::Anchor,
13421        text: &str,
13422        trigger_in_words: bool,
13423        cx: &mut ViewContext<Editor>,
13424    ) -> bool;
13425
13426    fn sort_completions(&self) -> bool {
13427        true
13428    }
13429}
13430
13431pub trait CodeActionProvider {
13432    fn code_actions(
13433        &self,
13434        buffer: &Model<Buffer>,
13435        range: Range<text::Anchor>,
13436        cx: &mut WindowContext,
13437    ) -> Task<Result<Vec<CodeAction>>>;
13438
13439    fn apply_code_action(
13440        &self,
13441        buffer_handle: Model<Buffer>,
13442        action: CodeAction,
13443        excerpt_id: ExcerptId,
13444        push_to_history: bool,
13445        cx: &mut WindowContext,
13446    ) -> Task<Result<ProjectTransaction>>;
13447}
13448
13449impl CodeActionProvider for Model<Project> {
13450    fn code_actions(
13451        &self,
13452        buffer: &Model<Buffer>,
13453        range: Range<text::Anchor>,
13454        cx: &mut WindowContext,
13455    ) -> Task<Result<Vec<CodeAction>>> {
13456        self.update(cx, |project, cx| {
13457            project.code_actions(buffer, range, None, cx)
13458        })
13459    }
13460
13461    fn apply_code_action(
13462        &self,
13463        buffer_handle: Model<Buffer>,
13464        action: CodeAction,
13465        _excerpt_id: ExcerptId,
13466        push_to_history: bool,
13467        cx: &mut WindowContext,
13468    ) -> Task<Result<ProjectTransaction>> {
13469        self.update(cx, |project, cx| {
13470            project.apply_code_action(buffer_handle, action, push_to_history, cx)
13471        })
13472    }
13473}
13474
13475fn snippet_completions(
13476    project: &Project,
13477    buffer: &Model<Buffer>,
13478    buffer_position: text::Anchor,
13479    cx: &mut AppContext,
13480) -> Task<Result<Vec<Completion>>> {
13481    let language = buffer.read(cx).language_at(buffer_position);
13482    let language_name = language.as_ref().map(|language| language.lsp_id());
13483    let snippet_store = project.snippets().read(cx);
13484    let snippets = snippet_store.snippets_for(language_name, cx);
13485
13486    if snippets.is_empty() {
13487        return Task::ready(Ok(vec![]));
13488    }
13489    let snapshot = buffer.read(cx).text_snapshot();
13490    let chars: String = snapshot
13491        .reversed_chars_for_range(text::Anchor::MIN..buffer_position)
13492        .collect();
13493
13494    let scope = language.map(|language| language.default_scope());
13495    let executor = cx.background_executor().clone();
13496
13497    cx.background_executor().spawn(async move {
13498        let classifier = CharClassifier::new(scope).for_completion(true);
13499        let mut last_word = chars
13500            .chars()
13501            .take_while(|c| classifier.is_word(*c))
13502            .collect::<String>();
13503        last_word = last_word.chars().rev().collect();
13504
13505        if last_word.is_empty() {
13506            return Ok(vec![]);
13507        }
13508
13509        let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13510        let to_lsp = |point: &text::Anchor| {
13511            let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13512            point_to_lsp(end)
13513        };
13514        let lsp_end = to_lsp(&buffer_position);
13515
13516        let candidates = snippets
13517            .iter()
13518            .enumerate()
13519            .flat_map(|(ix, snippet)| {
13520                snippet
13521                    .prefix
13522                    .iter()
13523                    .map(move |prefix| StringMatchCandidate::new(ix, &prefix))
13524            })
13525            .collect::<Vec<StringMatchCandidate>>();
13526
13527        let mut matches = fuzzy::match_strings(
13528            &candidates,
13529            &last_word,
13530            last_word.chars().any(|c| c.is_uppercase()),
13531            100,
13532            &Default::default(),
13533            executor,
13534        )
13535        .await;
13536
13537        // Remove all candidates where the query's start does not match the start of any word in the candidate
13538        if let Some(query_start) = last_word.chars().next() {
13539            matches.retain(|string_match| {
13540                split_words(&string_match.string).any(|word| {
13541                    // Check that the first codepoint of the word as lowercase matches the first
13542                    // codepoint of the query as lowercase
13543                    word.chars()
13544                        .flat_map(|codepoint| codepoint.to_lowercase())
13545                        .zip(query_start.to_lowercase())
13546                        .all(|(word_cp, query_cp)| word_cp == query_cp)
13547                })
13548            });
13549        }
13550
13551        let matched_strings = matches
13552            .into_iter()
13553            .map(|m| m.string)
13554            .collect::<HashSet<_>>();
13555
13556        let result: Vec<Completion> = snippets
13557            .into_iter()
13558            .filter_map(|snippet| {
13559                let matching_prefix = snippet
13560                    .prefix
13561                    .iter()
13562                    .find(|prefix| matched_strings.contains(*prefix))?;
13563                let start = as_offset - last_word.len();
13564                let start = snapshot.anchor_before(start);
13565                let range = start..buffer_position;
13566                let lsp_start = to_lsp(&start);
13567                let lsp_range = lsp::Range {
13568                    start: lsp_start,
13569                    end: lsp_end,
13570                };
13571                Some(Completion {
13572                    old_range: range,
13573                    new_text: snippet.body.clone(),
13574                    label: CodeLabel {
13575                        text: matching_prefix.clone(),
13576                        runs: vec![],
13577                        filter_range: 0..matching_prefix.len(),
13578                    },
13579                    server_id: LanguageServerId(usize::MAX),
13580                    documentation: snippet.description.clone().map(Documentation::SingleLine),
13581                    lsp_completion: lsp::CompletionItem {
13582                        label: snippet.prefix.first().unwrap().clone(),
13583                        kind: Some(CompletionItemKind::SNIPPET),
13584                        label_details: snippet.description.as_ref().map(|description| {
13585                            lsp::CompletionItemLabelDetails {
13586                                detail: Some(description.clone()),
13587                                description: None,
13588                            }
13589                        }),
13590                        insert_text_format: Some(InsertTextFormat::SNIPPET),
13591                        text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13592                            lsp::InsertReplaceEdit {
13593                                new_text: snippet.body.clone(),
13594                                insert: lsp_range,
13595                                replace: lsp_range,
13596                            },
13597                        )),
13598                        filter_text: Some(snippet.body.clone()),
13599                        sort_text: Some(char::MAX.to_string()),
13600                        ..Default::default()
13601                    },
13602                    confirm: None,
13603                })
13604            })
13605            .collect();
13606
13607        Ok(result)
13608    })
13609}
13610
13611impl CompletionProvider for Model<Project> {
13612    fn completions(
13613        &self,
13614        buffer: &Model<Buffer>,
13615        buffer_position: text::Anchor,
13616        options: CompletionContext,
13617        cx: &mut ViewContext<Editor>,
13618    ) -> Task<Result<Vec<Completion>>> {
13619        self.update(cx, |project, cx| {
13620            let snippets = snippet_completions(project, buffer, buffer_position, cx);
13621            let project_completions = project.completions(buffer, buffer_position, options, cx);
13622            cx.background_executor().spawn(async move {
13623                let mut completions = project_completions.await?;
13624                let snippets_completions = snippets.await?;
13625                completions.extend(snippets_completions);
13626                Ok(completions)
13627            })
13628        })
13629    }
13630
13631    fn resolve_completions(
13632        &self,
13633        buffer: Model<Buffer>,
13634        completion_indices: Vec<usize>,
13635        completions: Rc<RefCell<Box<[Completion]>>>,
13636        cx: &mut ViewContext<Editor>,
13637    ) -> Task<Result<bool>> {
13638        self.update(cx, |project, cx| {
13639            project.resolve_completions(buffer, completion_indices, completions, cx)
13640        })
13641    }
13642
13643    fn apply_additional_edits_for_completion(
13644        &self,
13645        buffer: Model<Buffer>,
13646        completion: Completion,
13647        push_to_history: bool,
13648        cx: &mut ViewContext<Editor>,
13649    ) -> Task<Result<Option<language::Transaction>>> {
13650        self.update(cx, |project, cx| {
13651            project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13652        })
13653    }
13654
13655    fn is_completion_trigger(
13656        &self,
13657        buffer: &Model<Buffer>,
13658        position: language::Anchor,
13659        text: &str,
13660        trigger_in_words: bool,
13661        cx: &mut ViewContext<Editor>,
13662    ) -> bool {
13663        let mut chars = text.chars();
13664        let char = if let Some(char) = chars.next() {
13665            char
13666        } else {
13667            return false;
13668        };
13669        if chars.next().is_some() {
13670            return false;
13671        }
13672
13673        let buffer = buffer.read(cx);
13674        let snapshot = buffer.snapshot();
13675        if !snapshot.settings_at(position, cx).show_completions_on_input {
13676            return false;
13677        }
13678        let classifier = snapshot.char_classifier_at(position).for_completion(true);
13679        if trigger_in_words && classifier.is_word(char) {
13680            return true;
13681        }
13682
13683        buffer.completion_triggers().contains(text)
13684    }
13685}
13686
13687impl SemanticsProvider for Model<Project> {
13688    fn hover(
13689        &self,
13690        buffer: &Model<Buffer>,
13691        position: text::Anchor,
13692        cx: &mut AppContext,
13693    ) -> Option<Task<Vec<project::Hover>>> {
13694        Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13695    }
13696
13697    fn document_highlights(
13698        &self,
13699        buffer: &Model<Buffer>,
13700        position: text::Anchor,
13701        cx: &mut AppContext,
13702    ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13703        Some(self.update(cx, |project, cx| {
13704            project.document_highlights(buffer, position, cx)
13705        }))
13706    }
13707
13708    fn definitions(
13709        &self,
13710        buffer: &Model<Buffer>,
13711        position: text::Anchor,
13712        kind: GotoDefinitionKind,
13713        cx: &mut AppContext,
13714    ) -> Option<Task<Result<Vec<LocationLink>>>> {
13715        Some(self.update(cx, |project, cx| match kind {
13716            GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13717            GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13718            GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13719            GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13720        }))
13721    }
13722
13723    fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13724        // TODO: make this work for remote projects
13725        self.read(cx)
13726            .language_servers_for_local_buffer(buffer.read(cx), cx)
13727            .any(
13728                |(_, server)| match server.capabilities().inlay_hint_provider {
13729                    Some(lsp::OneOf::Left(enabled)) => enabled,
13730                    Some(lsp::OneOf::Right(_)) => true,
13731                    None => false,
13732                },
13733            )
13734    }
13735
13736    fn inlay_hints(
13737        &self,
13738        buffer_handle: Model<Buffer>,
13739        range: Range<text::Anchor>,
13740        cx: &mut AppContext,
13741    ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13742        Some(self.update(cx, |project, cx| {
13743            project.inlay_hints(buffer_handle, range, cx)
13744        }))
13745    }
13746
13747    fn resolve_inlay_hint(
13748        &self,
13749        hint: InlayHint,
13750        buffer_handle: Model<Buffer>,
13751        server_id: LanguageServerId,
13752        cx: &mut AppContext,
13753    ) -> Option<Task<anyhow::Result<InlayHint>>> {
13754        Some(self.update(cx, |project, cx| {
13755            project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13756        }))
13757    }
13758
13759    fn range_for_rename(
13760        &self,
13761        buffer: &Model<Buffer>,
13762        position: text::Anchor,
13763        cx: &mut AppContext,
13764    ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13765        Some(self.update(cx, |project, cx| {
13766            project.prepare_rename(buffer.clone(), position, cx)
13767        }))
13768    }
13769
13770    fn perform_rename(
13771        &self,
13772        buffer: &Model<Buffer>,
13773        position: text::Anchor,
13774        new_name: String,
13775        cx: &mut AppContext,
13776    ) -> Option<Task<Result<ProjectTransaction>>> {
13777        Some(self.update(cx, |project, cx| {
13778            project.perform_rename(buffer.clone(), position, new_name, cx)
13779        }))
13780    }
13781}
13782
13783fn inlay_hint_settings(
13784    location: Anchor,
13785    snapshot: &MultiBufferSnapshot,
13786    cx: &mut ViewContext<'_, Editor>,
13787) -> InlayHintSettings {
13788    let file = snapshot.file_at(location);
13789    let language = snapshot.language_at(location).map(|l| l.name());
13790    language_settings(language, file, cx).inlay_hints
13791}
13792
13793fn consume_contiguous_rows(
13794    contiguous_row_selections: &mut Vec<Selection<Point>>,
13795    selection: &Selection<Point>,
13796    display_map: &DisplaySnapshot,
13797    selections: &mut Peekable<std::slice::Iter<Selection<Point>>>,
13798) -> (MultiBufferRow, MultiBufferRow) {
13799    contiguous_row_selections.push(selection.clone());
13800    let start_row = MultiBufferRow(selection.start.row);
13801    let mut end_row = ending_row(selection, display_map);
13802
13803    while let Some(next_selection) = selections.peek() {
13804        if next_selection.start.row <= end_row.0 {
13805            end_row = ending_row(next_selection, display_map);
13806            contiguous_row_selections.push(selections.next().unwrap().clone());
13807        } else {
13808            break;
13809        }
13810    }
13811    (start_row, end_row)
13812}
13813
13814fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13815    if next_selection.end.column > 0 || next_selection.is_empty() {
13816        MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13817    } else {
13818        MultiBufferRow(next_selection.end.row)
13819    }
13820}
13821
13822impl EditorSnapshot {
13823    pub fn remote_selections_in_range<'a>(
13824        &'a self,
13825        range: &'a Range<Anchor>,
13826        collaboration_hub: &dyn CollaborationHub,
13827        cx: &'a AppContext,
13828    ) -> impl 'a + Iterator<Item = RemoteSelection> {
13829        let participant_names = collaboration_hub.user_names(cx);
13830        let participant_indices = collaboration_hub.user_participant_indices(cx);
13831        let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13832        let collaborators_by_replica_id = collaborators_by_peer_id
13833            .iter()
13834            .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13835            .collect::<HashMap<_, _>>();
13836        self.buffer_snapshot
13837            .selections_in_range(range, false)
13838            .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13839                let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13840                let participant_index = participant_indices.get(&collaborator.user_id).copied();
13841                let user_name = participant_names.get(&collaborator.user_id).cloned();
13842                Some(RemoteSelection {
13843                    replica_id,
13844                    selection,
13845                    cursor_shape,
13846                    line_mode,
13847                    participant_index,
13848                    peer_id: collaborator.peer_id,
13849                    user_name,
13850                })
13851            })
13852    }
13853
13854    pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13855        self.display_snapshot.buffer_snapshot.language_at(position)
13856    }
13857
13858    pub fn is_focused(&self) -> bool {
13859        self.is_focused
13860    }
13861
13862    pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13863        self.placeholder_text.as_ref()
13864    }
13865
13866    pub fn scroll_position(&self) -> gpui::Point<f32> {
13867        self.scroll_anchor.scroll_position(&self.display_snapshot)
13868    }
13869
13870    fn gutter_dimensions(
13871        &self,
13872        font_id: FontId,
13873        font_size: Pixels,
13874        em_width: Pixels,
13875        em_advance: Pixels,
13876        max_line_number_width: Pixels,
13877        cx: &AppContext,
13878    ) -> GutterDimensions {
13879        if !self.show_gutter {
13880            return GutterDimensions::default();
13881        }
13882        let descent = cx.text_system().descent(font_id, font_size);
13883
13884        let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13885            matches!(
13886                ProjectSettings::get_global(cx).git.git_gutter,
13887                Some(GitGutterSetting::TrackedFiles)
13888            )
13889        });
13890        let gutter_settings = EditorSettings::get_global(cx).gutter;
13891        let show_line_numbers = self
13892            .show_line_numbers
13893            .unwrap_or(gutter_settings.line_numbers);
13894        let line_gutter_width = if show_line_numbers {
13895            // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13896            let min_width_for_number_on_gutter = em_advance * 4.0;
13897            max_line_number_width.max(min_width_for_number_on_gutter)
13898        } else {
13899            0.0.into()
13900        };
13901
13902        let show_code_actions = self
13903            .show_code_actions
13904            .unwrap_or(gutter_settings.code_actions);
13905
13906        let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13907
13908        let git_blame_entries_width =
13909            self.git_blame_gutter_max_author_length
13910                .map(|max_author_length| {
13911                    // Length of the author name, but also space for the commit hash,
13912                    // the spacing and the timestamp.
13913                    let max_char_count = max_author_length
13914                        .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13915                        + 7 // length of commit sha
13916                        + 14 // length of max relative timestamp ("60 minutes ago")
13917                        + 4; // gaps and margins
13918
13919                    em_advance * max_char_count
13920                });
13921
13922        let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13923        left_padding += if show_code_actions || show_runnables {
13924            em_width * 3.0
13925        } else if show_git_gutter && show_line_numbers {
13926            em_width * 2.0
13927        } else if show_git_gutter || show_line_numbers {
13928            em_width
13929        } else {
13930            px(0.)
13931        };
13932
13933        let right_padding = if gutter_settings.folds && show_line_numbers {
13934            em_width * 4.0
13935        } else if gutter_settings.folds {
13936            em_width * 3.0
13937        } else if show_line_numbers {
13938            em_width
13939        } else {
13940            px(0.)
13941        };
13942
13943        GutterDimensions {
13944            left_padding,
13945            right_padding,
13946            width: line_gutter_width + left_padding + right_padding,
13947            margin: -descent,
13948            git_blame_entries_width,
13949        }
13950    }
13951
13952    pub fn render_crease_toggle(
13953        &self,
13954        buffer_row: MultiBufferRow,
13955        row_contains_cursor: bool,
13956        editor: View<Editor>,
13957        cx: &mut WindowContext,
13958    ) -> Option<AnyElement> {
13959        let folded = self.is_line_folded(buffer_row);
13960        let mut is_foldable = false;
13961
13962        if let Some(crease) = self
13963            .crease_snapshot
13964            .query_row(buffer_row, &self.buffer_snapshot)
13965        {
13966            is_foldable = true;
13967            match crease {
13968                Crease::Inline { render_toggle, .. } | Crease::Block { render_toggle, .. } => {
13969                    if let Some(render_toggle) = render_toggle {
13970                        let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13971                            if folded {
13972                                editor.update(cx, |editor, cx| {
13973                                    editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13974                                });
13975                            } else {
13976                                editor.update(cx, |editor, cx| {
13977                                    editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13978                                });
13979                            }
13980                        });
13981                        return Some((render_toggle)(buffer_row, folded, toggle_callback, cx));
13982                    }
13983                }
13984            }
13985        }
13986
13987        is_foldable |= self.starts_indent(buffer_row);
13988
13989        if folded || (is_foldable && (row_contains_cursor || self.gutter_hovered)) {
13990            Some(
13991                Disclosure::new(("gutter_crease", buffer_row.0), !folded)
13992                    .toggle_state(folded)
13993                    .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13994                        if folded {
13995                            this.unfold_at(&UnfoldAt { buffer_row }, cx);
13996                        } else {
13997                            this.fold_at(&FoldAt { buffer_row }, cx);
13998                        }
13999                    }))
14000                    .into_any_element(),
14001            )
14002        } else {
14003            None
14004        }
14005    }
14006
14007    pub fn render_crease_trailer(
14008        &self,
14009        buffer_row: MultiBufferRow,
14010        cx: &mut WindowContext,
14011    ) -> Option<AnyElement> {
14012        let folded = self.is_line_folded(buffer_row);
14013        if let Crease::Inline { render_trailer, .. } = self
14014            .crease_snapshot
14015            .query_row(buffer_row, &self.buffer_snapshot)?
14016        {
14017            let render_trailer = render_trailer.as_ref()?;
14018            Some(render_trailer(buffer_row, folded, cx))
14019        } else {
14020            None
14021        }
14022    }
14023}
14024
14025impl Deref for EditorSnapshot {
14026    type Target = DisplaySnapshot;
14027
14028    fn deref(&self) -> &Self::Target {
14029        &self.display_snapshot
14030    }
14031}
14032
14033#[derive(Clone, Debug, PartialEq, Eq)]
14034pub enum EditorEvent {
14035    InputIgnored {
14036        text: Arc<str>,
14037    },
14038    InputHandled {
14039        utf16_range_to_replace: Option<Range<isize>>,
14040        text: Arc<str>,
14041    },
14042    ExcerptsAdded {
14043        buffer: Model<Buffer>,
14044        predecessor: ExcerptId,
14045        excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
14046    },
14047    ExcerptsRemoved {
14048        ids: Vec<ExcerptId>,
14049    },
14050    BufferFoldToggled {
14051        ids: Vec<ExcerptId>,
14052        folded: bool,
14053    },
14054    ExcerptsEdited {
14055        ids: Vec<ExcerptId>,
14056    },
14057    ExcerptsExpanded {
14058        ids: Vec<ExcerptId>,
14059    },
14060    BufferEdited,
14061    Edited {
14062        transaction_id: clock::Lamport,
14063    },
14064    Reparsed(BufferId),
14065    Focused,
14066    FocusedIn,
14067    Blurred,
14068    DirtyChanged,
14069    Saved,
14070    TitleChanged,
14071    DiffBaseChanged,
14072    SelectionsChanged {
14073        local: bool,
14074    },
14075    ScrollPositionChanged {
14076        local: bool,
14077        autoscroll: bool,
14078    },
14079    Closed,
14080    TransactionUndone {
14081        transaction_id: clock::Lamport,
14082    },
14083    TransactionBegun {
14084        transaction_id: clock::Lamport,
14085    },
14086    Reloaded,
14087    CursorShapeChanged,
14088}
14089
14090impl EventEmitter<EditorEvent> for Editor {}
14091
14092impl FocusableView for Editor {
14093    fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
14094        self.focus_handle.clone()
14095    }
14096}
14097
14098impl Render for Editor {
14099    fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
14100        let settings = ThemeSettings::get_global(cx);
14101
14102        let mut text_style = match self.mode {
14103            EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
14104                color: cx.theme().colors().editor_foreground,
14105                font_family: settings.ui_font.family.clone(),
14106                font_features: settings.ui_font.features.clone(),
14107                font_fallbacks: settings.ui_font.fallbacks.clone(),
14108                font_size: rems(0.875).into(),
14109                font_weight: settings.ui_font.weight,
14110                line_height: relative(settings.buffer_line_height.value()),
14111                ..Default::default()
14112            },
14113            EditorMode::Full => TextStyle {
14114                color: cx.theme().colors().editor_foreground,
14115                font_family: settings.buffer_font.family.clone(),
14116                font_features: settings.buffer_font.features.clone(),
14117                font_fallbacks: settings.buffer_font.fallbacks.clone(),
14118                font_size: settings.buffer_font_size(cx).into(),
14119                font_weight: settings.buffer_font.weight,
14120                line_height: relative(settings.buffer_line_height.value()),
14121                ..Default::default()
14122            },
14123        };
14124        if let Some(text_style_refinement) = &self.text_style_refinement {
14125            text_style.refine(text_style_refinement)
14126        }
14127
14128        let background = match self.mode {
14129            EditorMode::SingleLine { .. } => cx.theme().system().transparent,
14130            EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
14131            EditorMode::Full => cx.theme().colors().editor_background,
14132        };
14133
14134        EditorElement::new(
14135            cx.view(),
14136            EditorStyle {
14137                background,
14138                local_player: cx.theme().players().local(),
14139                text: text_style,
14140                scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
14141                syntax: cx.theme().syntax().clone(),
14142                status: cx.theme().status().clone(),
14143                inlay_hints_style: make_inlay_hints_style(cx),
14144                inline_completion_styles: make_suggestion_styles(cx),
14145                unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
14146            },
14147        )
14148    }
14149}
14150
14151impl ViewInputHandler for Editor {
14152    fn text_for_range(
14153        &mut self,
14154        range_utf16: Range<usize>,
14155        adjusted_range: &mut Option<Range<usize>>,
14156        cx: &mut ViewContext<Self>,
14157    ) -> Option<String> {
14158        let snapshot = self.buffer.read(cx).read(cx);
14159        let start = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.start), Bias::Left);
14160        let end = snapshot.clip_offset_utf16(OffsetUtf16(range_utf16.end), Bias::Right);
14161        if (start.0..end.0) != range_utf16 {
14162            adjusted_range.replace(start.0..end.0);
14163        }
14164        Some(snapshot.text_for_range(start..end).collect())
14165    }
14166
14167    fn selected_text_range(
14168        &mut self,
14169        ignore_disabled_input: bool,
14170        cx: &mut ViewContext<Self>,
14171    ) -> Option<UTF16Selection> {
14172        // Prevent the IME menu from appearing when holding down an alphabetic key
14173        // while input is disabled.
14174        if !ignore_disabled_input && !self.input_enabled {
14175            return None;
14176        }
14177
14178        let selection = self.selections.newest::<OffsetUtf16>(cx);
14179        let range = selection.range();
14180
14181        Some(UTF16Selection {
14182            range: range.start.0..range.end.0,
14183            reversed: selection.reversed,
14184        })
14185    }
14186
14187    fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
14188        let snapshot = self.buffer.read(cx).read(cx);
14189        let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
14190        Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
14191    }
14192
14193    fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
14194        self.clear_highlights::<InputComposition>(cx);
14195        self.ime_transaction.take();
14196    }
14197
14198    fn replace_text_in_range(
14199        &mut self,
14200        range_utf16: Option<Range<usize>>,
14201        text: &str,
14202        cx: &mut ViewContext<Self>,
14203    ) {
14204        if !self.input_enabled {
14205            cx.emit(EditorEvent::InputIgnored { text: text.into() });
14206            return;
14207        }
14208
14209        self.transact(cx, |this, cx| {
14210            let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
14211                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14212                Some(this.selection_replacement_ranges(range_utf16, cx))
14213            } else {
14214                this.marked_text_ranges(cx)
14215            };
14216
14217            let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
14218                let newest_selection_id = this.selections.newest_anchor().id;
14219                this.selections
14220                    .all::<OffsetUtf16>(cx)
14221                    .iter()
14222                    .zip(ranges_to_replace.iter())
14223                    .find_map(|(selection, range)| {
14224                        if selection.id == newest_selection_id {
14225                            Some(
14226                                (range.start.0 as isize - selection.head().0 as isize)
14227                                    ..(range.end.0 as isize - selection.head().0 as isize),
14228                            )
14229                        } else {
14230                            None
14231                        }
14232                    })
14233            });
14234
14235            cx.emit(EditorEvent::InputHandled {
14236                utf16_range_to_replace: range_to_replace,
14237                text: text.into(),
14238            });
14239
14240            if let Some(new_selected_ranges) = new_selected_ranges {
14241                this.change_selections(None, cx, |selections| {
14242                    selections.select_ranges(new_selected_ranges)
14243                });
14244                this.backspace(&Default::default(), cx);
14245            }
14246
14247            this.handle_input(text, cx);
14248        });
14249
14250        if let Some(transaction) = self.ime_transaction {
14251            self.buffer.update(cx, |buffer, cx| {
14252                buffer.group_until_transaction(transaction, cx);
14253            });
14254        }
14255
14256        self.unmark_text(cx);
14257    }
14258
14259    fn replace_and_mark_text_in_range(
14260        &mut self,
14261        range_utf16: Option<Range<usize>>,
14262        text: &str,
14263        new_selected_range_utf16: Option<Range<usize>>,
14264        cx: &mut ViewContext<Self>,
14265    ) {
14266        if !self.input_enabled {
14267            return;
14268        }
14269
14270        let transaction = self.transact(cx, |this, cx| {
14271            let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
14272                let snapshot = this.buffer.read(cx).read(cx);
14273                if let Some(relative_range_utf16) = range_utf16.as_ref() {
14274                    for marked_range in &mut marked_ranges {
14275                        marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
14276                        marked_range.start.0 += relative_range_utf16.start;
14277                        marked_range.start =
14278                            snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
14279                        marked_range.end =
14280                            snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
14281                    }
14282                }
14283                Some(marked_ranges)
14284            } else if let Some(range_utf16) = range_utf16 {
14285                let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
14286                Some(this.selection_replacement_ranges(range_utf16, cx))
14287            } else {
14288                None
14289            };
14290
14291            let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
14292                let newest_selection_id = this.selections.newest_anchor().id;
14293                this.selections
14294                    .all::<OffsetUtf16>(cx)
14295                    .iter()
14296                    .zip(ranges_to_replace.iter())
14297                    .find_map(|(selection, range)| {
14298                        if selection.id == newest_selection_id {
14299                            Some(
14300                                (range.start.0 as isize - selection.head().0 as isize)
14301                                    ..(range.end.0 as isize - selection.head().0 as isize),
14302                            )
14303                        } else {
14304                            None
14305                        }
14306                    })
14307            });
14308
14309            cx.emit(EditorEvent::InputHandled {
14310                utf16_range_to_replace: range_to_replace,
14311                text: text.into(),
14312            });
14313
14314            if let Some(ranges) = ranges_to_replace {
14315                this.change_selections(None, cx, |s| s.select_ranges(ranges));
14316            }
14317
14318            let marked_ranges = {
14319                let snapshot = this.buffer.read(cx).read(cx);
14320                this.selections
14321                    .disjoint_anchors()
14322                    .iter()
14323                    .map(|selection| {
14324                        selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
14325                    })
14326                    .collect::<Vec<_>>()
14327            };
14328
14329            if text.is_empty() {
14330                this.unmark_text(cx);
14331            } else {
14332                this.highlight_text::<InputComposition>(
14333                    marked_ranges.clone(),
14334                    HighlightStyle {
14335                        underline: Some(UnderlineStyle {
14336                            thickness: px(1.),
14337                            color: None,
14338                            wavy: false,
14339                        }),
14340                        ..Default::default()
14341                    },
14342                    cx,
14343                );
14344            }
14345
14346            // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
14347            let use_autoclose = this.use_autoclose;
14348            let use_auto_surround = this.use_auto_surround;
14349            this.set_use_autoclose(false);
14350            this.set_use_auto_surround(false);
14351            this.handle_input(text, cx);
14352            this.set_use_autoclose(use_autoclose);
14353            this.set_use_auto_surround(use_auto_surround);
14354
14355            if let Some(new_selected_range) = new_selected_range_utf16 {
14356                let snapshot = this.buffer.read(cx).read(cx);
14357                let new_selected_ranges = marked_ranges
14358                    .into_iter()
14359                    .map(|marked_range| {
14360                        let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
14361                        let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
14362                        let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
14363                        snapshot.clip_offset_utf16(new_start, Bias::Left)
14364                            ..snapshot.clip_offset_utf16(new_end, Bias::Right)
14365                    })
14366                    .collect::<Vec<_>>();
14367
14368                drop(snapshot);
14369                this.change_selections(None, cx, |selections| {
14370                    selections.select_ranges(new_selected_ranges)
14371                });
14372            }
14373        });
14374
14375        self.ime_transaction = self.ime_transaction.or(transaction);
14376        if let Some(transaction) = self.ime_transaction {
14377            self.buffer.update(cx, |buffer, cx| {
14378                buffer.group_until_transaction(transaction, cx);
14379            });
14380        }
14381
14382        if self.text_highlights::<InputComposition>(cx).is_none() {
14383            self.ime_transaction.take();
14384        }
14385    }
14386
14387    fn bounds_for_range(
14388        &mut self,
14389        range_utf16: Range<usize>,
14390        element_bounds: gpui::Bounds<Pixels>,
14391        cx: &mut ViewContext<Self>,
14392    ) -> Option<gpui::Bounds<Pixels>> {
14393        let text_layout_details = self.text_layout_details(cx);
14394        let gpui::Point {
14395            x: em_width,
14396            y: line_height,
14397        } = self.character_size(cx);
14398
14399        let snapshot = self.snapshot(cx);
14400        let scroll_position = snapshot.scroll_position();
14401        let scroll_left = scroll_position.x * em_width;
14402
14403        let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
14404        let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
14405            + self.gutter_dimensions.width
14406            + self.gutter_dimensions.margin;
14407        let y = line_height * (start.row().as_f32() - scroll_position.y);
14408
14409        Some(Bounds {
14410            origin: element_bounds.origin + point(x, y),
14411            size: size(em_width, line_height),
14412        })
14413    }
14414}
14415
14416trait SelectionExt {
14417    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14418    fn spanned_rows(
14419        &self,
14420        include_end_if_at_line_start: bool,
14421        map: &DisplaySnapshot,
14422    ) -> Range<MultiBufferRow>;
14423}
14424
14425impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14426    fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14427        let start = self
14428            .start
14429            .to_point(&map.buffer_snapshot)
14430            .to_display_point(map);
14431        let end = self
14432            .end
14433            .to_point(&map.buffer_snapshot)
14434            .to_display_point(map);
14435        if self.reversed {
14436            end..start
14437        } else {
14438            start..end
14439        }
14440    }
14441
14442    fn spanned_rows(
14443        &self,
14444        include_end_if_at_line_start: bool,
14445        map: &DisplaySnapshot,
14446    ) -> Range<MultiBufferRow> {
14447        let start = self.start.to_point(&map.buffer_snapshot);
14448        let mut end = self.end.to_point(&map.buffer_snapshot);
14449        if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14450            end.row -= 1;
14451        }
14452
14453        let buffer_start = map.prev_line_boundary(start).0;
14454        let buffer_end = map.next_line_boundary(end).0;
14455        MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14456    }
14457}
14458
14459impl<T: InvalidationRegion> InvalidationStack<T> {
14460    fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14461    where
14462        S: Clone + ToOffset,
14463    {
14464        while let Some(region) = self.last() {
14465            let all_selections_inside_invalidation_ranges =
14466                if selections.len() == region.ranges().len() {
14467                    selections
14468                        .iter()
14469                        .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14470                        .all(|(selection, invalidation_range)| {
14471                            let head = selection.head().to_offset(buffer);
14472                            invalidation_range.start <= head && invalidation_range.end >= head
14473                        })
14474                } else {
14475                    false
14476                };
14477
14478            if all_selections_inside_invalidation_ranges {
14479                break;
14480            } else {
14481                self.pop();
14482            }
14483        }
14484    }
14485}
14486
14487impl<T> Default for InvalidationStack<T> {
14488    fn default() -> Self {
14489        Self(Default::default())
14490    }
14491}
14492
14493impl<T> Deref for InvalidationStack<T> {
14494    type Target = Vec<T>;
14495
14496    fn deref(&self) -> &Self::Target {
14497        &self.0
14498    }
14499}
14500
14501impl<T> DerefMut for InvalidationStack<T> {
14502    fn deref_mut(&mut self) -> &mut Self::Target {
14503        &mut self.0
14504    }
14505}
14506
14507impl InvalidationRegion for SnippetState {
14508    fn ranges(&self) -> &[Range<Anchor>] {
14509        &self.ranges[self.active_index]
14510    }
14511}
14512
14513pub fn diagnostic_block_renderer(
14514    diagnostic: Diagnostic,
14515    max_message_rows: Option<u8>,
14516    allow_closing: bool,
14517    _is_valid: bool,
14518) -> RenderBlock {
14519    let (text_without_backticks, code_ranges) =
14520        highlight_diagnostic_message(&diagnostic, max_message_rows);
14521
14522    Arc::new(move |cx: &mut BlockContext| {
14523        let group_id: SharedString = cx.block_id.to_string().into();
14524
14525        let mut text_style = cx.text_style().clone();
14526        text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14527        let theme_settings = ThemeSettings::get_global(cx);
14528        text_style.font_family = theme_settings.buffer_font.family.clone();
14529        text_style.font_style = theme_settings.buffer_font.style;
14530        text_style.font_features = theme_settings.buffer_font.features.clone();
14531        text_style.font_weight = theme_settings.buffer_font.weight;
14532
14533        let multi_line_diagnostic = diagnostic.message.contains('\n');
14534
14535        let buttons = |diagnostic: &Diagnostic| {
14536            if multi_line_diagnostic {
14537                v_flex()
14538            } else {
14539                h_flex()
14540            }
14541            .when(allow_closing, |div| {
14542                div.children(diagnostic.is_primary.then(|| {
14543                    IconButton::new("close-block", IconName::XCircle)
14544                        .icon_color(Color::Muted)
14545                        .size(ButtonSize::Compact)
14546                        .style(ButtonStyle::Transparent)
14547                        .visible_on_hover(group_id.clone())
14548                        .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14549                        .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14550                }))
14551            })
14552            .child(
14553                IconButton::new("copy-block", IconName::Copy)
14554                    .icon_color(Color::Muted)
14555                    .size(ButtonSize::Compact)
14556                    .style(ButtonStyle::Transparent)
14557                    .visible_on_hover(group_id.clone())
14558                    .on_click({
14559                        let message = diagnostic.message.clone();
14560                        move |_click, cx| {
14561                            cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14562                        }
14563                    })
14564                    .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14565            )
14566        };
14567
14568        let icon_size = buttons(&diagnostic)
14569            .into_any_element()
14570            .layout_as_root(AvailableSpace::min_size(), cx);
14571
14572        h_flex()
14573            .id(cx.block_id)
14574            .group(group_id.clone())
14575            .relative()
14576            .size_full()
14577            .block_mouse_down()
14578            .pl(cx.gutter_dimensions.width)
14579            .w(cx.max_width - cx.gutter_dimensions.full_width())
14580            .child(
14581                div()
14582                    .flex()
14583                    .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14584                    .flex_shrink(),
14585            )
14586            .child(buttons(&diagnostic))
14587            .child(div().flex().flex_shrink_0().child(
14588                StyledText::new(text_without_backticks.clone()).with_highlights(
14589                    &text_style,
14590                    code_ranges.iter().map(|range| {
14591                        (
14592                            range.clone(),
14593                            HighlightStyle {
14594                                font_weight: Some(FontWeight::BOLD),
14595                                ..Default::default()
14596                            },
14597                        )
14598                    }),
14599                ),
14600            ))
14601            .into_any_element()
14602    })
14603}
14604
14605fn inline_completion_edit_text(
14606    editor_snapshot: &EditorSnapshot,
14607    edits: &Vec<(Range<Anchor>, String)>,
14608    cx: &WindowContext,
14609) -> InlineCompletionText {
14610    let edit_start = edits
14611        .first()
14612        .unwrap()
14613        .0
14614        .start
14615        .to_display_point(editor_snapshot);
14616
14617    let mut text = String::new();
14618    let mut offset = DisplayPoint::new(edit_start.row(), 0).to_offset(editor_snapshot, Bias::Left);
14619    let mut highlights = Vec::new();
14620    for (old_range, new_text) in edits {
14621        let old_offset_range = old_range.to_offset(&editor_snapshot.buffer_snapshot);
14622        text.extend(
14623            editor_snapshot
14624                .buffer_snapshot
14625                .chunks(offset..old_offset_range.start, false)
14626                .map(|chunk| chunk.text),
14627        );
14628        offset = old_offset_range.end;
14629
14630        let start = text.len();
14631        text.push_str(new_text);
14632        let end = text.len();
14633        highlights.push((
14634            start..end,
14635            HighlightStyle {
14636                background_color: Some(cx.theme().status().created_background),
14637                ..Default::default()
14638            },
14639        ));
14640    }
14641
14642    let edit_end = edits
14643        .last()
14644        .unwrap()
14645        .0
14646        .end
14647        .to_display_point(editor_snapshot);
14648    let end_of_line = DisplayPoint::new(edit_end.row(), editor_snapshot.line_len(edit_end.row()))
14649        .to_offset(editor_snapshot, Bias::Right);
14650    text.extend(
14651        editor_snapshot
14652            .buffer_snapshot
14653            .chunks(offset..end_of_line, false)
14654            .map(|chunk| chunk.text),
14655    );
14656
14657    InlineCompletionText::Edit {
14658        text: text.into(),
14659        highlights,
14660    }
14661}
14662
14663pub fn highlight_diagnostic_message(
14664    diagnostic: &Diagnostic,
14665    mut max_message_rows: Option<u8>,
14666) -> (SharedString, Vec<Range<usize>>) {
14667    let mut text_without_backticks = String::new();
14668    let mut code_ranges = Vec::new();
14669
14670    if let Some(source) = &diagnostic.source {
14671        text_without_backticks.push_str(source);
14672        code_ranges.push(0..source.len());
14673        text_without_backticks.push_str(": ");
14674    }
14675
14676    let mut prev_offset = 0;
14677    let mut in_code_block = false;
14678    let has_row_limit = max_message_rows.is_some();
14679    let mut newline_indices = diagnostic
14680        .message
14681        .match_indices('\n')
14682        .filter(|_| has_row_limit)
14683        .map(|(ix, _)| ix)
14684        .fuse()
14685        .peekable();
14686
14687    for (quote_ix, _) in diagnostic
14688        .message
14689        .match_indices('`')
14690        .chain([(diagnostic.message.len(), "")])
14691    {
14692        let mut first_newline_ix = None;
14693        let mut last_newline_ix = None;
14694        while let Some(newline_ix) = newline_indices.peek() {
14695            if *newline_ix < quote_ix {
14696                if first_newline_ix.is_none() {
14697                    first_newline_ix = Some(*newline_ix);
14698                }
14699                last_newline_ix = Some(*newline_ix);
14700
14701                if let Some(rows_left) = &mut max_message_rows {
14702                    if *rows_left == 0 {
14703                        break;
14704                    } else {
14705                        *rows_left -= 1;
14706                    }
14707                }
14708                let _ = newline_indices.next();
14709            } else {
14710                break;
14711            }
14712        }
14713        let prev_len = text_without_backticks.len();
14714        let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14715        text_without_backticks.push_str(new_text);
14716        if in_code_block {
14717            code_ranges.push(prev_len..text_without_backticks.len());
14718        }
14719        prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14720        in_code_block = !in_code_block;
14721        if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14722            text_without_backticks.push_str("...");
14723            break;
14724        }
14725    }
14726
14727    (text_without_backticks.into(), code_ranges)
14728}
14729
14730fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14731    match severity {
14732        DiagnosticSeverity::ERROR => colors.error,
14733        DiagnosticSeverity::WARNING => colors.warning,
14734        DiagnosticSeverity::INFORMATION => colors.info,
14735        DiagnosticSeverity::HINT => colors.info,
14736        _ => colors.ignored,
14737    }
14738}
14739
14740pub fn styled_runs_for_code_label<'a>(
14741    label: &'a CodeLabel,
14742    syntax_theme: &'a theme::SyntaxTheme,
14743) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14744    let fade_out = HighlightStyle {
14745        fade_out: Some(0.35),
14746        ..Default::default()
14747    };
14748
14749    let mut prev_end = label.filter_range.end;
14750    label
14751        .runs
14752        .iter()
14753        .enumerate()
14754        .flat_map(move |(ix, (range, highlight_id))| {
14755            let style = if let Some(style) = highlight_id.style(syntax_theme) {
14756                style
14757            } else {
14758                return Default::default();
14759            };
14760            let mut muted_style = style;
14761            muted_style.highlight(fade_out);
14762
14763            let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14764            if range.start >= label.filter_range.end {
14765                if range.start > prev_end {
14766                    runs.push((prev_end..range.start, fade_out));
14767                }
14768                runs.push((range.clone(), muted_style));
14769            } else if range.end <= label.filter_range.end {
14770                runs.push((range.clone(), style));
14771            } else {
14772                runs.push((range.start..label.filter_range.end, style));
14773                runs.push((label.filter_range.end..range.end, muted_style));
14774            }
14775            prev_end = cmp::max(prev_end, range.end);
14776
14777            if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14778                runs.push((prev_end..label.text.len(), fade_out));
14779            }
14780
14781            runs
14782        })
14783}
14784
14785pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14786    let mut prev_index = 0;
14787    let mut prev_codepoint: Option<char> = None;
14788    text.char_indices()
14789        .chain([(text.len(), '\0')])
14790        .filter_map(move |(index, codepoint)| {
14791            let prev_codepoint = prev_codepoint.replace(codepoint)?;
14792            let is_boundary = index == text.len()
14793                || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14794                || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14795            if is_boundary {
14796                let chunk = &text[prev_index..index];
14797                prev_index = index;
14798                Some(chunk)
14799            } else {
14800                None
14801            }
14802        })
14803}
14804
14805pub trait RangeToAnchorExt: Sized {
14806    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14807
14808    fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14809        let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14810        anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14811    }
14812}
14813
14814impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14815    fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14816        let start_offset = self.start.to_offset(snapshot);
14817        let end_offset = self.end.to_offset(snapshot);
14818        if start_offset == end_offset {
14819            snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14820        } else {
14821            snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14822        }
14823    }
14824}
14825
14826pub trait RowExt {
14827    fn as_f32(&self) -> f32;
14828
14829    fn next_row(&self) -> Self;
14830
14831    fn previous_row(&self) -> Self;
14832
14833    fn minus(&self, other: Self) -> u32;
14834}
14835
14836impl RowExt for DisplayRow {
14837    fn as_f32(&self) -> f32 {
14838        self.0 as f32
14839    }
14840
14841    fn next_row(&self) -> Self {
14842        Self(self.0 + 1)
14843    }
14844
14845    fn previous_row(&self) -> Self {
14846        Self(self.0.saturating_sub(1))
14847    }
14848
14849    fn minus(&self, other: Self) -> u32 {
14850        self.0 - other.0
14851    }
14852}
14853
14854impl RowExt for MultiBufferRow {
14855    fn as_f32(&self) -> f32 {
14856        self.0 as f32
14857    }
14858
14859    fn next_row(&self) -> Self {
14860        Self(self.0 + 1)
14861    }
14862
14863    fn previous_row(&self) -> Self {
14864        Self(self.0.saturating_sub(1))
14865    }
14866
14867    fn minus(&self, other: Self) -> u32 {
14868        self.0 - other.0
14869    }
14870}
14871
14872trait RowRangeExt {
14873    type Row;
14874
14875    fn len(&self) -> usize;
14876
14877    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14878}
14879
14880impl RowRangeExt for Range<MultiBufferRow> {
14881    type Row = MultiBufferRow;
14882
14883    fn len(&self) -> usize {
14884        (self.end.0 - self.start.0) as usize
14885    }
14886
14887    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14888        (self.start.0..self.end.0).map(MultiBufferRow)
14889    }
14890}
14891
14892impl RowRangeExt for Range<DisplayRow> {
14893    type Row = DisplayRow;
14894
14895    fn len(&self) -> usize {
14896        (self.end.0 - self.start.0) as usize
14897    }
14898
14899    fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14900        (self.start.0..self.end.0).map(DisplayRow)
14901    }
14902}
14903
14904fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14905    if hunk.diff_base_byte_range.is_empty() {
14906        DiffHunkStatus::Added
14907    } else if hunk.row_range.is_empty() {
14908        DiffHunkStatus::Removed
14909    } else {
14910        DiffHunkStatus::Modified
14911    }
14912}
14913
14914/// If select range has more than one line, we
14915/// just point the cursor to range.start.
14916fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14917    if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14918        range
14919    } else {
14920        range.start..range.start
14921    }
14922}
14923
14924pub struct KillRing(ClipboardItem);
14925impl Global for KillRing {}
14926
14927const UPDATE_DEBOUNCE: Duration = Duration::from_millis(50);